IBM AS-400e User Manual 2

AS/400e
HTTP Server for AS/400 Web Programming Guide

GC41-5435-04
AS/400e
HTTP Server for AS/400 Web Programming Guide

GC41-5435-04
Note
Before using this information and the product it supports, be sure to read the general information under “Chapter 11. Notices” on page 145.
This edition applies to the IBM HTTP Server for AS/400 licensed program (Program 5769-DG1), Version 4 Release 5 Modification 0 and to all subsequent releases and modifications until otherwise indicated in new editions. This edition applies only to reduced instruction set computer (RISC) systems.
This edition replaces GC41-5435-03.
© Copyright International Business Machines Corporation 1997, 2000. All rights reserved.
US Government Users Restricted Rights – Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.

Contents

About HTTP Server for AS/400 Web
Programming Guide (GC41-5435) ....v
Conventions in this book ..........v
AS/400 Operations Navigator ........v
Installing Operations Navigator .......vi
Prerequisite and related information ......vi
How to send your comments ........vi
Chapter 1. Writing Common Gateway
Interface Programs ..........1
OverviewoftheCGI ...........1
CGI and Dynamic Documents .......2
UsesforCGI.............3
The CGI process .............3
Overview..............3
SendingInformationtotheServer......5
Data Conversions on CGI Input and Output . . . 5
ReturningOutputfromtheServer......11
HowCGIProgramsWork ........12
Environment variables ...........13
Requests from Standard Search (ISINDEX)
Documents.............15
Passing SSL Environment Variables to a CGI
Program..............15
CGI Programs and AS/400 Activation Groups . . . 17
AS/400 Activation Groups ........17
CGIConsiderations...........18
Activation Group Problem Examples .....18
Chapter 2. Application Programming
Interfaces .............23
APIs for CGI applications .........24
Get Environment Variable (QtmhGetEnv) API . . 25
Put Environment Variable (QtmhPutEnv) API . . 26
Read from Stdin (QtmhRdStin) API .....27
Write to Stdout (QtmhWrStout) API .....29
Convert to DB (QtmhCvtDB) API ......30
Parse QUERY_STRING Environment Variable or
Post stdin data (QzhbCgiParse) API .....32
Produce Full HTTP Response (QzhbCgiUtils) API 36
ConfigurationAPIs............38
Convert URL to Path (QzhbCvtURLtoPath) API 38
Retrieve Directive (QzhbRetrieveDirective) API 40
Retreive a list of all Configuration Names
(QzhbGetConfigNames) API ........42
Create a Configuration (QzhbCreateConfig) API 43
Delete a Configuration (QzhbDeleteConfig) API 44
Read a Configuration File into Memory
(QzhbOpenConfig) API .........45
Free a Configuration File from Memory
(QzhbCloseConfig) API .........46
Search for a Main Directive (QzhbFindDirective)
API................47
Search for a Subdirective under Main Directive
(QzhbFindSubdirective) API ........49
Return Details of a Main Directive or Subdirective (QzhbGetDirectiveDetail) API . . . 51 Add a Main Directive or Subdirective
(QzhbAddDirective) API .........52
Remove a Main Directive or Subdirective
(QzhbRemoveDirective) API ........54
Replace a Main Directive or Subdirective
(QzhbReplaceDirective) API ........55
ServerinstanceAPIs...........56
Retrieve a list of all Server Instances
(QzhbGetInstanceNames) API .......56
Look up Server Instance Data
(QzhbGetInstanceData) API ........58
Change Server Instance Data
(QzhbChangeInstanceData) API ......60
Create a Server Instance (QzhbCreateInstance)
API................62
Delete a Server Instance (QzhbDeleteInstance)
API................63
Group file APIs .............64
Create a new Group File (QzhbCreateGroupList)
API................64
Read a Group File into Memory
(QzhbOpenGroupList) API ........65
Free Group File from Memory
(QzhbCloseGroupList) API ........67
Retrieve the next Group in the Group List
(QzhbGetNextGroup) API ........68
Locate a named group in a Group List
(QzhbFindGroupInList) API ........69
Retrieve the Name of a Group
(QzhbGetGroupName) API ........70
Add a new Group to the end of a Group List
(QzhbAddGroupToList) API ........71
Remove a Group from a Group List
(QzhbRemoveGroupFromList) API .....72
Retrieve the next User in the Group
(QzhbGetNextUser) API .........73
Locate a User in a Group
(QzhbFindUserInGroup) API .......74
Retrieve the Name of a User
(QzhbGetUserString) API .........75
Add a new user to the end of a Group
(QzhbAddUserToGroup) API .......76
Remove a User or Element from a Group
(QzhbRemoveUserFromGroup) API .....77
Chapter 3. Using Net.Data to Write CGI
Programs for You ..........79
OverviewofNet.Data...........79
Chapter 4. Using Persistent CGI
Programs .............81
© Copyright IBM Corp. 1997, 2000 iii
Overview of Persistent CGI .........81
Named Activation Groups ........81
Accept-HTSession CGI Header .......81
HTTimeoutCGIHeader.........82
Considerations for using Persistent CGI
Programs..............82
Persistent CGI Program Example ......83
Chapter 5. Enabling your AS/400 to run
CGI programs............85
How to enable the server to run CGI programs . . 85 Using directives for security and access control . . 86
Thedefaultfailrule ..........87
Explicit CGI enablement .........87
ServerrunsonlyCGIprograms.......87
CGIprogramconsiderations.........87
Chapter 6. Sample programs (in Java,
C, and RPG) ............89
Example of Java language CGI program .....89
Example of C language CGI program......94
Example of RPG language CGI program.....99
Example of a C language server configuration API
program...............105
HTTPreturncodesandvalues.......113
Predefined functions and macros ......114
Returncodes ............119
Server API configuration directives ......120
ServerAPIusagenotes.........120
Server API directives and syntax ......120
Server API directive variables .......121
Compatibility with other APIs ........122
Porting CGI programs .........122
Authentication and Authorization .....122
Environment variables .........123
ServerAPIvariables..........124
Chapter 8. Writing Java Servlets . . . 129
Overview of servlets ...........129
Chapter 9. Using Server-Side Includes 131
Considerations for using server-side includes. . . 131
Preparing to use server-side includes .....131
Format for server-side includes .......132
Directives for server-side includes ......132
Chapter 10. Troubleshooting your CGI
programs .............139
Chapter 7. Writing Server API
programs .............109
OverviewoftheServerAPI ........109
General procedure for writing Server API
programs...............109
Guidelines .............109
Basic server request process .......110
Application functions ..........111
Chapter 11. Notices .........145
Programming Interface Information ......146
Trademarks..............146
Readers’ Comments — We’d Like to
Hear from You ...........149
iv
Web Programming Guide V4R5

About HTTP Server for AS/400 Web Programming Guide (GC41-5435)

The web is an interactive medium. For example, it allows users to use search utilities to locate information on a topic, give feedback to a company about its products, and more. The IBM HTTP Server software does not perform these tasks. They are performed by external programs using information passed to them by the server. The HTTP Server for AS/400 Web Programming Guide tells you how to write external programs that interact with the IBM HTTP Server for AS/400 product.
The HTTP Server for AS/400 Webmaster’s Guide, GC41-5434, describes the configuration directives used to set up and control the IBM HTTP Server for AS/400 product.
The IBM AS/400 Information Center presents information about the Web server and many other AS/400 products and topics in an electronic, searchable database format. The Information Center offers assistance in setting up and configuring your Web server and publishing a Web site, as well as the advanced functions such as logging and proxy serving. It is available on the Internet at http://publib.boulder.ibm.com/html/as400/infocenter.html or on CD-ROM: AS/400 Information Center, SK3T-2027-03
The IBM HTTP Server is IBMs web server, and it is a cross platform product. With the IBM HTTP Server you can serve multimedia objects such as Hypertext Markup Language (HTML) documents to World Wide Web browser clients with your AS/400 system. The IBM HTTP Server for AS/400 is fully HTTP 1.1 compliant.
The IBM HTTP Server for AS/400 (that was introduced in V4R3) replaces the IBM AS/400 Internet Connection Server (ICS) introduced in OS/400 V4R1.

Conventions in this book

Boldface Indicates the name of an item you need to select, the name of a field, or a
string you must enter.
Italics Indicates book titles or variable information that must be replaced by an
actual value.
Bold italics Indicates a new term. Monospace Indicates an example, a portion of a file, or a previously entered value.

AS/400 Operations Navigator

AS/400 Operations Navigator is a powerful graphical interface for Windows clients. With AS/400 Operations Navigator, you can manage and administer your AS/400 systems from your Windows desktop.
You can use Operations Navigator to manage communications, printing, database, security, and other system operations. Operations Navigator includes Management Central for managing multiple AS/400 systems centrally.
This new interface has been designed to make you more productive and is the only user interface to new, advanced features of OS/400. Therefore, IBM
© Copyright IBM Corp. 1997, 2000 v
recommends that you use AS/400 Operations Navigator, which has online help to guide you. While this interface is being developed, you may still need to use an emulator such as PC5250 to do some of your tasks.

Installing Operations Navigator

To use AS/400 Operations Navigator, you must have Client Access installed on your Windows PC. For help in connecting your Windows PC to your AS/400 system, consult Client Access Express for Windows - Setup, SC41-5507-01.
AS/400 Operations Navigator is a separately installable component of Client Access that contains many subcomponents. If you are installing for the first time and you use the Typical installation option, the following options are installed by default:
v Operations Navigator base support
v Basic operations (messages, printer output, and printers)
To select the subcomponents that you want to install, select the Custom installation option. (After Operations Navigator has been installed, you can add subcomponents by using Client Access Selective Setup.)
After you install Client Access, double-click the AS400 Operations Navigator icon on your desktop to access Operations Navigator and create an AS/400 connection.

Prerequisite and related information

Use the AS/400 Information Center as a starting point for your AS/400 information needs. It is available in either of the following ways:
v The Internet at this uniform resource locator (URL) address:
http://publib.boulder.ibm.com/html/as400/infocenter.html
v On CD-ROM: AS/400 Information Center, SK3T-2027-03 .
The AS/400 Information Center contains important topics such as logical partitioning, clustering, Java, TCP/IP, Web serving, and secured networks. It also contains Internet links to Web sites such as the AS/400 Online Library and the AS/400 Technical Studio. Included in the Information Center is a link that describes at a high level the differences in information between the Information Center and the Online Library.

How to send your comments

Your feedback is important in helping to provide the most accurate and high-quality information. If you have any comments about this book or any other AS/400 documentation, fill out the readerscomment form at the back of this book.
v If you prefer to send comments by mail, use the readerscomment form with the
address that is printed on the back. If you are mailing a readerscomment form from a country other than the United States, you can give the form to the local IBM branch office or IBM representative for postage-paid mailing.
v If you prefer to send comments by FAX, use either of the following numbers:
United States and Canada: 1-800-937-3430
Other countries: 1-507-253-5192
v If you prefer to send comments electronically, use this network ID:
IBMMAIL, to IBMMAIL(USIB56RZ)
vi Web Programming Guide V4R5
– RCHCLERK@us.ibm.com
Be sure to include the following:
v The name of the book.
v The publication number of the book.
v The page number or topic to which your comment applies.
About HTTP Server for AS/400 Web Programming Guide (GC41-5435) vii
viii Web Programming Guide V4R5

Chapter 1. Writing Common Gateway Interface Programs

OverviewoftheCGI ...........1
CGI and Dynamic Documents .......2
UsesforCGI.............3
The CGI process .............3
Overview..............3
SendingInformationtotheServer......5
Data Conversions on CGI Input and Output . . . 5
CGI Input Conversion Modes.......6
DBCS Considerations .........7
CGI Output Conversion Modes ......9
ReturningOutputfromtheServer......11
HowCGIProgramsWork ........12
This chapter discusses the Common Gateway Interface (CGI): What it is, why you might want to use it, and how it works.

Overview of the CGI

CGI is a standard, supported by almost all web servers, that defines how information is exchanged between a web server and an external program (CGI program).
The CGI specification dictates how CGI programs get their input and how they produce any output. CGI programs process data that is received from browser clients. For example, the client fills out a form and sends the information back to the server. Then the server runs the CGI program.
Parsing ..............12
Datamanipulation..........12
Response generation .........12
Environment variables ...........13
Requests from Standard Search (ISINDEX)
Documents.............15
Passing SSL Environment Variables to a CGI
Program..............15
CGI Programs and AS/400 Activation Groups . . . 17
AS/400 Activation Groups ........17
CGIConsiderations...........18
Activation Group Problem Examples .....18
Programs that are called by the server must conform to the server CGI interface in order to run properly. We will describe this in further detail later in this chapter.
The administrator controls which CGI programs the system can run by using the server directives. The server recognizes a URL that contains a request for a CGI program, commonly called a CGI script. Depending on the server directives, the server calls that program on behalf of the client browser.
For more information on CGI, see this URL:
http://www.w3.org/Daemon/User/CGI/Overview.html.
®
AS/400
supports CGI programs that are written in C++, Rexx, Java®, ILE-C, ILE-RPG, and ILE-COBOL. It also supports multi-thread CGI programs in all of these languages capable of multiple threads. For sample code that can help you with CGI programs, see the AS/400 Web Builders Workshop. You can find it at the following URL:
http://www.as400.ibm.com/tstudio/workshop/webbuild.htm.
You need to compile programs that are written in programming languages. Compiled programs typically run faster than uncompiled programs. On the other hand, those programs that are written in scripting languages tend to be easier to write, maintain, and debug.
© Copyright IBM Corp. 1997, 2000 1
The functions and tasks that CGI programs can perform range from the simple to the very advanced. In general, we call those that perform the simple tasks CGI scripts because you do not compile them. We often call those that perform complex tasks gateway programs. In this manual, we refer to both types as CGI programs.
Given the wide choice of languages and the variety of functions, the possible uses for CGI programs seem almost endless. How you use them is up to you. Once you understand the CGI specification, you will know how servers pass input to CGI programs and how servers expect output.
There are many uses for CGI programs. Basically, you should design them to handle dynamic information. Dynamic in this context refers to temporary information that is created for a one-time use and not stored anywhere on the web. This information may be a document, an e-mail message, or the results of a conversion program.
For detailed information about AS/400 CGI APIs, see Chapter 2. Application Programming Interfaceson page 23.

CGI and Dynamic Documents

There are many types of files that exist on the web. Primarily they fall into one of the following categories:
v Images
v Multimedia
v Programs
v HTML documents
Servers break HTML documents into two distinct types:
v Static
v Dynamic
Static documents exist in non-changing source form on the web server. You should create Dynamic documents as temporary documents to satisfy a specific, individual request.
Consider the process of serving, these two types of documents. Responding to requests for static documents is fairly simple. For example, Jill User accesses the Acme web server to get information on the Pro-Expert gas grill. She clicks on Products, then on Grills, and finally on Pro-Expert. Each time Jill clicks on a link, the web browser uses the URL that is attached to the link to request a specific document from the web server. The server responds by sending a copy of the document to Jills browser.
What if Jill decides that, she wants to search through the information on the Acme web server for all documents that contain information on Acme grills? Such information could consist of news articles, press releases, price listings, and service agreements. This is a more difficult request to process. This is not a request for an existing document. Instead, it is a request for a dynamically generated list of documents that meet certain criteria. This is where CGI comes in.
You can use a CGI program to parse the request and search through the documents on your web server. You can also use it to create a list with hypertext links to each of the documents that contain the specified word or string.
2 Web Programming Guide V4R5

Uses for CGI

HTML allows you to access resources on the Internet by using other protocols that are specified in the URL. Examples of such protocols are mailto, ftp, and news. If you code a link with mailto that is followed by an e-mail address, the link will result in a generic mail form.
What if you wanted your customers to provide specific information, such as how often they use the web? Or how they heard about your company? Rather than using the generic mailto form, you can create a form that asks these questions and more. You can then use a CGI program to interpret the information, include it in an e-mail message, and send it to the appropriate person.
You do not need to limit CGI programs to processing search requests and e-mail. You can use them for a wide variety of purposes. Basically, anytime you want to take input from the reader and generate a response, you can use a CGI program. The input may even be apparent to the reader. For example, many people want to know how many other people have visited their home page. You can create a CGI program that keeps track of the number of requests for your home page. This program can display the new total each time someone links to your home page.

The CGI process

Usually CGI programs are referred to from within HTML documents. In general, the HTML document format defines the environment variables that specify the passing of information. When you design the layout of your HTML document, you must keep in mind how a CGI program might affect the look of your document. Developing the CGI program along with the HTML document will help you avoid many design mistakes.

Overview

The CGI process involves three players: The web browser, the web server, and the CGI program. To exemplify how CGI programs for online forms work, let us assume that the web browser has already requested and obtained an HTML form.
1. The user clicks buttons or enters information in fields, and then clicks on an
2. The web browser then sends the data to the web server in an encoded format.
3. When the web server receives data, it converts the data to a format compliant
4. The CGI program then decodes and processes the data.
5. The system sends this response back to the web server in a form that is
6. The web server then interprets the response and forwards it to the web
Note: If a CGI application program must change the HTTP server job attributes
HTML button to submit the request.
For example, the data might consist of responses on an HTML form.
with the CGI specification for input and sends it to the CGI program.
compliant with the CGI specification for output.
browser.
while processing, the CGI program must restore the attributes to their initial values before the CGI program ends. Failure to restore job attributes that are changed in the CGI program will result in unpredictable responses to future server requests. For example, a CGI program that requires a library in the library list needs to add the library to the library list. The CGI program must remove the library list before the CGI program ends.
Chapter 1. Writing Common Gateway Interface Programs 3
The following HTML form illustrates the various types of fields:
Note: The CGIXMP.EXE program referred to in this sample is just an example; it is
not shipped with the server product.
<HTML> <HEAD> <TITLE>CGIXMP Test Case</TITLE> </HEAD> <BODY> <H1>CGI Sample Test Case</H1> Fill in the following fields and press APPLY. The values you enter will be read by the CGIXMP.EXE program and displayed in a simple HTML form which is generated dynamically by the program. <P> <HR> <form method=POST action="/cgi-bin/cgixmp"> <P> <H3>Checkbox Field</H3> <P> <PRE> <input type="checkbox" name="var1" value="123"> Check to set variable VAR1 to 123<BR> <input type="checkbox" name="var2" value="XyZ" checked> Check to set variable VAR2 to XyZ<BR> </PRE> <P> <H3>Radio Button Field</H3> <P> <PRE> <input type="radio" name="var3" value="1"> Select to set variable VAR3 to 1<BR> <input type="radio" name="var3" value="2"> Select to set variable VAR3 to 2<BR> <input type="radio" name="var3" value="3" checked> Select to set variable VAR3 to 3<BR> <input type="radio" name="var3" value="4"> Select to set variable VAR3 to 4<BR> </PRE> <P> <H3>Single selection List Field</H3> <P> <PRE> Select a value for variable VAR4 <select size=1 name="var4"> <option>0<option>1<option>2<option>3 <option>4<option>5</select> </PRE> <P> <H3>Text Entry Field</H3> <P> <PRE> Enter value for variable VAR5 <input type="text" name="var5" size=20 maxlength=256 value="TEST value"> </PRE> <P> <H3>Multiple selection List Field</H3> <P> <PRE> Select a value for variable VAR6 <select multiple size=2 name="var6"> <option>Ford<option>Chevrolet<option>Chrysler<option> Ferrari<option>Porsche </select> </PRE>
<P> <H3>Password Field</H3> <P>
4 Web Programming Guide V4R5
<PRE> Enter Password <input type="password" name="pword" size=10 maxlength=10> </PRE> <P> <H3>Hidden Field</H3> <P> <input type="hidden" name="hidden" value="Text not shown on form..."> <P> <PRE> <input type="submit" name="pushbutton" value="Apply"> <input type="reset" name="pushbutton" value="Reset"> <HR> </PRE> </FORM> </BODY> </HTML>

Sending Information to the Server

When you fill out a form, the web browser sends the request to the server in a format that is described as URL-encoded. The web browser also performs this function whenever you enter a phrase in a search field and click on the submission button. In URL-encoded information:
v The URL starts with the URL of the processing program.
v A question mark (?) precedes attached data, such as name=value information
from a form, which the system appends to the URL.
v A plus sign (+) represents spaces.
v A percent sign (%) that is followed by the American National Standard Code for
Information Interchange (ASCII) hexadecimal equivalent of the symbol represents special characters, such as a period (.) or slash (/).
v An ampersand (&) separates fields and sends multiple values for a field such as
check boxes.
Note: The method attribute specifies how the server sends the form information to
the program. You use the GET and POST methods in the HTML file to process forms. The GET method sends the information through environment variables. You will see the information in the URL after the ?character. The POST method passes the data through standard input.
The main advantage of using the GET method is that you can access the CGI program with a query without using a form. In other words, you can create canned queries that pass parameters to the program. For example, if you want to send the previous query to the program directly, you can do the following:
<A HREF="/cgi-bin/program.pgm?Name=John&LName=Richard&user=Smith%Company=IBM"> YourCGI Program</a>
The main advantage to the POST method is that the query length can be unlimited so you do not have to worry about the client or server truncating data. The query string of the GET method cannot exceed 4 KB.

Data Conversions on CGI Input and Output

The server can perform ASCII to EBCDIC conversions before sending data to CGI programs. This is because the Internet is an ASCII world and the AS/400 is primarily an extended binary-coded decimal interchange code (EBCDIC) world. The server can also perform EBCDIC to ASCII conversions before sending data
Chapter 1. Writing Common Gateway Interface Programs 5
back to the browser. You must provide data to a CGI program through environment variables and standard-input (stdin). HTTP and HTML specifications allow you to tag text data with a character set (charset parameter on the Content-Type header). However, this practice is not widely in use today (although technically required for HTTP1.0/1.1 compliance). According to this specification, text data that is not tagged can be assumed to be in the default character set ISO-8859-1 (US-ASCII). AS/400 correlates this character set with ASCII CCSID 819.
There are basically three different ways the server can process the input to and output from your CGI program. You can configure the server to control which mode is used by specifying an overall server directive (CGIConvMode) or an optional parameter on the Exec or Post-Script script directives:
CGIConvMode Mode Exec request-template program-path [server-IP-address or hostname] [Mode] Post-Script program_path_and_name [server-IP-address or hostname] [Mode]
Where Mode is one of the following:
%%MIXED%% or %%MIXED/MIXED%% This is the default.
%%EBCDIC%% or %%EBCDIC/MIXED%%
%%EBCDIC/EBCDIC%%
%%BINARY%% or %%BINARY/MIXED%%
%%BINARY/EBCDIC%%
%%BINARY/BINARY%%
%%EBCDIC_JCD%% or %%EBCDIC_JCD/MIXED%%
%%EBCDIC_JCD/EBCDIC%%
The CGIMode can be thought of as 2 logical pieces. The input mode and output mode. They are separated by the /. If only the input mode is provided, the output mode is defaulted to MIXED for compatibility.
In addition, the system provides the following CGI environment variables to the CGI program:
v CGI_MODE - which input conversion mode the server is using (%%MIXED%%,
%%EBCDIC%%, %%BINARY%%, or %%EBCDIC_JCD%%).
v CGI_ASCII_CCSID - from which ASCII CCSID was used to convert the data
v CGI_EBCDIC_CCSID - which EBCDIC CCSID the data was converted into
v CGI_OUTPUT_MODE - which output conversion mode the server is using
(%%MIXED%%, %%EBCDIC%%, or %%BINARY%%)
The following section explains CGI input conversion modes in more detail.
CGI Input Conversion Modes
MIXED
This mode is the default mode of operation for the server. The system converts values for CGI environment variables to EBCDIC CCSID 37, including QUERY_STRING. The system converts stdin data to the CCSID of the job. However, the system still represents the encoded characters %xxby the ASCII 819 octet. This requires the CGI program to convert these further into EBCDIC to process the data. For more information, see symptom, Special characters are not being converted or handled as expected in Chapter 10. Troubleshooting your CGI programson page 139.
EBCDIC
6 Web Programming Guide V4R5
In this mode, the server will convert everything into the EBCDIC CCSID of the job. The server checks the Entity bodies for a charset tag. If found, the server will convert the corresponding ASCII CCSID to the EBCDIC CCSID of the job. If the server does not find a charset tag, it uses the value of the DefaultNetCCSID configuration directive as the conversion CCSID. In addition, the system converts escaped octets from ASCII to EBCDIC, eliminating the need to perform this conversion in the CGI program.
BINARY
In this mode, the server processes environment variables (except QUERY_STRING) the same way as EBCDIC mode. The server performs no conversions on either QUERY_STRING or stdin data.
EBCDIC_JCD
Japanese browsers can potentially send data in one of three code pages, JIS (ISO-2022-JP), S-JIS (PC-Windows), or EUC (UNIX). In this mode, the server uses a well-known JCD utility to determine which codepage to use (if not explicitly specified by a charset tag) to convert stdin data.
Table 1 summarizes the type of conversion that is performed by the server for each CGI mode.
Table 1. Conversion action for text in CGI Stdin.
CGI_MODE Conversion Stdin
encoding
%%BINARY%% None No conversion FsCCSID No conversion No
%%EBCDIC%% NetCCSID to
FsCCSID
%%EBCDIC%% - with charset tag received
%%EBCDIC_JCD%% Detect input based
%%MIXED%% (Compatability mode)
Calculate target EBCDIC CCSID based on received ASCII charset tag
on received data. Convert data to FsCCSID
NetCCSID to FsCCSID (receive charset tag is ignored)
FsCCSID FsCCSID FsCCSID FsCCSID
EBCDIC equivalent of received charset
FsCCSID FsCCSID Detect ASCII
FsCCSID with ASCII escape sequences
Environment
variables
FsCCSID FsCCSID FsCCSID
CCSID 37 CCSID 37 with
Query_String
encoding
input based on received data. Convert data to FsCCSID
ASCII escape sequences
conversion
Detect ASCII input based on received data. Convert data to FsCCSID
CCSID37 with ASCII escape sequences
argv
encoding
DBCS Considerations
URL-encoded forms containing DBCS data could contain ASCII octets that represent parts of DBCS characters. The server can only convert non-encoded character data. This means that it must un-encode the double-byte character set (DBCS) stdin and QUERY_STRING data before performing the conversion. In addition, it has to reassemble and re-encode the resulting EBCDIC representation before passing it to the CGI program. Because of this extra processing, CGI programs that you write to handle DBCS data may choose to receive the data as BINARY and perform all conversions to streamline the entire process.
Chapter 1. Writing Common Gateway Interface Programs 7
Using the EBCDIC_JCD mode: The EBCDIC_JCD mode determines what character set is being used by the browser for a given request. This mode is also used to automatically adjust the ASCII/EBCDIC code conversions used by the web server as the request is processed.
After auto detection, the %%EBCDIC_JCD%% mode converts the stdin and QUERY_STRING data from the detected network CCSID into the correct EBCDIC CCSID for Japanese. The default conversions configured for the server instance are overridden. The DefaultFsCCSID directive or the -fsccsid startup parameter specifies the default conversions. The startup FsCCSID must be a Japanese CCSID (5026 or 5035).
The possible detected network code page is Shift JIS, eucJP, and ISO-2022-JP. The following are the associated CCSIDs for each code page:
Shift JIS (See note 1) ========= CCSID 932: IBM PC (old JIS sequence, OS/2 J3.X/4.0, IBM Windows J3.1) CCSID 942: IBM PC (old JIS sequence, OS/2 J3.X/4.0) CCSID 943: MS Shift JIS (new JIS sequence, OS/2 J4.0
eucJP ===== CCSID 5050: Extended UNIX Code (Japanese)
ISO-2022-JP (See note 2) =========== CCSID 5052: Subset of RFC 1468 ISO-2022-JP (JIS X 0201 Roman and
MS Windows J3.1/95/NT)
JIS X 0208-1983) plus JIS X 0201 Katakana.
CCSID 5054: Subset of RFC 1468 ISO-20220JP (ASCII and JIS X 0208-1983)
plus JIS X 0201 Katakana.
The detected network CCSID is available to the CGI program. The CCSID is stored in the CGI_ASCII_CCSID environment variable. When JCD can not detect, the default code conversion is done as configured (between NetCCSID and FsCCSID). (See note 3.)
Since the code page of Stdin and QUERY_STRING are encoded according to the web clients outbound code page, we recommend using the following configuration value combinations when you use the %%EBCDIC_JCD%% mode.
Startup FsCCSID Startup NetCCSID Description
--------------- ---------------- ---------------------­5026/5035 (See note 4) <-> 943 Default: MS Shift JIS 5026/5035 (See note 4) <-> 942 Default: IBM PC 5026/5035 (See note 4) <-> 5052/5054 Default: ISO-2022-JP
Using CCSID 5050(eucJP) for the startup NetCCSID, is not recommended. When 5050 is specified for the startup NetCCSID, the default code conversion is done between FsCCSID and 5050. This means that if JCD cannot detect a code page, JCD returns 5050 as the default network CCSID. Most browsers use a default outbound code page of Shift JIS or ISO-2022-JP, not eucJP.
If the web client sends a charset tag, JCD gives priority to the charset tag. Stdout function is the same. If the charset/ccsid tag is specified in the Content-Type field, stdout gives priority to charset/ccsid tag. Stdout also ignores the JCD detected network CCSID. (See note 5.)
8 Web Programming Guide V4R5
Notes:
1. If startup NetCCSID is 932 or 942, detected network, Shift JISs CCSID is the
same as startup NetCCSID. Otherwise, Shift JISs CCSID is 943.
Startup NetCCSID Shift JIS (JCD detected CCSID)
---------------- -----------------------------­932 932 942 942 943 943 5052 943 5054 943 5050 943
2. Netscape Navigator 3.x sends the alphanumeric characters by using JIS X 0201
Roman escape sequence (CCSID 5052) for ISO-2022-JP. Netscape Communicator
4.x sends the alphanumeric characters by using ASCII escape sequence (CCSID
5054) for ISO-2022-JP.
3. JCD function has the capability to detect EUC and SBCS Katakana, but it is
difficult to detect them. IBM
®
recommends that you do not use SBCS Katakana
and EUC in CGI.
4. CCSID 5026 assigns lowercase alphabet characters on special code point. This
often causes a problem with lowercase alphabet characters. To avoid this problem, do one of the following:
v Do not use lowercase alphabet literals in CGI programs if the FsCCSID is
5026.
v Use CCSID 5035 for FsCCSID.
v Use the Charset/CCSID tag as illustrated in the following excerpt of a CGI
program:
main(){
printf("Content-Type: text/html; Charset=ISO-2022-JP\n\n"); ...
}
v Do the code conversions in the CGI program. The following sample C
program converts the literals into CCSID 930 (the equivalent to CCSID 5026)
main(){
printf("Content-Type: text/html\n\n);
#pragama convert(930)
printf("<html>"); printf("This is katakana code page\n");
#pragama convert(0)
...
}
5. When the web client sends a charset tag, the network CCSID becomes the
ASCII CCSID associated with Multipurpose Internet Mail Extensions (MIME) charset header. The charset tag ignores the JCD detected CCSID. When the Charset/ccsid tag is in the Content-Type header generated by the CGI program, the JCD-detected CCSID is ignored by this charset/ccsid. Stdout will not perform a conversion if the charset is the same as the MIMEs charset. Stdout will not perform a conversion if the CCSID is ASCII. Stdout will perform code conversion if the CCSID is EBCDIC. Because the environment variables and stdin are already stored in FsCCSID, ensure that you are consistent between the FsCCSID and the Content-Type headers CCSID.
CGI Output Conversion Modes
The CgiConv mode includes an output mode. This section explains CGI output conversion modes in more detail.
Chapter 1. Writing Common Gateway Interface Programs 9
%%MIXED%%
In this mode HTTP header output is in CCSID 37. However, the escape sequence must be the EBCDIC representative of the ASCII code point for the 2 characters following the %in the escape sequence. An example of a HTTP header that may contain escape sequences is the Location header.
%%EBCDIC%%
In this mode HTTP header output is in CCSID 37. However, the escape sequence must be the EBCDIC representative of the EBCDIC code point for the 2 characters following the %in the escape sequence. An example of a HTTP header that may contain escape sequences is the Location header.
%%BINARY%%
In this mode HTTP header output is in CCSID 819 with the escape sequences also being the ASCII representative of the ASCII code point. An example of a HTTP header that may contain escape sequences is the Location header.
For HTTP body standard-output (stdout) data that is sent from the CGI program, the server recognizes and uses the charset or CCSID parameter on the text/* Content-Types. If you specify ASCII, the server performs no conversions on the data. Otherwise, the system uses the Content-Type value instead of the DefaultFsCCSID on conversions back to the browser. The system sets an appropriate charset tag for all text/* Content-Types that it sends back to the browser. The exception to this is %%MIXED%%, %%MIXED/MIXED%%, %%BINARY/BINARY%% modes and when the charset or CCSID parameter is set to 65535.
Table 2 summarizes the type of conversion that is performed and the charset tag that is returned to the browser by the server.
Table 2. Conversion action and charset tag generation for text in CGI Stdout.
CGI Stdout CCSID/Charset in HTTP header Conversion action Server reply charset tag
EBCDIC CCSID/Charset Calculate EBCDIC to ASCII
conversion based on supplied EBCDIC CCSID/Charset
ASCII CCSID/Charset No conversion Stdout CCSID/Charset as Charset
65535 No conversion None
None (%%BINARY%%, %%BINARY/MIXED%%, or %%BINARY/EBCDIC%%)
None (%%BINARY/BINARY%%) No Conversion None
None (%%EBCDIC%%, %%EBCDIC/MIXED%%, or %%EBCDIC/EBCDIC%%)
None (%%EBCDIC%%, %%EBCDIC/MIXED%%, or %%EBCDIC/EBCDIC%% with charset tag received on HTTP request)
None (%%EBCDIC_JCD%%, %%EBCDIC_JCD/MIXED%%, or %%EBCDIC_JCD/EBCDIC%%)
Default Conversion - FsCCSID to NetCCSID
Default Conversion - FsCCSID to NetCCSID
Use inverse of conversion calculated for stdin
Default Conversion - FsCCSID to NetCCSID
Calculated ASCII charset
NetCCSID as charset
NetCCSID as charset
Charset as received on HTTP request
NetCCSID as charset
10 Web Programming Guide V4R5
Table 2. Conversion action and charset tag generation for text in CGI Stdout. (continued)
CGI Stdout CCSID/Charset in HTTP header Conversion action Server reply charset tag
None (%%MIXED%% or %%MIXED/MIXED%%)
Invalid CGI error 500 generated by server
Default Conversion - FsCCSID to NetCCSID
None (compatibility mode)
The server also sets an environment variable CGI_OUTPUT_MODE to reflect the setting for the CGI output mode. It contains the CGI output conversion mode the server is using for this request. Valid values are %%EBCDIC%%, %%MIXED%%, or %%BINARY%%. The program can use this information to determine what conversion, if any, the server performs on CGI output.

Returning Output from the Server

When the CGI program is finished, it passes the resulting response to the server by using standard output (stdout). The server interprets the response and sends it to the browser.
A CGI program writes a CGI header that is followed by an entity body to standard output. The CGI header is the information that describes the data in the entity body. The entity body is the data that the server sends to the client. A single newline character always ends the CGI header. The newline character for ILE/C is \n. For ILE/RPG or ILE/COBOL, it is hexadecimal 15. The following are some examples of Content-Type headers:
Content-Type: text/html\n\n Content-Type: text/html; charset=iso-8859-2\n\n
If the response is a static document, the CGI program returns either the URL of the document using the CGI Location header or returns a Status header. The CGI program does not have an entity body when using the Location header. If the host name is the local host, the HTTP server will retrieve the specified document that the CGI program sent. It will then send a copy to the web browser. If the host name is not the local host, the HTTP processes it as a redirect to the web browser. For example:
Location: http://www.acme.com/products.html\n\n
The Status header should have a Content_Type: and a Status in the CGI header. When Status is in the CGI header, an entity body should be sent with the data to be returned by the server. The entity body data contains information that the CGI program provides to a client for error processing. The Status line is the Status with an HTTP 3 digit status code and a string of alphanumeric characters (A-Z, a-z, 0-9 and space). The HTTP status code must be a valid 3 digit number from the HTTP/1.1 specification.
Note: The newline character \n ends the CGI header.
CONTENT-TYPE: text/html\n Status: 600 Invalid data\n \n <html><head><title>Invalid data</title> </head><body> <h1>Invalid data typed</h1> <br><pre> The data entered must be valid numeric digits for id number <br></pre> </body></html>
Chapter 1. Writing Common Gateway Interface Programs 11

How CGI Programs Work

Most CGI programs include the following three stages:
v Parsing CGI programs
v Data manipulation within a CGI program
v Response generation by a CGI program
Parsing
Parsing is the first stage of a CGI program. In this stage, the program takes the data from QUERY_STRING environment variable, command line arguments using argv() or standard input. When the method is GET, the system reads the data from the QUERY_STRING environment variable or command line arguments by using argv(). There is no way to determine the length of data in QUERY_STRING. The system encodes the QUERY_STRING data in the request header.
An example of data read in the QUERY_STRING variable (%%MIXED%% mode):
NAME=Eugene+T%2E+Fox&ADDR=etfox%40ibm.net&INTEREST=RCO
Parsing breaks the fields at the ampersands and decodes the ASCII hexadecimal characters. The results look like this:
NAME=Eugene T. Fox ADDR=etfox@ibm.net INTEREST=RCO
You can use the QtmhCvtDb API to parse the information into a structure. The CGI program can refer to the structure fields. If using %%MIXED%% input mode, the %xxencoding values are in ASCII and must be converted into the %xx EBCDIC encoding values before calling QtmhCvtDb. If using %%EBCDIC%% mode, the server will do this conversion for you. The system converts ASCII %xxfirst to the ASCII character and then to the EBCDIC character. Ultimately, the system sets the EBCDIC character to the %xxin the EBCDIC CCSID. For code samples, use the following URL to the AS/400 web site:
http://www.as400.ibm.com/tstudio/index.htm.
When the method is post, the system reads the data from standard input. Before the CGI attempts to read standard input, it must check environment variables REQUEST_METHOD and CONTENT_LENGTH. Read standard input only when the REQUEST_METHOD is POST. The read must specify no more than CONTENT_LENGTH bytes. Attempts to specify more than CONTENT_LENGTH bytes on reading standard input are not defined.
Data manipulation
Data manipulation is the second stage of a CGI program. In this stage, the program takes the parsed data and performs the appropriate action. For example, a CGI program designed to process an application form might perform one of the following functions:
1. Take the input from the parsing stage
2. Convert abbreviations into more meaningful information
3. Plug the information into an e-mail template
4. Use SNDDST to send the e-mail.
Response generation
Response generation is the final stage of a CGI program. In this stage, the program formulates its response to the web server, which forwards it to the browser. The response contains MIME headers that vary depending on the type of response.
12 Web Programming Guide V4R5
With a search, the response might be the URLs of all the documents that met the search value. With a request that results in e-mail, the response might be a message that confirms that the system actually sent the e-mail.

Environment variables

Before you begin writing your CGI program, you need to understand the format in which the server will pass the data. The server receives the URL-encoded information and, depending on the type of request, passes the information to the CGI program. The server does this by using environment variables, command line arguments, or standard input.
A CGI application program should be able to handle a NULL value when getting an environment variable. For example, when the CGI program is trying to do a getenv(CONTENT_LENGTH) and the method is GET, the value would be returned NULL. This is because CONTENT_LENGTH is only defined in method POST (to describe the length of standard input).
The system supports the following environment variables:
AUTH_TYPE
If the server supports client authentication and the script is a protected script, this environment variable contains the method that is used to authenticate the client. For example:
Basic
CGI_ASCII_CCSID
Contains the ASCII CCSID the server used when converting CGI input data. If the server did not perform any conversion, (for example, in %%BINARY%% mode), the server sets this value to the DefaultNetCCSID configuration directive value.
CGI_MODE
Contains the CGI conversion mode the server is using for this request. Valid values are %%EBCDIC%%, %%MIXED%%, %%BINARY%%, or %%EBCDIC_JCD%%. The program can use this information to determine what conversion, if any, was performed by the server on CGI input data and what format that data is currently in.
CGI_EBCDIC_CCSID
Contains the EBCDIC CCSID under which the current server job is running (DefaultFsCCSID configuration directive). It also represents the current job CCSID that is used during server conversion (if any) of CGI input data.
CONTENT_LENGTH
When the method of POST is used to send information, this variable contains the number of characters. Servers typically do not send an end-of-file flag when they forward the information by using stdin. If needed, you can use the CONTENT_LENGTH value to determine the end of the input string. For example:
7034
CONTENT_TYPE
When information is sent with the method of POST, this variable contains the type of data included. You can create your own content type in the server configuration file and map it to a viewer. For example:
Application/x-www-form-urlencoded
Chapter 1. Writing Common Gateway Interface Programs 13
GATEWAY_INTERFACE
Contains the version of CGI that the server is using. For example:
CGI/1.1
HTTP_ACCEPT
Contains the list of MIME types the browser accepts. For example:
text/html
HTTP_USER_AGENT
Contains the name of your browser (web client). It includes the name and version of the browser, requests that are made through a proxy, and other information. For example:
Netscape Navigator dll /v3.0
IBM_CCSID_VALUE
The CCSID under which the current server job is running.
PATH_INFO
Contains the additional path information as sent by the web browser. For example:
/ballyhoo
PATH_TRANSLATED
Contains the decoded or translated version of the path information that is contained in PATH_INFO, which takes the path and does any virtual-to-physical mapping to it. For example:
/wwwhome/ballyhoo
QUERY_STRING
When information is sent using a method of GET, this variable contains the information in a query that follows the ?. The string is coded in the standard URL format of changing spaces to +and encoding special characters with %xxhexadecimal encoding. The CGI program must decode this information. For example:
NAME=Eugene+T%2E+Fox&ADDR=etfox%7Cibm.net&INTEREST=xyz
REMOTE_ADDR
Contains the IP address of the remote host (web browser) that is making the request, if available. For example:
9.23.06.8
REMOTE_HOST
Contains the host name of the web browser that is making the request, if available. For example:
raleigh.ibm.com
REMOTE_IDENT
Contains the user ID of the remote user. For example:
Jillx
REMOTE_USER
If you have a protected script and the server supports client authentication, this environment variable contains the user name that is passed for authentication. For example:
Jill
REQUEST_METHOD
14 Web Programming Guide V4R5
Contains the method (as specified with the METHOD attribute in an HTML form) that is used to send the request. For example:
GET or POST
SCRIPT_NAME
A virtual path to the program being run. Use this for self-referring URLs.
SERVER_NAME
Contains the server host name or IP address of the server. For example:
www.ibm.com
SERVER_PORT
Contains the port number to which the client request was sent. For example:
80
SERVER_PROTOCOL
Contains the name and version of the information protocol that is used to make the request. For example:
HTTP/1.0
SERVER_SOFTWARE
Contains the name and version of the information server software that is answering the request. For example:
IBM-Secure-ICS/AS/400 Secure HTTP Server

Requests from Standard Search (ISINDEX) Documents

ISINDEX is an HTML tag that identifies the document as a standard search document and causes the browser to automatically generate an entry field. When information is sent from an ISINDEX document, the server takes the appended data (the information following the ?), breaks it at the pluses (+), and sends the data to the CGI program as command line arguments (argv). For example:
<ISINDEX>
Note: It is possible to write CGI scripts that display all environment variables. At
times these variables may include sensitive data such as user IDs and passwords for various products. Consequently, you must be careful about displaying environment variables in your CGI scripts, and you must be careful about who has access to them.

Passing SSL Environment Variables to a CGI Program

You can use the following SSL-related environment variables in CGI programs.
HTTPS
Returns ON if the system has completed an SSL handshake. It returns OFF if the exchange of signals to set up communications between two modems has failed. For example:
OFF
HTTPS_CLIENT_CERT
The entire certificate passed to the server from the client browser when SSL Client authentication is enabled. The format of the certificate is a BASE64 encoded string that represents the DER format of the X.509 certificate.
HTTPS_CLIENT_CERT_COUNTRY
The Country Code from the client certificates distinguished name. For example:
US
Chapter 1. Writing Common Gateway Interface Programs 15
HTTPS_CLIENT_CERT_COMMON_NAME
The Common Name from the client certificates distinguished name. For example:
John Smith
HTTPS_CLIENT_CERT_ISSUER_COMMON_NAME
The Common Name of the Certificate Authority that issued the clients certificate. For example:
Digital ID
HTTPS_CLIENT_CERT_ISSUER_COUNTRY
The Country code of the Certificate Authority that issued the clients certificate. For example:
US
HTTPS_CLIENT_CERT_ISSUER_LOCALITY
The Locality of the Certificate Authority that issued the clients certificate. For example:
50265
HTTPS_CLIENT_CERT_ISSUER_STATE_OR_PROVINCE
The State or Province of the Certificate Authority that issued the clients certificate. For example:
Iowa
HTTPS_CLIENT_CERT_ISSUER_ORG_UNIT
The Organizational Unit of the Certificate Authority that issued the clients certificate. For example:
Department of Client Certificates
HTTPS_CLIENT_CERT_ISSUER_ORGANIZATION
The Organization name of the Certificate Authority that issued the clients certificate. For example:
Roadrunner CA
HTTPS_CLIENT_CERT_LEN
The Length of the certificate passed in HTTPS_CLIENT_CERT.
HTTPS_CLIENT_CERT_LOCALITY
The Locality (zip code in the US) from the client certificates distinguished name. For example:
55901
HTTPS_CLIENT_CERT_SERIAL_NUM
The serial number assigned by the issuing Certificate Authority. For example:
92787829
HTTPS_CLIENT_CERT_ORG_UNIT
The Organizational Unit name from the client certificates distinguished name. For example:
Department of Coyote products
HTTPS_CLIENT_CERT_ORGANIZATION
The Organization name from the client certificates distinguished name. For example:
Acme Corporation
16 Web Programming Guide V4R5
HTTPS_CLIENT_CERT_STATE_OR_PROVINCE
The State or Province from the client certificates distinguished name. For example:
Minnesota
HTTPS_KEYSIZE
Returns the number of bits in the session key that is established by SSL after a completed exchange of signals to set up communications between two modems. This value is blank if HTTPS=OFF. For example:
512
Examples of key sizes are Export {40} or {128}.
HTTPS_PORT
If a valid security product is installed and the SSLMode directive is SSLMode=ON, this environment variable contains the SSL port number the server is listening on. For example:
443

CGI Programs and AS/400 Activation Groups

The following section is intended to give a brief overview of AS/400 Activation Groups.
Note: It is very important to become familiar with the details of activation groups
prior to developing or porting a CGI application that will use this support.

AS/400 Activation Groups

Program activation is the process that is used to prepare a program to run. The system must activate AS/400 ILE programs before they can be run. Program activation includes the allocation and initialization of static storage for the program in addition to completing the binding of programs to service programs.
Program activation is not an AS/400 unique concept. All modern computer operating systems must perform program initialization and load. What is unique to AS/400 is the concept of Activation Groups. All ILE programs and service programs are activated within an activation group. This substructure contains the resources necessary to run the program. The resources that are contained and are managed with an activation group include:
v Static and automatic program variables
v Dynamic storage
v Temporary data management resources (For example, open files and SQL
cursors)
v Certain types of exception handlers and ending procedures
Run-time creation of ILE activation groups is controlled by specifying an activation group attribute when your program or service program is created. The attribute is specified by using the ACTGRP parameter on the CRTPGM or CRTSRVPGM command. The valid options for this attribute include user-named, *NEW, and *CALLER. The following is a brief description of these options:
user-named - A named activation group allows you to manage a collection of ILE programs and ILE service programs as one application. The activation group is created when it is first needed. All programs and service programs that specify the same activation group name use it then.
Chapter 1. Writing Common Gateway Interface Programs 17
*NEW- The name for this activation group is selected by ILE and will always be unique. System-named activation groups are always deleted when the high level language returns.
*CALLER - Specifying *CALLER causes the ILE program or service program to be activated within the activation group of the calling program. A new activation group is never created with this attribute.
*NEW is the standard behavior that can be expected on other systems such as
®
UNIX
Notes:
1. When you create a persistent CGI program, you must specify a named
2. CGI programs that are not persistent should not refer to job-level scoped
For additional information about activation groups see, ILE Concepts, SC41-5606 book.
.
activation group.
resources.

CGI Considerations

There are advantages to running CGI programs in either a user-named or *CALLER activation group. The performance overhead associated with activating a CGI every time that is requested can be drastically reduced. It is important to understand that because the system does not delete user-named activation groups, normal high level language end verbs cannot provide complete end processing. For example, the system will not close open files, and the system will not return the static and heap storage that are allocated by a program. The program must manage these resources explicitly. This will be especially important when moving CGI programs that rely on end processing to function properly.
Note: When you activate multi-threaded CGI on your web server, you get multiple
thread support for your CGI application Your CGI application must end all of its threads before returning to the server. When using multi-thread capable CGI, you need to put the CGI program in a new or named activation group.
The following section shows examples which will work fine running in a *NEW activation group, however will cause problems if run in a user-named or *CALLER activation group.

Activation Group Problem Examples

Note
The following examples are not general CGI programming examples. For general CGI programming examples, see Chapter 6. Sample programs (in Java, C, and RPG)on page 89.
In the following example a CGI program when run in a *NEW activation group, would write Hello World to the browser. What is important to understand is that this application is taking advantage of job end processing to delete the stdio buffers that are used to buffer the stdout data.
You could build the following CGI program to run in either a user-named or *CALLER activation group. In such an instance, the server will not process the
18 Web Programming Guide V4R5
information that was written to stdout. This will cause the web browser to display a Document Contains No Dataerror message. Another application could run again in the same activation group that properly erased stdout. In this instance, the data that has been buffered from previous calls would be sent.
#include <stdio.h> void main(void) {
/***************************************************/ /* Write header information. */ /***************************************************/ printf("Content-type: text/html\n\n");
/***************************************************/ /* Write header information. */ /***************************************************/ printf("Hello World\n");
}
End processing may not erase stdio buffers so the application must erase the stdout with a fflush(stdout) call. The following example will work regardless of the activation group specification:
#include <stdio.h> void main(void) {
/***************************************************/ /* Write header information. */ /***************************************************/ printf("Content-type: text/html\n\n");
/***************************************************/ /* Write header information. */ /***************************************************/ printf("Hello World\n");
/*-------------------------------------------------*/ /* FIX: Flush stdout. */ /*-------------------------------------------------*/ fflush(stdout);
}
When run in a *NEW activation group, this example CGI would read CONTENT_LENGTH bytes of data from stdin and write this back out to stdout. The system has allocated the buffer that is used to hold the data with a malloc. Like the example that is previously shown, this application is relying on several aspects of job end processing to function properly.
If this CGI program were built to run in either a user-named or *CALLER activation group, the following problems would occur:
v As with the simple example that is previously shown, the application is not
erasing stdout. This would cause the web browser to display a Document Contains No Dataerror message. You could run another application again in the same activation group that properly erased stdout. This would send the data that has been buffered from previous calls.
v Stdin is buffered similar to stdout. If the contents of stdin are not erased, the
stdin data on the second and all following calls of the CGI program will be unpredictable and the contents may at times contain information from subsequent requests.
Chapter 1. Writing Common Gateway Interface Programs 19
v The heap storage allocated using malloc is not being freed. Over time, a memory
leak error like this could use significant amounts of memory. This is a common application error that only surfaces when the application is not running in a *NEW activation group.
/*************************************************************************/ /* */ /* CGI Example program. */ /* */ /*************************************************************************/
#include void main(void) {
char* stdinBuffer; char* contentLength; int numBytes; int bytesRead; FILE* pStdin;
/**********************************************************************/ /* Write the header. */ /**********************************************************************/ printf("Content-type: text/html\n\n");
/**********************************************************************/ /* Get the length of data on stdin. */ /**********************************************************************/ contentLength = getenv("CONTENT_LENGTH");
if (contentLength != NULL) {
/*******************************************************************/ /* Allocate storage and clear the storage to hold the data. */ /*******************************************************************/ numBytes = atoi(contentLength); stdinBuffer = (char*)malloc(numBytes+1); if ( stdinBuffer )
memset(stdinBuffer, 0x00, numBytes+1);
/*******************************************************************/ /* Read the data from stdin and write back to stdout. */ /*******************************************************************/ bytesRead = fread(stdinBuffer, 1, numBytes, pStdin); stdinBufferþbytesRead+1þ = '\0'; printf("%s", stdinBuffer);
} else
printf("Error getting content length\n");
return;
}
The following example shows the changes that would be required to this application to allow it to run in a user-named or *CALLER activation group:
/*************************************************************************/ /* */ /* CGI Example program with changes to support user-named */ /* and *CALLER ACTGRP. */ /* */ /*************************************************************************/
#include void main(void)
20 Web Programming Guide V4R5
{
char* stdinBuffer; char* contentLength; int numBytes; int bytesRead; FILE* pStdin;
/**********************************************************************/ /* Write the header. */ /**********************************************************************/ printf("Content-type: text/html\n\n");
/**********************************************************************/ /* Get the length of data on stdin. */ /**********************************************************************/ contentLength = getenv("CONTENT_LENGTH");
if (contentLength != NULL) {
/*******************************************************************/ /* Allocate storage and clear the storage to hold the data. */ /*******************************************************************/ numBytes = atoi(contentLength); stdinBuffer = (char*)malloc(numBytes+1); if ( stdinBuffer )
memset(stdinBuffer, 0x00, numBytes+1);
/*-----------------------------------------------------------------*/ /* FIX 2: Reset stdin buffers. */ /*-----------------------------------------------------------------*/ pStdin = freopen("", "r", stdin);
/*******************************************************************/ /* Read the data from stdin and write back to stdout. */ /*******************************************************************/ bytesRead = fread(stdinBuffer, 1, numBytes, pStdin); stdinBufferþbytesRead+1þ = '\0'; printf("%s", stdinBuffer);
/*-----------------------------------------------------------------*/ /* FIX 3: Free allocated memory. */ /*-----------------------------------------------------------------*/ free(stdinBuffer);
} else
printf("Error getting content length\n");
/*-------------------------------------------------------------------*/ /* FIX 1: Flush stdout. */ /*-------------------------------------------------------------------*/ fflush(stdout); return;
}
Chapter 1. Writing Common Gateway Interface Programs 21
22 Web Programming Guide V4R5

Chapter 2. Application Programming Interfaces

APIs for CGI applications .........24
Get Environment Variable (QtmhGetEnv) API . . 25
Required parameter group .......25
Errormessages...........26
Put Environment Variable (QtmhPutEnv) API . . 26
Required parameter group .......26
Errormessages...........27
Read from Stdin (QtmhRdStin) API .....27
Required parameter group .......28
Error Messages ...........28
Write to Stdout (QtmhWrStout) API .....29
Required parameter group .......29
Errormessages...........29
Convert to DB (QtmhCvtDB) API ......30
Required parameter group .......31
Errormessages...........32
Parse QUERY_STRING Environment Variable or
Post stdin data (QzhbCgiParse) API .....32
Required parameter group .......33
CGII0200 Format ..........35
Field descriptions ..........35
Errormessages...........36
Produce Full HTTP Response (QzhbCgiUtils) API 36
Errormessages...........38
ConfigurationAPIs............38
Convert URL to Path (QzhbCvtURLtoPath) API 38
Authorities and locks .........38
Required parameter group .......39
Errormessages...........40
Retrieve Directive (QzhbRetrieveDirective) API 40
Authorities and locks .........40
Required parameter group .......40
Errormessages...........42
Retreive a list of all Configuration Names
(QzhbGetConfigNames) API ........42
Authorities and locks .........42
Required parameter group .......42
Errormessages...........43
Create a Configuration (QzhbCreateConfig) API 43
Authorities and locks .........43
Required parameter group .......43
Errormessages...........44
Delete a Configuration (QzhbDeleteConfig) API 44
Authorities and locks .........44
Required parameter group .......44
Errormessages...........44
Read a Configuration File into Memory
(QzhbOpenConfig) API .........45
Authorities and locks .........45
Required parameter group .......45
Errormessages...........46
Free a Configuration File from Memory
(QzhbCloseConfig) API .........46
Authorities and locks .........46
Required parameter group .......46
Errormessages...........47
Search for a Main Directive (QzhbFindDirective)
API................47
Authorities and locks .........47
Required parameter group .......47
Errormessages...........48
Search for a Subdirective under Main Directive
(QzhbFindSubdirective) API ........49
Authorities and locks .........49
Required parameter group .......49
Errormessages...........50
Return Details of a Main Directive or Subdirective (QzhbGetDirectiveDetail) API . . . 51
Authorities and locks .........51
Required parameter group .......51
Errormessages...........52
Add a Main Directive or Subdirective
(QzhbAddDirective) API .........52
Authorities and locks .........52
Required parameter group .......52
Errormessages...........54
Remove a Main Directive or Subdirective
(QzhbRemoveDirective) API ........54
Authorities and locks .........54
Required parameter group .......54
Errormessages...........55
Replace a Main Directive or Subdirective
(QzhbReplaceDirective) API ........55
Authorities and locks .........55
Required parameter group .......55
Errormessages...........56
ServerinstanceAPIs...........56
Retrieve a list of all Server Instances
(QzhbGetInstanceNames) API .......56
Authorities and locks .........56
Required parameter group .......56
INSN0100 Format ..........57
Field descriptions ..........57
Errormessages...........57
Look up Server Instance Data
(QzhbGetInstanceData) API ........58
Authorities and locks .........58
Required parameter group .......58
INSD0100 Format ..........59
Field descriptions ..........59
Errormessages...........60
Change Server Instance Data
(QzhbChangeInstanceData) API ......60
Authorities and locks .........61
Required parameter group .......61
Errormessages...........61
Create a Server Instance (QzhbCreateInstance)
API................62
Authorities and locks .........62
Required parameter group .......62
Errormessages...........63
© Copyright IBM Corp. 1997, 2000 23
Delete a Server Instance (QzhbDeleteInstance)
API................63
Authorities and locks .........63
Required parameter group .......63
Errormessages...........64
Group file APIs .............64
Create a new Group File (QzhbCreateGroupList)
API................64
Authorities and locks .........64
Required parameter group .......65
Errormessages...........65
Read a Group File into Memory
(QzhbOpenGroupList) API ........65
Authorities and locks .........65
Required parameter group .......66
Errormessages...........66
Free Group File from Memory
(QzhbCloseGroupList) API ........67
Authorities and locks .........67
Required parameter group .......67
Errormessages...........67
Retrieve the next Group in the Group List
(QzhbGetNextGroup) API ........68
Authorities and locks .........68
Required parameter group .......68
Errormessages...........68
Locate a named group in a Group List
(QzhbFindGroupInList) API ........69
Authorities and locks .........69
Required parameter group .......69
Errormessages...........69
Retrieve the Name of a Group
(QzhbGetGroupName) API ........70
Authorities and locks .........70
Required parameter group .......70
Errormessages...........70
Add a new Group to the end of a Group List
(QzhbAddGroupToList) API ........71
Authorities and locks .........71
Required parameter group .......71
Errormessages...........72
Remove a Group from a Group List
(QzhbRemoveGroupFromList) API .....72
Authorities and locks .........72
Required parameter group .......72
Errormessages...........72
Retrieve the next User in the Group
(QzhbGetNextUser) API .........73
Authorities and locks .........73
Required parameter group .......73
Errormessages...........73
Locate a User in a Group
(QzhbFindUserInGroup) API .......74
Authorities and locks .........74
Required parameter group .......74
Errormessages...........75
Retrieve the Name of a User
(QzhbGetUserString) API .........75
Authorities and locks .........75
Required parameter group .......75
Errormessages...........76
Add a new user to the end of a Group
(QzhbAddUserToGroup) API .......76
Authorities and locks .........76
Required parameter group .......77
Errormessages...........77
Remove a User or Element from a Group
(QzhbRemoveUserFromGroup) API .....77
Authorities and locks .........78
Required parameter group .......78
Errormessages...........78
This chapter includes detailed information on application programming interfaces (APIs) used with the IBM HTTP Server for AS/400.
AS/400 supports these APIs in C++, Java, Rexx, ILE C, ILE COBOL, and ILE RPG programming languages. Although all APIs are supported in all of these languages, most C CGI applications will only need to use QtmhCvtDB, QzhbCgiParse, or QzhbCgiUtils. This is because ANSI C can work with stdin, stdout, and environment variables directly. ILE C CGI applications use ANSI C function calls to work with stdin, stdout, environment variables, and string functions for parsing stdin and environment variable data.

APIs for CGI applications

To use these APIs in a CGI application, you must bind the CGI program to *SRVPGM QZHBCGI in library QHTTPSVR. ILE C programs must include header file QSYSINC/H(QZHBCGI). AS/400 CGI application programs must be written and compiled in Integrated Language Environment ILE/COBOL.
24 Web Programming Guide V4R5
®
(ILE)/C, ILE/RPG, and

Get Environment Variable (QtmhGetEnv) API

Parameters
Required Parameter Group:
1 Receiver variable Output Char(*) 2 Length of receiver variable Input Binary(4) 3 Length of response Output Binary(4) 4 Request variable Input Char(*) 5 Length of request variable Input Binary(4) 6 Error Code I/O CHAR(*)
The QtmhGetEnv API allows you to get the value set by the server for a particular HTTP environment variable.
Required parameter group
Receiver variable
OUTPUT:CHAR(*)
The output variable that contains the value set by the server for the requested environment variable. In CGI input mode %%MIXED%%, this value will be in CCSID 37; otherwise, it will be in the CCSID of the current job. Note that the QUERY_STRING in %%BINARY%% mode is not converted by the server.
Length of receiver variable
INPUT:BINARY(4)
The input variable containing the length of the space provided to receive the environment variables value.
Length of response
OUTPUT:BINARY(4)
The output variable that contains the length of the environment variables value. When the API is unable to determine the value for the requested environment variable, the length of the environment variable value is set to zero. When the size required for the environment variable value is larger than the length of the receiver variable, the size required to receive the value is returned.
Request variable
INPUT:CHAR(*)
The input variable containing the desired environment variables name.
Length of request variable
INPUT:BINARY(4)
The input variable containing the length of the desired environment variables name.
Error Code
I/O:CHAR(*)
Chapter 2. Application Programming Interfaces 25
The structure in which to return error information. For the format of the structure and for details on how to process API errors, see the programming topic in the AS/400 Information Center.
Error messages
CPF24B4 E
Severe Error while addressing parameter list.
CPF3C17 E
Error occurred with input data parameter.
CPF3C19 E
Error occurred with receiver variable specified.
CPF3CF1 E
Error code parameter not valid.
Note: The Environment Variable APIs provide the getenv() (Get Value of
Environment Variable) function necessary to retrieve environment variables in ILE/C. Therefore, programs written in ILE/C do not need to use the QtmhGetEnv() API. This API, for ILE/C, is more difficult to use (and is slower) than the getenv() API on which it is based.

Put Environment Variable (QtmhPutEnv) API

Parameters
Required Parameter Group:
1 Environment string Input Char(*) 2 Length of environment string Input Binary(4) 3 Error Code I/O Char(*)
The QtmhPutEnv API allows you to set or create a job-level environment variable. This is useful for communication between programs running in the same job, such as your program and the Net.Data
®
language environment DTW_SYSTEM.
Required parameter group
Environment string
INPUT:CHAR(*)
The input string of the form: envVar=value. Where envVaris the name of the new or existing environment variable, and valueis the value you wish to set the environment variable. Note that they are both case sensitive. The server expects this value to be in the CCSID of the job.
Length of environment string
INPUT:BINARY(4)
The input variable that contains the length of the environment string parameter. For example, the length of the environment string envVar=value is twelve.
Error Code
I/O:CHAR(*)
26 Web Programming Guide V4R5
The structure in which to return error information. For the format of the structure and for details on how to process API errors, see the programming topic in the AS/400 Information Center.
Error messages
CPF24B4 E
Severe Error while addressing parameter list.
CPF3021 E
The value specified for the argument is not correct.
CPF3C17 E
Error occurred with input data parameter.
CPF3CF1 E
Error code parameter not valid.
CPF3408 E
The address used for an argument is not correct.
CPF3460 E
Storage allocation request failed.
CPF3474 E
Unknown system state.
CPF3484 E
A damaged object was encountered.
Note: The Environment Variable APIs provide the putenv() (Put Value in
Environment Variable) function necessary to set (or create and set) an environment variable. Therefore, programs written in ILE/C do not need to use the QtmhPutEnv() API. This API, for ILE/C, is more difficult to use (and is slower) than the putenv() API on which it is based.

Read from Stdin (QtmhRdStin) API

Parameters
Required Parameter Group:
1 Receiver variable Output Char(*) 2 Length of receiver variable Input Binary(4) 3 Length of response available Output Binary(4) 4 Error Code I/O Char(*)
The QtmhRdStin API allows CGI programs that are written in languages other than C to read from stdin. CGI programs read from stdin when the request from the browser indicates the method that is POST. This API reads what the server has generated as input for the CGI program.
Important!
CGI input data is only available from standard input when the client request is submitted with method POST. There are no standard input data when the method is GET or HEAD. In addition, the Content_Length environment variable is set only when the Request_Method is POST.
Chapter 2. Application Programming Interfaces 27
The program reads all of the data in a single request. This is because the API treats each request as a request for data starting at its beginning. The API handles each request as if it was the only request.
The length of the data returned by QtmhRdStin includes all the data from stdin. This includes line-formatting characters that are normally a part of the POST data as defined by the CGI specification.
Note that the format of this data is different depending on the CGI input mode being used. For %%MIXED%% mode, the data will have American National Standard Code for Information Interchange (ASCII) hexadecimal encoded characters. For %%EBCDIC%% mode, all data including hexadecimal will be in the CCSID of the job. The server performs no conversion for %%BINARY%% mode.
Required parameter group
Receiver variable
OUTPUT:CHAR(*)
The output variable that contains the data read from stdin. In CGI input mode %%MIXED%%, this data is in the CCSID of the job except that the encoded characters %xxare still represented by the ASCII 819 octet. In %%EBCDIC%% mode, this data is in the CCSID of the job, including the escape sequences. In %%BINARY%% mode, the data is in the code page sent by the browser.
Length of receiver variable
INPUT:BINARY(4)
The input variable containing the number of bytes that are to be read from stdin.
Length or response available
OUTPUT:BINARY(4)
The output variable containing the length of the data read from stdin. If there is no data available from stdin, this variable will be set to zero.
Error Code
I/O:Char(*)
The structure in which to return error information. For the format of the structure and for details on how to process API errors, see the programming topic in the AS/400 Information Center.
Error Messages
CPF24B4 E
Severe Error while addressing parameter list.
CPF3C17 E
Error occurred with input data parameter.
CPF3C19 E
CPF3CF1 E
28 Web Programming Guide V4R5
Error occurred with receiver variable specified.
Error code parameter not valid.

Write to Stdout (QtmhWrStout) API

Parameters
Required Parameter Group:
1 Data variable Input Char(*) 2 Length of data variable Input Binary(4) 3 Error Code I/O Char(*)
The QtmhWrStout API provides the ability for CGI programs that are written in languages other than C to write to stdout.
Required parameter group
Data variable
Input:CHAR(*)
The input variable containing the data to write to stdout.
Length of data variable
INPUT:BINARY(4)
The input variable contains the length of the data written to stdout. The length of the data must be larger than 0.
Error Code
I/O:CHAR(*)
The structure in which to return error information. For the format of the structure and for details on how to process API errors, see the programming topic in the AS/400 Information Center.
Error messages
CPF24B4 E
Severe Error while addressing parameter list.
CPF3C17 E
Error occurred with input data parameter.
CPF3CF1 E
Error code parameter not valid.
Note: CGI programs written in the C language do not require a special API to
write data to stdout. The following example shows how a CGI program might write to stdout:
fwrite(buffer,1,sizeof(buffer),stdout);
CGI programs are expected to produce data in the stdout that is formatted according to the CGI interface specification. The QtmhWrStout API provides no line formatting; the user of the API must perform prescribed formatting which includes the requirement for text line characters (such as new line). Errors are not indicated for data that is not formatted per CGI requirements.
Chapter 2. Application Programming Interfaces 29

Convert to DB (QtmhCvtDB) API

Parameters
Required Parameter Group:
1 Qualified database file name Input Char(20) 2 Input string Input Char(*) 3 Length of input string Input Binary(4) 4 Response variable Output Char(*) 5 Length of response variable Input Binary(4) 6 Length of response available Output Binary(4) 7 Response code Output Binary(4) 8 Error Code I/O Char(*)
The QtmhCvtDB API provides an interface for CGI programs to parse CGI input, defined as a series of keywords and their values, into a buffer which is formatted according to a DDS file specification. CGI input data, which comes to the CGI program as character data, will be converted by the QtmhCvtDB API to the data type defined for the keyword by the corresponding field name in the input DDS file. AS/400 language statements, such as the ILE C #pragma mapinc statement, provide the ability to map the returned structure with field names defined in the DDS file. See the appropriate language users guide for details.
Note that the QtmhCvtDB API is not allowed in CGI mode %%BINARY%%.
The following DDS field types are handled:
A Alphanumeric (see note 1)
P Packed Decimal (see note 2)
S Zoned Decimal
F Floating Point
T Time
L Date
Z Timestamp
B Binary (see note 3)
O DBCS
These DDS field types are not handled:
H Hexadecimal (see note 4)
G Graphic (see note 5)
J DBCS (see note 5)
E DBCS (see note 5)
Notes:
1. The VARLEN keyword is not supported.
2. When using a packed decimal field, the #pragma mapinc() must use _P the
option, to create a packed structure.
30 Web Programming Guide V4R5
3. Input to Binary fields is converted to integer. The DDS file specification must
declare zero decimal positions (for example, xB 0, where x is 1-9).
4. ILE C converts hex DDS field data to character fields. Since the input stream to
QtmhCvtDB() is a text string, the hexdata would be converted from text to character fields. Therefore, using the A (Alphanumeric) field type to obtain the same conversion.
Required parameter group
Qualified database file name
Input:CHAR(20)
The input variable containing the name of the database file defining field names and data types for the keywords anticipated in the input to the CGI program. Typically, the database file is generated using DDS to define the fields corresponding to the keywords anticipated in the CGI inputs. The first 10 characters contain the database file name, and the second 10 characters contain the library name.
Input string
INPUT:CHAR(*)
The input variable containing the string of CGI input parameters to be parsed. When the environment variable REQUEST_METHOD indicates that the method is GET, characters up to the first ? are ignored. The string must meet the format requirements for CGI input keyword strings.
Length of input string
INPUT:BINARY(4)
The input variable containing the length of the character string that contains the CGI input parameters to be parsed. The length of the string must be greater than 0.
Response variable
OUTPUT:CHAR(*)
The output variable which is to contain the structure mapped according to the database file describing the input parameters anticipated by the CGI program.
Length of response available
INPUT:BINARY(4)
The input variable containing the total length of the buffer into which the CGI input parameters will be parsed.
Length of response
OUTPUT:BINARY(4)
The output variable that contains the length of the response. If the response variable is too small to contain the entire response, this parameter will be set to the size that is required to contain the entire response.
Response code
OUTPUT:BINARY(4)
A code that indicates the status of the request.
0 All keywords have been translated according the database file.
Chapter 2. Application Programming Interfaces 31
-1 The database file contains definitions for structure fields for which the CGI input has no corresponding keyword.
-2 The CGI input contains one or more keywords for which the database file contains no corresponding field.
-3 A combination of the condition for response codes -1 and -2 has been detected.
-4 An error occurred while converting the CGI input string to the DDS defined data types. The data may or may not be usable.
-5 This API is not valid when a program is not called by the IBM HTTP Server. No data parsing is done.
-6 This API is not valid when operating in %%BINARY%% mode. No data parsing is done.
Error Code
I/O CHAR(*)
The structure in which to return error information. For the format of the structure and for details on how to process API errors, see the programming topic in the AS/400 Information Center.
Error messages
CPF24B4 E
Severe Error while addressing parameter list.
CPF3C17 E
Error occurred with input data parameter.
CPF3C19 E
Error occurred with receiver variable specified.
CPF3CF1 E
Error code parameter not valid.
CPF9810 E
Library &1 not found.
CPF9812 E
File &1 in library &2 not found.
CPF9822 E
Not authorized to file &1 in library &2

Parse QUERY_STRING Environment Variable or Post stdin data (QzhbCgiParse) API

You can use the QzhbCgiParse API to parse the QUERY_STRING environment variable, in the case of the GET method, or standard input, in the case of POST method, for CGI scripts. If the QUERY_STRING environment variable is not set, the QzhbCgiParse API reads the CONTENT_LENGTH characters from its input. All return output is written to its standard output.
You can only call QzhbCgiParse once for the POST method. To use this API with the POST method, you would first want to read all of stdin and assign it to the QUERY_STRING environment variable. You would then change the environment variable REQUEST_METHOD to GET.
32 Web Programming Guide V4R5
Parameters
Required Parameter Group:
1 Command string Input Char(*) 2 Output format Input Char(8) 3 Target Buffer Output Char(*) 4 Length of Target Buffer Input Binary(4) 5 Length of response Output Binary(4) 6 Error Code I/O CHAR(*)
Required parameter group
Command string
Input:CHAR(20)
The command string is a null ended string for flags and modifiers. At least one space must separate each flag. There is a one-character equivalent for each flag. The following flags are supported:
-a[gain] continuation-handle
The continuation-handle is the value returned to the caller in the target buffer when only partial information is returned. This flag is not valid on the first call to this API. It is used to retrieve the next set of information that would have been returned on a previous call if there had been enough space in the target buffer. All other flags must be the same as the previous call. Incomplete or inaccurate information may result if all other flags are not the same.
Note: This flag can only be used for the CGII0200 format.
-k[eywords]
Parses QUERY-STRING for keywords. Keywords are decoded and written to the target buffer, one per line.
-f[orm]
Parses QUERY_STRING as form request. The field names will be set as environment variables with the prefix FORM_. Field values are the contents of the variables.
-v[alue] field-name
Parses QUERY_STRING as form request. Returns only the value of field-name in the target buffer.
-r[ead]
Reads CONTENT_LENGTH characters from standard input and writes them to the target buffer.
-i[nit]
If QUERY_STRING is not set, reads the value of standard input and returns a string that can be used to set QUERY_STRING.
-s[ep] separator
Specifies the string that is used to separate multiple values. If you are using the -value flag, the default separation is newline. If you are using the -form flag, the default separator is a comma (,).
Chapter 2. Application Programming Interfaces 33
-p[refix] prefix
Used with -POST and -form to specify the prefix to use when creating environment variable names. The default is FORM_.
-c[ount]
Used with -keywords, -form, and -value, returns a count of items in the target buffer that is related to these flags:
-keywords
Returns the number of keywords.
-form
Returns the number of unique fields (multiple values are counted as one)
-value field-name
Returns the number of values for field-name. If there is no field that is named field-name, the output is 0.
-number
Used with -keywords, -form, and -value. Returns the specified occurrence in the target buffer related to the following flags:
-keywords
Returns the nth keyword. For example, -2 -keywords writes the second keyword.
-form
Returns all the values of the nth field.
-value field-name
Returns the nth of the multiple values of field field-name.
-POST
Information from standard input is directly decoded and parsed into values that can be used to set environment variables. This flag is the equivalent to consecutive use of the -init and -form options.
-F[sccsid] FileCCSID
The FileCCSID is the name of the file system CCSID used in CCSID conversion when processing the CGI input data. The CGI program wants the data to be returned in this CCSID. It only applies when the server is using %%BINARY%% CGI conversion mode. When an unknown CCSID is set, the current value of the CGI_EBCDIC_CCSID environment variable is used.
-N[etccsid] NetCCSID
The NetCCSID is the network CCSID used in CCSID conversion when processing the CGI input data. This is the CCSID that the data is presumed to be in at this time (as assumed or as set in a charset tag). It only applies when the server is using %%BINARY%% CGI Input mode. When an unknown CCSID is set, the current value of the CGI_ASCII_CCSID environment variable is used.
Output format
INPUT:CHAR(*)
The format of the data to be returned in the target buffer. You must use one of the following format names:
v CGII0100 This format is the free-form format returned to standard output on
other platforms.
v CGII0200 CGI form variable format. This format only applies to the -form
and -POST option.
34 Web Programming Guide V4R5
Target Buffer
OUTPUT:CHAR(*)
This is output buffer that contains the information requested by the command string (if any).
Length of Target Buffer
INPUT:BINARY(4)
The length of the target buffer provided to receive the API output.
Length of Response
OUTPUT:BINARY(4)
The actual length of the information returned in the target buffer.
Error Code
I/O:CHAR(*)
The structure in which to return error information. For the format of the structure and for details on how to process API errors, see the programming topic in the AS/400 Information Center.
CGII0200 Format
Offset Decimal
0 0 BINARY(4) Bytes returned
4 4 BINARY(4) Bytes available
8 8 CHAR(20) Continuation handle
28 1C BINARY(4) Offset to first variable entry
32 20 BINARY(4) Number of variable entries returned
36 24 CHAR(*) Reserved
Note: These fields contain variable entry information and are repeated for each variable entry returned.
Offset Hexadecimal
Type Field
BINARY(4) Length of variable entry (See note)
BINARY(4) Length of variable name (See note)
CHAR(*) Variable name (See note)
BINARY(4) Length of variable value (See note)
CHAR(*) Variable value (See note)
CHAR(*) Reserved (See note)
Field descriptions
Bytes returned The number of bytes of data returned.
Bytes available The number of bytes of data available to be returned. All available
data is returned if enough space is available.
Continuation handle The handle that is returned when more data is available to return, but the target buffer is not large enough. The handle indicates the point in the repository that the retrieval stopped. If the handle is used on the next call to the API (using the -again flag), the API returns more data starting at the point that the handle indicates. This field is set to blanks when all information is returned.
Chapter 2. Application Programming Interfaces 35
Offset to first variable entry The offset to the first variable entry returned. The offset is from the beginning of the structure. If no entries are returned, the offset is set to zero.
Number of variable entries returned The number of variable entries returned. If the target buffer is not large enough to hold the information, this number contains only the number of variables actually returned.
Reserved This field is ignored.
Length of variable entry The length of this variable entry. This value is used in
determining the offset to the next variable entry. Note that this value is always set to a multiple of four.
Length of variable name The length of the variable name for this entry.
Variable name A field name as found in the form data. If the server is using
%%EBCDIC%% or %%MIXED%% CGI mode, this value is in the CCSID of the job. If the server is using %%BINARY%% CGI mode, this value is in the codepage as sent from the browser unless -fsccsid is specified on the API invocation. If -fsccsid is specified, the value is in that CCSID.
Length of variable value The length of the variable value for this entry.
Variable value A field name as found in the form data. If the server is using
%%EBCDIC%% or %%MIXED%% CGI mode, this value is in the CCSID of the job. If the server is using %%BINARY%% CGI mode, this value is in the codepage as sent from the browser unless -fsccsid is specified on the API invocation. If -fsccsid is specified, the value is in that CCSID.
Error messages
CPF24B4 E
Severe Error while addressing parameter list.
CPF3C17 E
Error occurred with input data parameter.
CPF3C19 E
Error occurred with receiver variable specified.
CPF3CF1 E
Error code parameter not valid.
Note: For further information on errors, the joblog for the CGI job may contain
CPF9898 messages (with all English text) describing the error in more detail.

Produce Full HTTP Response (QzhbCgiUtils) API

Use the QzhbCgiUtils API to produce a full HTTP 1.0/1.1 response for non-parsed header CGI programs. This API provides functionality similar to the cgiutils command used by other IBM HTTP Server platforms.
Parameters
Required Parameter Group:
1 Command string Input Char(*) 2 Error code I/O Char(*)
36 Web Programming Guide V4R5
Command string
INPUT:CHAR(*)
The command string is a null ended string of flags and modifiers. Each flag must be separated by at least one space. The following flags are supported:
-nodate
Does not return the Date: header to the browser.
-noel
Does not return a blank line after headers. This is useful if you want other MIME headers after the initial header lines.
-status nnn
Returns full HTTP response with status code nnn, instead of only a set of HTTP headers. Do not use this flag if you only want the Expires: header.
-reason explanation
Specifies the reason line for the HTTP response. You can only use this flag with the -status flag. If the explanation text contains more than one word, you must enclose it in parentheses.
-ct [type/subtype]
Specifies MIME Content-Type header to return to the browser. If you omit the type/subtype, the MIME content type is set to the default text/plan.
-charset character-set
Used with the -ct flag to specify the charset tag associated with the text Content-Types.
-ce encoding
Specifies MIME Content-Encoding header to return to the browser.
-cl language-code
Specifies MIME Content-Language header to return to the browser.
-length nnn
Specifies MIME Content-Length header to return to the browser.
-expires Time-Spec
Specifies MIME Expires header to return to the browser. This flag specifies the time to live in any combination of years, months, days, hours, minutes, and seconds. The time must be enclosed in parentheses. For example:
-expires (2 days 12 hours)
-expires now
Produces an Expires: header that matches the Date: header to return to the browser.
-uri URI
Specifies the Universal Resource Identifier (URI) for the returned document. URI can be considered the same as URL.
-extra xxx: yyy
Specifies an extra header that cannot otherwise be specified.
Error Code
I/O:CHAR(*)
The structure in which to return error information. For the format of the structure and for details on how to process API errors, see the programming topic in the AS/400 Information Center.
Chapter 2. Application Programming Interfaces 37
Error messages
CPF24B4 E
CPF3C17 E
CPF3CF1 E

Configuration APIs

The configuration APIs are in *SRVPGM QZHBCONF in library QHTTPSVR. ILE C programs must include header file QHTTPSVR/H(QZHBCONF).
While each individual API lists its own authorities, the following authorities are needed to run all configuration APIs:
v *OBJOPR, *READ, *ADD, and *EXECUTE to the QUSRSYS library
v *READ, *ADD, *DELETE, *EXECUTE, *OBJOPR, *OBJEXIST, and either
*OBJMGT or *OBJALTER to the QUSERSYS/QATMHTTPC file
v *READ, *ADD, *DELETE, *EXECUTE, *OBJOPR, *OBJEXIST, and either
*OBJMGT or *OBJALTER to the QUSERSYS/QATMHTTPA file
Note: The QUSERSYS/QATMHTTPA file is the administration (ADMIN) server
Severe Error while addressing parameter list.
Error occurred with input data parameter.
Error code parameter not valid.
configuration file.

Convert URL to Path (QzhbCvtURLtoPath) API

Required Parameter Group:
1 Name of Configuration Input Char(10) 2 The URL Input Char(*) 3 Length of the URL Input Binary(4) 4 Path to physical resource Output Char(*) 5 Length of path available Input Binary(4) 6 Actual length of path Output Binary(4) 7 PATH_TRANSLATED Output Char(*) 8 Length of PATH_TRANSLATED
available
9 Actual length of
PATH_TRANSLATED
10 QUERY_STRING Output Char(*) 11 Length of QUERY_STRING
available
12 Actual length of
QUERY_STRING
13 Error Code I/O Char(*)
Threadsafe: Yes
Use the QzhbCvtURLtoPath to convert a URL into the physical resource the webserver serves as a result of a request of this URL. All character input and output data will be in the CCSID of the job.
Input Binary(4)
Output Binary(4)
Input Binary(4)
Output Binary(4)
Authorities and locks
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR and **READ authority to the QUSRSYS/QATMHTTPC file
38 Web Programming Guide V4R5
Required parameter group
Name of Configuration
INPUT; CHAR(10)
The name of the configuration from where to retrieve the information.
The URL
INPUT; CHAR(*)
The URL to convert into a physical resource.
Length of the URL
INPUT; BINARY(4)
The length of the URL.
Path to physical resource
OUTPUT; CHAR(*)
The fully qualified path to the physical resource the web server would serve as a result of a request of this URL.
Length of the path available
INPUT; BINARY(4)
The length of the space provided to receive the path to a physical resource.
Actual length of path
OUTPUT; BINARY(4)
The actual path to the physical resource. When the API is unable to determine a physical resource to convert to, this server sets this value to zero. When the size required for the path is larger than the length of the space provided, the actual space required for the path is returned.
PATH_TRANSLATED
OUTPUT; CHAR(*)
The value of PATH_TRANSLATED.
Length of PATH_TRANSLATED available
INPUT; BINARY(4)
The length of the space provided to receive PATH_TRANSLATED.
Actual length of PATH_TRANSLATED
INPUT; BINARY(4)
The actual length of the PATH_TRANSLATED. When API is unable to determine PATH_TRANSLATED, this value will be set to zero. When the size required for PATH_TRANSLATED is larger than the length of the space provided, the actual space required is returned.
QUERY_STRING
OUTPUT; CHAR(*)
The value of QUERY_STRING.
Length of QUERY_STRING available
INPUT; BINARY(4)
The length of the space provided to receive QUERY_STRING.
Actual length of QUERY_STRING
OUTPUT; BINARY(4)
Chapter 2. Application Programming Interfaces 39
The actual length of the QUERY_STRING. When the API is unable to determine QUERY_STRING, this value will be set to zero. When the size required for QUERY_STRING is larger than the length of the space provided, the actual space required is returned.
Error Code
I/O; CHAR(*)
The structure in which to return error information. For the format of the structure and for details on how to process API errors, see the programming topic in the AS/400 Information Center.
Error messages
CPF3C17 E
Error occurred with input data parameter.
CPF3CF1 E
Error code parameter not valid.
HTPA104 E
Server configuration not found or is unreadable.

Retrieve Directive (QzhbRetrieveDirective) API

Required Parameter Group:
1 Name of Configuration Input Char(10) 2 Name of the directive Input Char(*) 3 Length of the directive name Input Binary (4) 4 Number of values returned Output Binary (4) 5 Format name Input Char(8) 6 Buffer containing length/value
pairs
7 Length of space available Input Binary (4) 8 Actual length of total values
returned
9 Error code I/O Char(*)
Threadsafe: Yes
Output Char(*)
Output Binary (4)
Use the QzhbRetrieveDirective to retrieve the current value of a configuration directive. Some directives can have more than one value. If it does, a list of values is returned in the order found in the configuration file. All character input and output data will be in the CCSID of the job.
Note: The use of this API is discouraged. Support for other more comprehensive
Authorities and locks
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR and **READ authority to the QUSRSYS/QATMHTTPC file
Required parameter group
Name of configuration
INPUT; CHAR(10)
The name of the configuration from which to retrieve the information.
40 Web Programming Guide V4R5
configuration APIs (that are descibed in this section) have been provided. This API is being provided for compatibility.
Name of the directive
INPUT; CHAR(*)
The name of the directive to retrieve.
Length of the directive name
INPUT; BINARY(4)
The length of the directive name.
Number of values returned
OUTPUT; BINARY(4)
The number of values returned in the output buffer. This value will be zero if the server finds no matching directives or if there was not enough space available for all the values.
Format name
INPUT; CHAR(8)
The format of the data returned.The possible format names follow:
RTVD0100 Retrieve length/value pairs.
Buffer containing values
OUTPUT; CHAR(*)
The buffer containing the output.
Length of space available
INPUT; BINARY(4)
The length of the space provided to receive the directive values.
Actual length of total values returned
OUTPUT; BINARY(4)
The actual length of the total values returned. When the API is unable to find a matching directive, this value will be set to zero. When the size required for the total value is larger than the length of the space provided, the actual space required for the total number of values is returned.
Error Code
I/O;CHAR(*)
The structure in which to return error information. For the format of the structure and for details on how to process API errors, see the programming topic in the AS/400 Information Center.
Format of Output Data
The buffer will contain data in one of the following formats:
RTVD0100 Format: The server uses the RTVD0100 format to retrieve a list of length and value pairs for the directive specified.
Offset Type Field
Dec Hex
0 0 BINARY(4) Displacement to next
entry
4 4 CHAR(*) Value
Chapter 2. Application Programming Interfaces 41
Error messages
CPF3C17 E
Error occurred with input data parameter
CPF3CF1 E
Error code parameter not valid.
HTPA104 E
Server configuration not found or is unreadable.

Retreive a list of all Configuration Names (QzhbGetConfigNames) API

Required Parameter Group:
1 buf Output Char(*) 2 buf_size Input Binary(4) 3 buf_actlen Output Binary(4) 4 count Output Binary(4) 5 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbGetConfigNames API to retrieve a list of all server configuration names defined on your AS/400.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR and *READ authority to the QUSRSYS/QATMHTTPC file
Required parameter group
buf
OUTPUT:CHAR(*)
The buffer where the configuration names are placed.
buf_size
INPUT:BINARY(4)
The size of the buffer in bytes.
buf_actlen
OUTPUT:BINARY(4)
The length of all configuration names. Any data beyond the size specified in buf_size parameter is truncated.
count
OUTPUT:BINARY(4)
The total number of server configuration names, whether or not they fit in the buffer.
errcode
I/O:CHAR(*)
42 Web Programming Guide V4R5
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
CPF9802 E
Not authorized to object &2 &3.

Create a Configuration (QzhbCreateConfig) API

Required Parameter Group:
1 name Input Char(10) 2 basedname Input Char(10) 3 basedfile Input Char(8) 4 basedf_len Input Binary(4) 5 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbCreateConfig API to create a new configuration. You can create a new configuration based on an existing configuration by passing in an existing configuration name. You can also create an empty configuration file or a configuration file that is based on a text file.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *EXECUTE and *ADD authority to the QUSRSYS library
v *OBJOPR ,*ADD, *DLT, and either *OBJMGT or *OBJALTER authority to the
QUSRSYS/QATMHTTPC file
Required parameter group
name
INPUT:CHAR(10)
The configuration file name. The name can be up to 10 characters long (padded with blanks).
basedname
INPUT:CHAR(10)
The name of an existing configuration file used to create a new configuration file. The name can be up to 10 characters long (padded with blanks). To create an empty configuration, pass a NULL (omit) for this parameter or pass all blanks.
basedfile
INPUT:CHAR(8)
The path to the text file used to create the new configuration. This parameter is omissable.
basedf_len
INPUT:BINARY(4)
Chapter 2. Application Programming Interfaces 43
The length of the basedfile file. A length of 0 means that no basedfile file is passed. If this parameter is greater than 0, basedname cannot also be passed.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
CPFB602 E
Cannot open file.
HTPA001 E
Input parameter &1 not valid.
HTPA104 E
Server configuration &1 not found or is unreadable.
HTPA105 E
Unable to update server configuration &1.
CPF9802 E
Not authorized to object &2 &3.

Delete a Configuration (QzhbDeleteConfig) API

Required Parameter Group:
1 name Input Char(10) 2 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbDeleteConfig API to delete a configuration file.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR, *OBJEXIST, *DLT, and either *OBJMGT or *OBJALTER authority to the
QUSRSYS/QATMHTTPC file
Required parameter group
name
INPUT:CHAR(10)
The configuration file name you want to delete. The name can be up to 10 characters long (padded with blanks).
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
44 Web Programming Guide V4R5
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA104 E
Server configuration &1 not found or is unreadable.
HTPA105 E
Unable to update server configuration &1.
CPF9802 E
Not authorized to object &2 &3.

Read a Configuration File into Memory (QzhbOpenConfig) API

Required Parameter Group:
1 name Input Char(10) 2 writelock Input Binary(4) 3 cfg Output Binary(4) 4 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbOpenConfig API to read a configuration file into memory. A handle to the memory copy of the file is returned, and is used in subsequent API calls to manipulate directives within the file. When the copy of the file is no longer required, the QzhbCloseConfig API is used to free it and optionally write the altered contents out.
Authorities and locks
To invoke this API with a writelock value of 0, the user must have the following authorities:
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR and *READ authority to the QUSRSYS/QATMHTTPC file
To invoke this API with a writelock value of 1, the user must have the following authorities:
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR, *OBJMGR, *ADD, and *DLT authority to the QUSRSYS/QATMHTTPC
file
Required parameter group
name
INPUT:CHAR(10)
The name of the configuration file you want to read into memory. The name can be up to 10 characters long (padded with blanks).
writelock
INPUT:BINARY(4)
The value 0 (false) or 1 (true). If the value is 1, an exclusive read object lock is obtained on this member of the QUSRSYS/QATMHTTPC file. No other user can update the configuration while the lock is in place. The lock is released when the QzhbCloseConfig API is called. If the value is 0, no lock is placed on the member.
Chapter 2. Application Programming Interfaces 45
Note: You must specify a writelock of 1, and successfully obtain the object
lock, in order to later specify a write argument of 1 on the QzhbCloseConfig API. If you do not have this lock, the QzhbCloseConfig API will not write the contents of the configuration file.
cfg
OUTPUT:BINARY(4)
The handle returned to the loaded configuration file.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA104 E
Server configuration &1 not found or is unreadable.
HTPA105 E
Unable to update server configuration &1.
CPF9802 E
Not authorized to object &2 &3.

Free a Configuration File from Memory (QzhbCloseConfig) API

Required Parameter Group:
1 cfg Input Binary(4) 2 write Input Binary(4) 3 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbCloseConfig API to free a configuration file in memory. Optionally, the data in memory can first be written to the configuration file where it was read from by the QzhbOpenConfig API.
Authorities and locks
None.
Required parameter group
cfg
INPUT:BINARY(4)
The configuration file handle, returned by a call to API QzhbOpenConfig.
write
INPUT:BINARY(4)
46 Web Programming Guide V4R5
When 1 is specified in the write parameter, the directives are written to the configuration file before being freed from memory. If a write fails, the memory is not freed, the handle is still valid, and error information is returned.
When 0 is specified, the dirrectives are not written, but the object lock is released if it was obtained at QzhbOpenConfig time.
Note: In order to specify a write of 1, you must have previously specified a
writelock of 1 on the QzhbOpenConfig API.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA105 E
Unable to update server configuration &1.
HTPA106 E
Input configuration handle not valid.

Search for a Main Directive (QzhbFindDirective) API

Required Parameter Group:
1 cfg Input Binary(4) 2 value Input Char(*) 3 value_len Input Binary(4) 4 startdir Input Binary(4) 5 num Input Binary(4) 6 case_sens Input Binary(4) 7 dir Output Binary(4) 8 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbFindDirective API to find a main directive in a configuration file previously opened by a call to the QzhbOpenConfig API. If a directive is found, a handle to the directive is returned and can be used on subsequent calls to other APIs.
Authorities and locks
None.
Required parameter group
cfg
INPUT:BINARY(4)
The handle returned by a call to the QzhbOpenConfig API.
value
INPUT:BINARY(4)
Chapter 2. Application Programming Interfaces 47
The character string for matching to a directive. Only as many tokens (words delimited by a space) as are provided are matched. Any extra tokens either on the value string or the directive being considered for a match will not be compared. For example a value string of Port 1234 junk will match a directive of Port 1234. To match any directive, including comment lines, pass either a NULL pointer or a string with no tokens on it such as a 0 length string.
value_len
INPUT:BINARY(4)
The length of the value string.
startdir
INPUT:BINARY(4)
The directive handle that specifies where to begin searching for a match. The directive immediately following this one is the first one searched. If the startdir parameter is passed as a NULL, then searching begins at the beginning of the configuration file. If the startdir parameter is not passed as a NULL (omitted), then the startdir parameter must be the handle to a main directive, and cannot be a subdirective.
num
INPUT:BINARY(4)
The number of the match to be returned. The num parameter must be a number greater than or equal to 0. If the value is 0, then the last matching directive is returned. If the value is 1, the first match is returned. If the value is 2, the second match is returned, and so on.
case_sens
INPUT:BINARY(4)
The value of 0 (false) or a value of 1 (true), indicating whether matching of tokens in the search string should be case sensitive. In most cases, except where certain case-sensitive file paths are being considered, this parameter should be 0 (false). Note that the searches for the actual directive name, which is the first token on the line, is never case-sensitive.
dir
OUTPUT:BINARY(4)
The handle to the matched directive. If no directive is found, error HTPA110 is returned.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA106 E
48 Web Programming Guide V4R5
Input configuration handle not valid.
HTPA107 E
Input directive handle in parameter &1 not valid.
HTPA108 E
Input directive handle in parameter &1 not a main directive.
HTPA110 E
No matching directive found.

Search for a Subdirective under Main Directive (QzhbFindSubdirective) API

Required Parameter Group:
1 cfg Input Binary(4) 2 maindir Input Binary(4) 3 value Input Char(*) 4 value_len Input Binary(4) 5 startdir Input Binary(4) 6 num Input Binary(4) 7 case_sens Input Binary(4) 8 dir Output Binary(4) 9 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbFindSubdirective API to find a subdirective in a configuration file previously opened by a call to the QzhbOpenConfig API. If a subdirective is found, a handle to the subdirective is returned and can be used on subsequent calls to other APIs.
Authorities and locks
None.
Required parameter group
cfg
INPUT:BINARY(4)
The handle returned by a call to the QzhbOpenConfig API.
maindir
INPUT:BINARY(4)
The handle to a main directive previously returned by a call to the QzhbFindDirective API. If the startdir parameter is not NULL, then the maindir parameter can be passed as NULL since the main directive is implied by startdir. If both the maindir and startdir parameters are passed, then the startdir parameter must specify the handle to a subdirective under maindir.
value
INPUT:CHAR(*)
The character string for matching to a subdirective. Only as many tokens (words delimited by a blank) as are provided are matched. Any extra tokens either on the value string or the subdirective being considered for a match will not be compared. For example a value string of Port 1234 junk will match a directive of Port 1234. To match any subdirective, including comment lines, pass either a NULL pointer or a string with no tokens on it such as a 0 length string.
Chapter 2. Application Programming Interfaces 49
value_len
INPUT:BINARY(4)
The length of the value string.
startdir
INPUT:BINARY(4)
The subdirective handle that specifies where to begin searching for a match. The subdirective immediately following this one is the first one searched. If the startdir parameter is passed as a NULL (omitted), then searching begins at the beginning of the subdirective list for maindir. If the startdir parameter is not NULL, then the maindir parameter can be passed as NULL since the main directive is implied by startdir. If both the maindir and startdir parameters are passed, then startdir must be the handle to a subdirective under maindir.
num
INPUT:BINARY(4)
The number of the match to be returned. The num parameter must be a number greater than or equal to 0. If the value is 0, then the last matching subdirective is returned. If the value is 1, the first match is returned. If the value is 2, the second match is returned, and so on.
case_sens
INPUT:BINARY(4)
The value of 0 (false) or a value of 1 (true), indicating whether matching of tokens in the search string should be case sensitive. In most cases, except where certain case-sensitive file paths are being considered, this parameter should be 0 (false). Note that the searches for the actual subdirective name, which is the first token on the line, is never case-sensitive.
dir
OUTPUT:BINARY(4)
The handle to the matched subdirective, if found.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA106 E
Input configuration handle not valid.
HTPA107 E
Input directive handle in parameter &1 not valid.
HTPA108 E
HTPA109 E
50 Web Programming Guide V4R5
Input directive handle in parameter &1 not a main directive.
Input directive handle in parameter &1 not a subdirective.
HTPA110 E
No matching directive found.

Return Details of a Main Directive or Subdirective (QzhbGetDirectiveDetail) API

Required Parameter Group:
1 cfg Input Binary(4) 2 dir Input Binary(4) 3 buf Output Char(*) 4 buf_size Input Binary(4) 5 buf_actlen Output Binary(4) 6 hassubdirs Output Binary(4) 7 issubdir Output Binary(4) 8 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbGetDirectiveDetail API to extract detail information about a main directive or subdirective.
Authorities and locks
None.
Required parameter group
cfg
INPUT:BINARY(4)
The handle returned to the configuration file by a call to API QzhbOpenConfig.
dir
INPUT:BINARY(4)
The handle to a main directive or subdirective, as returned by the QzhbFindDirective or QzhbFindSubdirective APIs.
buf
OUTPUT:CHAR(*)
The buffer where the directive string is placed.
buf_size
INPUT:BINARY(4)
The size of the buffer in bytes.
buf_actlen
OUTPUT:BINARY(4)
The actual length of the directive string. Any data beyond the size specified in the buf_size parameter is truncated.
hassubdirs
OUTPUT:BINARY(4)
The value is set to 1 (true) when dir is a main directive and there are subdirectives under it. If dir is not a main directive, the value is set to 0 (false).
Chapter 2. Application Programming Interfaces 51
issubdir
OUTPUT:BINARY(4)
The value is set to 1 (true) when dir is a subdirective. The value is set to 0 (false) when dir is a main directive.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA106 E
Input configuration handle not valid.
HTPA107 E
Input directive handle in parameter &1 not valid.

Add a Main Directive or Subdirective (QzhbAddDirective) API

Required Parameter Group:
1 cfg Input Binary(4) 2 value Input Char(*) 3 value_len Input Binary(4) 4 position Input Binary(4) 5 reldir Input Binary(4) 6 newdir Output Binary(4) 7 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbAddDirective API to add a new main directive or subdirective to a configuration file located in memory.
Authorities and locks
None.
Required parameter group
cfg
INPUT:BINARY(4)
The handle returned by a call to API QzhbOpenConfig.
value
INPUT:CHAR(*)
The character string of the new directive. This string is not validated in any way to ensure that it is a valid directive.
52 Web Programming Guide V4R5
value_len
INPUT:BINARY(4)
The length of the value string. The length must be greater than or equal to 1.
position
INPUT:BINARY(4)
The number indicating the insertion position for the new directive. See Table 3 for more information.
reldir
INPUT:BINARY(4)
The handle to a main directive or subdirective, or a NULL (omitted). See Table 3 for more information.
newdir
OUTPUT:BINARY(4)
The handle of the newly added main directive or subdirective.
errcode
I/O:CHAR(*)
The structure in which to return error information.
The position and reldir parameters must be considered together. The combination of these parameters determine whether the directive being added is a main directive or subdirective and where in the configuration file it is to be added. Table 3 shows the behavior for the various combinations of these parameters.
Table 3. Using the reldir and position parameters.
reldir value
NULL (omitted) Not valid Not valid Inserted as a main
Main directive Inserted as a
Position 0 (Before)
main directive directly proceeding redir.
Position 1 (After)
Inserted as a main directive directly following reldir.
Position 2 (At front) Position 3 (At end)
directive at the beginning of the file.
Inserted as a subdirective at the front of this directive’s subdirective list.
Inserted as a main directive at the end of the file.
Inserted as a subdirective at the end of this directive’s subdirective list, but proceeding the close brace subdirective ″}″.
Position 4 (Automatic)
Inserted as a main directive at a location determined by internal rules of directive ordering. Use this mode when you are not sure where to insert.
Inserted as a subdirective at a location in this directive’s subdirective list as determined by internal rules of subdirective ordering. Use this mode when you are not sure where to insert.
Chapter 2. Application Programming Interfaces 53
Table 3. Using the reldir and position parameters. (continued)
reldir value
Subdirective Inserted as a
Position 0 (Before)
subdirective directly proceeding reldir.
Position 1 (After)
Inserted as a subdirective directly following reldir.
Position 2 (At front) Position 3 (At end)
Not valid Not valid Not valid
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA106 E
Input configuration handle not valid.
HTPA107 E
Input directive handle in parameter &1 not valid.
HTPA111 E
Combination of insertion position and relative directive not valid.
Position 4 (Automatic)

Remove a Main Directive or Subdirective (QzhbRemoveDirective) API

Required Parameter Group:
1 cfg Input Binary(4) 2 dir Input Binary(4) 3 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbRemoveDirective API to remove a main directive or subdirective from a configuration file located in memory.
Authorities and locks
None.
Required parameter group
cfg
INPUT:BINARY(4)
The handle returned by a call to API QzhbOpenConfig.
dir
INPUT:BINARY(4)
The handle to the main directive or subdirective to be removed.
errcode
I/O:CHAR(*)
54 Web Programming Guide V4R5
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA106 E
Input configuration handle not valid.
HTPA107 E
Input directive handle in parameter &1 not valid.

Replace a Main Directive or Subdirective (QzhbReplaceDirective) API

Required Parameter Group:
1 cfg Input Binary(4) 2 dir Input Binary(4) 3 value Input Char(*) 4 value_len Input Binary(4) 5 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbReplaceDirective API to replace the string value of a main directive or subdirective in a configuration file located in memory.
Authorities and locks
None.
Required parameter group
cfg
INPUT:BINARY(4)
The handle returned by a call to the QzhbOpenConfig API.
dir
INPUT:BINARY(4)
The handle to the main directive or subdirective to be changed.
value
INPUT:CHAR(*)
The character string to replace the directive. This string is not validated in any way to ensure that it is a valid directive.
value_len
INPUT:BINARY(4)
The length of the value string must be greater than or equal to 1.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Chapter 2. Application Programming Interfaces 55
Error messages
CPF3CF1 E
CPF3C1D E
HTPA001 E
HTPA106 E
HTPA107 E

Server instance APIs

The server instance APIs are in *SRVPGM QZHBCONF in library QHTTPSVR. ILE C programs must include header file QHTTPSVR/H(QZHBCONF).
While each individual API lists its own authorities, the following authorities are needed to run all server instance APIs:
v *OBJOPR, *READ, *ADD, and *EXECUTE to the QUSRSYS library
v *READ, *ADD, *DELETE, *EXECUTE, *OBJOPR, *OBJEXIST, and either
*OBJMGT or *OBJALTER to the QUSERSYS/QATMHINSTC file
v *READ, *ADD, *DELETE, *EXECUTE, *OBJOPR, *OBJEXIST, and either
*OBJMGT or *OBJALTER to the QUSERSYS/QATMHINSTA file
Error code parameter not valid.
Input variable length in parameter &1 not valid.
Input parameter &1 not valid.
Input configuration handle not valid.
Input directive handle in parameter &1 not valid.
Note: The QUSERSYS/QATMINSTA file is the administration (ADMIN) server
instance file.

Retrieve a list of all Server Instances (QzhbGetInstanceNames) API

Required Parameter Group:
1 buf Output Void 2 buf_size Input Binary(4) 3 format Input Char(8) 4 buf_actlen Output Binary(4) 5 count Output Binary(4) 6 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbGetInstanceNames API to retrieve a list of all server instance names defined on your AS/400.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR and *READ authority to the QUSRSYS/QATMHINSTC file
Required parameter group
buf
OUTPUT:VOID
56 Web Programming Guide V4R5
The buffer where the instance names are placed. Specify a buffer name up to 10 characters (padded with blanks) as necessary.
buf_size
INPUT:BINARY(4)
The size of the buffer in bytes.
format
INPUT:CHAR(8)
The format of the data returned. The possible format names follow:
INSN0100
buf_actlen
OUTPUT:BINARY(4)
The length of all the instance names. Any data beyond the size specified in the buf_size value is truncated by the system.
count
OUTPUT:BINARY(4)
The total number of instance names.
errcode
I/O:CHAR(*)
The structure in which to return error information.
INSN0100 Format
INSN0100 Format:
Offset Type Field
Dec Hex
0 0 CHAR(10) Instance name
10 0A CHAR(2) Reserved
12 0C BINARY(4) Running status
Field descriptions
Instance name
The 10 character name of the server instance, padded with blanks.
Running status
An integer value of 1 if this instance is currently running. An integer value of 0 if this server instance is currently stopped.
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
CPF3C21 E
Format name &1 not valid.
Chapter 2. Application Programming Interfaces 57
HTPA001 E
Input parameter &1 not valid
CPF9802 E
Not authorized to object &2 in &3.

Look up Server Instance Data (QzhbGetInstanceData) API

Required Parameter Group:
1 name Input Char(10) 2 buf Output Void 3 buf_size Input Binary(4) 4 format Input Char(8) 5 buf_actlen Output Binary(4) 6 running Output Binary(4) 7 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbGetInstanceData API to get detailed data about a specific server instance. This data includes whether the instance is currently running and all start-up data.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR and *READ authority to the QUSRSYS/QATMHINSTC file
Required parameter group
name
INPUT:CHAR(10)
The server instance name. The name can be up to 10 characters long (padded with blanks).
buf
OUTPUT:VOID
The buffer where the instance names are placed. The buffer is defined based on the format parameter. You may omit this parameter.
buf_size
INPUT:BINARY(4)
The size of the buffer in bytes. A size of 0 can be specified meaning that no data is returned in the buffer, but the running variable is still set to indicate the running status of the instance.
format
INPUT:CHAR(8)
The format in which the data should be returned. The possible format names follow:
INSD0100
buf_actlen
OUTPUT:BINARY(4)
58 Web Programming Guide V4R5
The number of bytes available for instance data. For the INSD0100 format, the buf_actlen value is 1104 bytes.
running
OUTPUT:BINARY(4)
Indicates if the server instance is running. If the instance is running, the running parameter is set to 1. If the instance is not running, the running parameter is set to 0. The running parameter can be omitted. If this value is omitted (null), the running status is not queried by this API, and no performance penalty is incurred for finding this information. See Retrieve a list of all Server Instances (QzhbGetInstanceNames) APIon page 56 for another method to query the running status of all instances.
errcode
I/O:CHAR(*)
The structure in which to return error information.
INSD0100 Format
Offset Decimal
0 0 CHAR(10) Configuration
10 0A CHAR(10) Autostart
20 14 BINARY(4) Min threads
24 18 BINARY(4) Max threads
28 1C BINARY(4) CCSID
32 2A CHAR(10) Outgoing table name
42 20 CHAR(10) Outgoing table library
52 3E CHAR(10) Incoming table name
62 34 CHAR(10) Incoming table library
72 48 CHAR(512) Access log file
584 248 CHAR(512) Error log file
1096 448 BINARY(4) Non-secure port
1100 44C BINARY(4) Secure port
Offset Hexadecimal
Type Field
Field descriptions
Note: In the descriptions below, *GLOBAL indicates that the global server
parameter value for this field is used by the instance, and *CFG indicates that the value from the named configuration file is used. All character strings are padded with blanks as necessary, and are NOT null terminated.
Configuration
The 10 character name of the configuration used for this instance.
Autostart
Indicates if the instance starts automatically. It is a 10 character string that contains *NO, *YES, or *GLOBAL.
Min threads
The minimum number of threads to use for this instance. It is an integer from 0 to 999, where 0 means the *CFG value.
Chapter 2. Application Programming Interfaces 59
Max threads
The maximum number of threads to use for this instance. It is an integer from -1 to 999, where 0 means the *CFG value and -1 means *NOMAX (no maximum).
CCSID
The character set to be used by the instance. It is an integer from 0 to 65533, where 0 means *GLOBAL.
Outgoing table name
The name of the table object to use as the EBCDIC to ASCII conversion table for outgoing data. It is a 10 character name or *GLOBAL.
Outgoing table library
The library containing the EBCDIC to ASCII table. This field is blank if the outgoing table name is *GLOBAL.
Incoming table name
The name of the table object to use as the ASCII to EBCDIC conversion table for incoming data. It is a 10 character name or *GLOBAL.
Incoming table library
The library containing the ASCII to EBCDIC table. This field is blank if the incoming table name is *GLOBAL.
Access log file
The path to the access log file as a 512 character string. This is an IFS type path name in the job CCSID, or *CFG.
Error log file
The path to the access log file as a 512 character string. This is an IFS type path name in the job CCSID, or *CFG
Non-secure port
The TCP port where the server will listen for normal HTTP connections. It is an integer from 0 to 65535, where 0 means *CFG.
Secure port
The TCP port where the server will listen for secure SSL HTTPS connections. It is an integer from 0 to 65535, where 0 means *CFG.
Error messages
CPF3C21 E
Format name &1 not valid.
CPF3CF1 E
Error code parameter not valid.
CPF9802 E
Not authorized to object &2 in &3.
HTPA001 E
Input parameter &1 not valid.
HTPA101 E
Server instance &1 not found or is unreadable.

Change Server Instance Data (QzhbChangeInstanceData) API

Required Parameter Group:
60 Web Programming Guide V4R5
1 name Input Char(10) 2 idata Input Void
3 idata_size Input Binary(4) 4 format Input Char(8) 5 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbChangeInstanceData API to change the start-up data for a specific server instance. This API provides a structure for input, even when not changing values, to all start-up data values to be set for a server instance. This API is typically used following a call to the QzhbGetInstanceData API, and after one or more fields in the structure have been modified.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR, *OBJMGT, *ADD, and *DLT authority to the
QUSRSYS/QATMHINSTC file
Required parameter group
name
INPUT:CHAR(10)
The server instance name. The name can be up to 10 characters long (padded with blanks).
idata
INPUT:VOID
The buffer where the instance data is stored. The contents of the buffer is defined by the format specifed by the format parameter. All fields in the idata parameter must contain valid values.
idata_size
INPUT:BINARY(4)
The size of the idata structure. The minimum size is the length needed for the INSD0100 format, 1104 bytes.
format
INPUT:CHAR(8)
The format of the data returned. The possible format names follow:
INSD0100
For information about the INSD0100 format, see INSD0100 Formaton page 59.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
Chapter 2. Application Programming Interfaces 61
CPF3C1D E
Input variable length in parameter &1 not valid.
CPF3C21 E
Format name &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA101 E
Server instance &1 not found or is unreadable.
HTPA102 E
Unable to update server instance &1.
HTPA103 E
Value in field &1 of the instance data structure not valid.

Create a Server Instance (QzhbCreateInstance) API

Required Parameter Group:
1 name Input Char(10) 2 idata Input Void 3 idata_size Input Binary(4) 4 format Input Char(8) 5 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbCreateInstance API to create a new server instance. This API provides a structure for input to all start-up data values to be set for a new server instance. Use this API following a call to the QzhbGetInstanceData API to create an instance based on an existing instance.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *EXECUTE and *ADD authority to the QUSRSYS library
v *OBJOPR, *ADD, *DLT, and either *OBJMGT or *OBJALTER authority to the
QUSRSYS/QATMHINSTC file
Required parameter group
name
INPUT:CHAR(10)
The name for the new server instance you want to create. The name can be up to 10 characters long (padded with blanks).
idata
INPUT:VOID
The buffer where the instance data is stored. The contents of the buffer is defined by the format specifed by the format parameter. All fields in the idata parameter must contain valid values.
idata_size
INPUT:BINARY(4)
The size of the idata structure. The minimum size is the length needed for the INSD0100 format, 1104 bytes.
62 Web Programming Guide V4R5
format
INPUT:CHAR(8)
The format of the data returned. The possible format names follow:
INSD0100
For information about the INSD0100 format, see INSD0100 Formaton page 59.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
CPF3C21 E
Format name &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA102 E
Unable to update server instance &1.
HTPA103 E
Value in field &1 of the instance data structure not valid.
CPF9802 E
Not authorized to object &2 &3.

Delete a Server Instance (QzhbDeleteInstance) API

Required Parameter Group:
1 name Input Char(10) 2 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbDeleteInstance API to delete a server instance.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *EXECUTE authority to the QUSRSYS library
v *OBJOPR, *OBJEXIST, *DLT and either *OBJMGT or *OBJALTER authority to the
QUSRSYS/QATMHINSTC file
Required parameter group
name
INPUT:CHAR(10)
The server instance name you want to delete. The name can be up to 10 characters long (padded with blanks).
Chapter 2. Application Programming Interfaces 63

Group file APIs

errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid
HTPA101 E
Server instance &1 not found or is unreadable.
HTPA102 E
Unable to update server instance &1.
CPF9802 E
Not authorized to object &2 &3.
The group file APIs are in *SRVPGM QZHBCONF in library QHTTPSVR. ILE C programs must include header file QHTTPSVR/H(QZHBCONF).

Create a new Group File (QzhbCreateGroupList) API

Required Parameter Group:
1 path Input Binary(4) 2 path_len Input Binary(4) 3 grplist Output Binary(4) 4 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbCreateGroupList API to create a new empty group file, and return a handle to that empty in-memory version of the file. Normally this API would be followed by calls to the QzhbAddGroupToList and QzhbAddUserToGroup APIs, followed by the QzhbCloseGroupList API to write group information out.
Upon successful completion of this API, a new group list handle is returned. This is a handle much like the one returned by the QzhbOpenGroupList API against an already existing file, with a writelock argument of 1 (TRUE). After a call to the QzhbCreateGroupList API the new file is left open for write access and the QzhbCloseGroupList API can be invoked with a write argument of 1. For more details about the writelock argument, see Read a Group File into Memory (QzhbOpenGroupList) APIon page 65.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *X authority to each directory in the path of the specified group file
v *WX authority to the last directory in the path that will contain the group file
path
64 Web Programming Guide V4R5
Required parameter group
path
INPUT:BINARY(4)
The path to the group file to be created in the Integrated File System. You can specify an absolute or relative path to the working directory. This path should be in the job CCSID.
path_len
INPUT:BINARY(4)
The length of the path string.
grplist
OUTPUT:BINARY(4)
The variable that receives the integer handle of the newly created empty group list. Subsequent API calls use this handle.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA202 E
Unable to update group file &1.
HTPA208 E
Group file &1 already exists.

Read a Group File into Memory (QzhbOpenGroupList) API

Required Parameter Group:
1 path Input Binary(4) 2 path_len Input Binary(4) 3 writelock Input Binary(4) 4 grplist Output Binary(4) 5 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbOpenGroupList API to read in an existing group file, and return a handle to an in-memory version of the file. See Free Group File from Memory (QzhbCloseGroupList) APIon page 67 for information about freeing memory and optionally writing the group list information out.
Authorities and locks
To invoke this API, the user must have the following authorities:
v *X authority to each directory in the path of the specified group file
Chapter 2. Application Programming Interfaces 65
v *R authority to the group file for a writelock value of 0
v *RW authority to the group file for a writelock value of 1
Required parameter group
path
INPUT:BINARY(4)
The path to the group file to be created in the Integrated File System. You can specify an absolute or relative path to the working directory.
path_len
INPUT:BINARY(4)
The length of the path string.
writelock
If the value is 1, the group file is opened for write access with a lock and kept open. No other user is allowed to update the group file while the lock is in place. The group file is closed and the lock released by invoking the QZHbCloseGroupList API. If the value is 0, then the following are true:
v The group file is opened for read access
v A lock is not placed on the group file
v The group file does not remain open
Note: You must specify a writelock of 1 in order to later specify a write
argument of 1 on the QzhbCloseGroupList API. If you do not hold the group file open for write, the QzhbCloseGroupList API will not write the contents of the file.
grplist
OUTPUT:BINARY(4)
The handle of the group list. Subsequent API calls use this handle.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA201 E
Group file &1 not found or is unreadable.
HTPA202 E
66 Web Programming Guide V4R5
Unable to update group file &1.

Free Group File from Memory (QzhbCloseGroupList) API

Required Parameter Group:
1 grplist Input Binary(4) 2 write Input Binary(4) 3 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbCloseGroupList API to free the memory of an in-memory copy of a group file. You can optionally write the in-memory version of the group list back to the group file before the memory is freed.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList API or QzhbOpenGroupList API.
write
INPUT:BINARY(4)
The value of 0 (false) or a value of 1 (true), indicating whether or not to write the contents of the in-memory group list back to the group file before freeing it from memory. If you specify 1 for this parameter, and the write fails, the memory is not freed and the grplist handle is still valid.
Note: In order to specify a write value of 1, you must have previously used
either the QzhbCreateConfigList API or specified a writelock of 1 on the QzhbOpenGroupList API. If these conditions are not met, the contents of the file are not written.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA202 E
Unable to update group file &1.
HTPA203 E
Input group list handle in parameter &1 not valid.
Chapter 2. Application Programming Interfaces 67

Retrieve the next Group in the Group List (QzhbGetNextGroup) API

Required Parameter Group:
1 grplist Input Binary(4) 2 prev_grp Input Binary(4) 3 grp Output Binary(4) 4 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbGetNextGroup API to retrieve the next group from an in-memory group list.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
prev_grp
INPUT:BINARY(4)
The group handle returned from a call to the QzhbGetNextGroup, QzhbGetNextGroup, QzhbFindGroupInList, or QzhbAddGroupToList API, that returns the group immediately following this group. A handle of 0 returns the first group in the group list.
grp
OUTPUT:BINARY(4)
The group name handle returned if the next group is found in the list. If no next group exists, then error HTPA206 is returned.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
Input group list handle in parameter &1 not valid.
HTPA204 E
Input group handle in parameter &1 not valid.
HTPA206 E
68 Web Programming Guide V4R5
Group file &1 not found in group list.

Locate a named group in a Group List (QzhbFindGroupInList) API

Required Parameter Group:
1 grplist Input Binary(4) 2 group Input Binary(4) 3 group_len Input Binary(4) 4 grp Output Binary(4) 5 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbFindGroupInList API to search an in-memory group list for a named group.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
group
INPUT:CHAR(*)
The group name for which the system will search the list . The group name is case-sensitive. Leading and trailing blanks are included with the name.
group_len
INPUT:BINARY(4)
The length of the group name string. The length must be greater than or equal to 1.
grp
OUTPUT:BINARY(4)
The group name handle returned if the named group was found in the list.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
Input group list handle in parameter &1 not valid.
Chapter 2. Application Programming Interfaces 69
HTPA206 E
Group file &1 not found in group list.

Retrieve the Name of a Group (QzhbGetGroupName) API

Required Parameter Group:
1 grplist Input Binary(4) 2 grp Input Binary(4) 3 buf Output Char(*) 4 buf_len Input Binary(4) 5 buf_actlen Output Binary(4) 6 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbGetGroupName API to retrieve the name of a group using the group handle.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
grp
INPUT:BINARY(4)
The group handle returned from a call to the QzhbGetNextGroup, QzhbFindGroupInList, or QzhbAddGroupToList API.
buf
OUTPUT:BINARY(4)
The buffer to receive the group name.
buf_len
OUTPUT:BINARY(4)
The size of the buffer.
buf_actlen
OUTPUT:BINARY(4)
The actual length of the group name. If the buf_actlen value is greater than the buf_len value, the data is truncated.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
70 Web Programming Guide V4R5
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
Input group list handle in parameter &1 not valid.
HTPA204 E
Input group handle in parameter &1 not valid.

Add a new Group to the end of a Group List (QzhbAddGroupToList) API

Required Parameter Group:
1 grplist Input Binary(4) 2 group Input Char(*) 3 group_len Input Binary(4) 4 grp Output Binary(4) 5 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbAddGroupToList API to add a new group to an in-memory group list.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
group
INPUT:CHAR(*)
The group name to add to the list.
group_len
INPUT:BINARY(4)
The length of the group name. The length must be greater than or equal to 1.
grp
OUTPUT:BINARY(4)
The handle of the newly created group, or the handle of an existing group if the named group already exists. Attempting to add a group that already exists is not considered an error by the system.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Chapter 2. Application Programming Interfaces 71
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
Input group list handle in parameter &1 not valid.

Remove a Group from a Group List (QzhbRemoveGroupFromList) API

Required Parameter Group:
1 grplist Input Binary(4) 2 grp Input Binary(4) 3 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbRemoveGroupFromList API to remove a named group, and all the users in that group, from an in-memory group list.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
grp
INPUT:BINARY(4)
The group handle returned from a call to the QzhbGetNextGroup, QzhbFindGroupInList, or QzhbAddGroupToList API.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
HTPA204 E
72 Web Programming Guide V4R5
Input group list handle in parameter &1 not valid.
Input group handle in parameter &1 not valid.

Retrieve the next User in the Group (QzhbGetNextUser) API

Required Parameter Group:
1 grplist Input Binary(4) 2 grp Input Binary(4) 3 prev_usr Input Binary(4) 5 usr Output Binary(4) 6 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbGetNextUser API to retrieve the next user from a group.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
grp
INPUT:BINARY(4)
The group handle returned from a call to the QzhbGetNextGroup, QzhbFindGroupInList, or QzhbAddGroupToList API.
prev_usr
INPUT:BINARY(4)
The user handle for an existing user that returns the user immediately following this user. A handle of 0 returns the first user in the group list.
usr
OUTPUT:BINARY(4)
The handle of the user if a next user is found in the group. If no next user is found, error HTPA207 is returned.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
Input group list handle in parameter &1 not valid.
HTPA204 E
Input group handle in parameter &1 not valid.
Chapter 2. Application Programming Interfaces 73
HTPA205 E
Input user handle in parameter &1 not valid.
HTPA207 E
User &1 not found in group.

Locate a User in a Group (QzhbFindUserInGroup) API

Required Parameter Group:
1 grplist Input Binary(4) 2 grp Input Binary(4) 3 user Input Char(*) 4 user_len Input Binary(4) 5 usr Output Binary(4) 6 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbFindUserInGroup API to search an in-memory group for a specific user.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
grp
INPUT:BINARY(4)
The group handle returned from a call to the QzhbGetNextGroup, QzhbFindGroupInList, or QzhbAddGroupToList API.
user
INPUT:CHAR(*)
The user name for which the system will search the group . The user name is case-sensitive. Leading and trailing blanks are included with the name.
user_len
INPUT:BINARY(4)
The length of the user string. The length must be greater than or equal to 1.
usr
OUTPUT:BINARY(4)
The handle of the user if it was found in the group.
errcode
I/O:CHAR(*)
The structure in which to return error information.
74 Web Programming Guide V4R5
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
Input group list handle in parameter &1 not valid.
HTPA204 E
Input group handle in parameter &1 not valid.
HTPA207 E
User &1 not found in group.

Retrieve the Name of a User (QzhbGetUserString) API

Required Parameter Group:
1 grplist Input Binary(4) 2 grp Input Binary(4) 3 usr Input Binary(4) 4 buf Output Char(*) 5 buf_len Input Binary(4) 6 buf_actlen Output Binary(4) 7 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbGetUserString API to retrieve the name string of a group member given the user handle, as returned by the QzhbGetNextUser, QzhbFindUserInGroup, or QzhbAddUserToGroup API.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
grp
INPUT:BINARY(4)
The group handle returned from a call to the QzhbGetNextGroup, QzhbFindGroupInList, or QzhbAddGroupToList API.
usr
INPUT:BINARY(4)
The user handle returned from a call to the QzhbGetNextUser, QzhbFindUserInGroup, or QzhbAddUserToGroup API.
Chapter 2. Application Programming Interfaces 75
buf
OUTPUT:CHAR(*)
The buffer to receive the user string.
buf_len
INPUT:BINARY(4)
The size of the buffer.
buf_actlen
OUTPUT:BINARY(4)
The actual length of the user string. If the buf_actlen value is greater than the buf_len value, the data is truncated by the system.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
Input group list handle in parameter &1 not valid.
HTPA204 E
Input group handle in parameter &1 not valid.
HTPA205 E
Input group handle in parameter &1 not valid.

Add a new user to the end of a Group (QzhbAddUserToGroup) API

Required Parameter Group:
1 grplist Input Binary(4) 2 grp Input Binary(4) 3 user Input Char(*) 4 user_len Input Binary(4) 5 usr Output Binary(4) 6 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbAddUserToGroup API to add a new user to an in-memory group.
Authorities and locks
None.
76 Web Programming Guide V4R5
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
grp
INPUT:BINARY(4)
The group handle returned from a call to the QzhbGetNextGroup, QzhbFindGroupInList, or QzhbAddGroupToList API.
user
INPUT:CHAR(*)
The user name to be added to the group.
user_len
INPUT:BINARY(4)
The length of the user string. The length must be greater than or equal to 1.
usr
OUTPUT:BINARY(4)
The handle of the newly created user, or the handle of an existing user if the named user already exists in the group. Attempting to add a user that already exists is not considered an error by the system.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
CPF3C1D E
Input variable length in parameter &1 not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
Input group list handle in parameter &1 not valid.
HTPA204 E
Input group handle in parameter &1 not valid.

Remove a User or Element from a Group (QzhbRemoveUserFromGroup) API

Required Parameter Group:
1 grplist Input Binary(4) 2 grp Input Binary(4) 3 usr Input Binary(4)
Chapter 2. Application Programming Interfaces 77
4 errcode I/O Char(*)
Threadsafe: Yes
Use the QzhbRemoveUserFromGroup API to remove a user from an in-memory group.
Authorities and locks
None.
Required parameter group
grplist
INPUT:BINARY(4)
The group list handle returned from a call to the QzhbCreateGroupList or QzhbOpenGroupList API.
grp
INPUT:BINARY(4)
The group handle returned from a call to the QzhbGetNextGroup, QzhbFindGroupInList, or QzhbAddGroupToList API.
usr
INPUT:BINARY(4)
The user handle returned from a call to the QzhbGetNextUser, QzhbFindUserInGroup, or QzhbAddUserToGroup API.
errcode
I/O:CHAR(*)
The structure in which to return error information.
Error messages
CPF3CF1 E
Error code parameter not valid.
HTPA001 E
Input parameter &1 not valid.
HTPA203 E
Input group list handle in parameter &1 not valid.
HTPA204 E
Input group handle in parameter &1 not valid.
HTPA205 E
Input user handle in parameter &1 not valid.
78 Web Programming Guide V4R5

Chapter 3. Using Net.Data to Write CGI Programs for You

This chapter discusses Net.Data for AS/400.
Net.Data is an application that runs on a server and allows you to easily create dynamic web documents that are called web macros. Web macros that are created for Net.Data have the simplicity of HTML with the functionality of CGI-BIN applications. Net.Data makes it easy to add live data to static web pages. Live data includes information that is stored in databases, files, applications, and system services.

Overview of Net.Data

Net.Data is a comprehensive web development environment for the creation of simple dynamic web pages or complex web-based applications. These applications enable browser clients to access data from a variety of sources, such as databases, applications, and system services.
Net.Data consists of a program, the web macro processor, and one or more dynamic libraries, called language environments. The executable input to Net.Data is the web macro.
The web macro processor communicates with IBM HTTP Server through its CGI-BIN interface. The server uses TCP/IP to connect to the Internet. Like other CGI-BIN programs, Net.Data is typically stored in the servers CGI-BIN directory. Net.Data is accessed when a URL received by the server refers to the web macro processor operable, DB2WWW, in the CGI-BIN directory.
Language environments are the web macro processors interface to your data and applications. Each language environment provides a specific interface to a particular resource. For example, Net.Data provides language environments to access DB2 environment.
A web macro is a file that contains a series of statements that are defined by the Net.Data web macro language. These statements can include standard HTML and language environment-specific statements (for example, SQL statements) as well as macro directives. These statements act as instructions to the web macro processor, telling it how to construct dynamic web pages.
When a URL is received by the server that refers to the web macro processor program, the server starts an instance of the web macro processor. It then passes essential information, including the name of the requested web macro and the section of the macro to use. The web macro processor then:
1. Reads and parses through the web macro
2. Interprets all the macro statements, and
3. Dynamically builds the HTML page
When a web macro language %FUNCTION statement is encountered, the web macro processor loads the requested language environment-dynamic library (service program). It then passes language-specific information to the language
®
databases, REXX, and other applications via the SYSTEM language
© Copyright IBM Corp. 1997, 2000 79
environment to be processed. The language environment processes the information and returns the results to the web macro processor.
After all parsing is done and language environment processing is completed, all that remains is pure HTML text. This text can then be interpreted by any browser. The web macro writer has complete control over the level of HTML it uses and what HTML tags are applied. The web macro processor imposes no restrictions. The pure HTML text is passed back to the server, and the web macro processor ends. The resulting HTML text is passed to the browser where the user interacts with it. Further requests from this user or any other user will result in the whole process just described taking place again.
For more detailed information about Net.Data, including how to configure Net.Data for the AS/400 and how to write Net.Data macros and language environments, see this URL:
http://www.as400.ibm.com/netdata
80 Web Programming Guide V4R5

Chapter 4. Using Persistent CGI Programs

Overview of Persistent CGI .........81
Named Activation Groups ........81
Accept-HTSession CGI Header .......81
HTTimeoutCGIHeader.........82

Overview of Persistent CGI

Persistent CGI is an extension to the CGI interface that allows a CGI program to remain active across multiple browser requests and maintain a session with that browser client. This allows files to be left open, the state to be maintained, and long running database transactions to be committed or rolled-back based on end-user input. The AS/400 CGI program must be written using named activation groups which allows the program to remain active after returning to the server. The CGI program notifies the server it wants to remain persistent using the Accept-HTSessionCGI header as the first header it returns. This header defines the session ID associated with this instance of the CGI program and is not returned to the browser. Subsequent URL requests to this program must contain the session ID as the first parameter after the program name. The server uses this ID to route the request to that specific instance of the CGI program. The CGI program should regenerate this session ID for each request. It is strongly recommended that you use Secure Sockets Layer (SSL) for persistent and secure business transaction processing.

Named Activation Groups

CGI programs can be built using named activation groups by specifying a name on the ACTGRP parameter of the CRTPGM or CRTSRVPGM commands. In doing this, the initial call to the program within the job will still have the startup cost of activating the program. However, an activation group is left active after the program has exited normally. All storage associated with that program is still allocated and in last-usedstate. The program is not initializated when it is called again. In addition, for the ILE C runtime, all settings are in last-usedstate, such as signal(), strtok(). The RCLACTGRP command is used to end a named activation group. Use the DSPJOB OPTION(*ACTGRP) command to display all the activation groups for the job. All ILE languages running on AS/400 can use this mechanism to enable persistence for their CGI programs.
Considerations for using Persistent CGI
Programs..............82
Persistent CGI Program Example ......83
For additional information about activation groups see, ILE Concepts, SC41-5606 book.

Accept-HTSession CGI Header

This header specifies the session handle associated with this instance of the Persistent CGI program. This session handle is used to route back subsequent requests to that program and must be unique, or the server will not honor the persistence request. A message is logged in the error log of the server.
Accept-HTSession = "Accept-HTSession" ":" handle
When the server receives this header, the CGI job servicing the request will be reserved in a persistent state. Only requests coming in with that session handle in the URL are routed back to that instance of the CGI program. The URL must be in the following format:
© Copyright IBM Corp. 1997, 2000 81
/path/cgi-name/handle/rest/of/path
Where handle is an exact match of the handle provided in the Accept-HTSession CGI header for the program cgi-name.
Note: The cgi-name that is being resolved is the name as it appears in the URL. It
is not necessarily the actual name of the program being started on the system. This is to remain consistent with the name resolution performed by the server.

HTTimeout CGI Header

The HTTimeout header is for the CGI program to define the amount of time, in minutes, that this CGI program wants to wait for a subsequent request. If not specified, the value specified on the PersistentCGITimeout directive is used. If specified, it takes precedence over the PersistentCGITimeout directive, but the server will not wait longer than the time specified on the MaxPersistentCGITimeout directive. This allows individual CGI programs to give users more time to respond to lengthy forms or explanations. However, it still gives the server ultimate control over the maximum time to wait.
HTTimeout = "HTTimeout" ":" minutes
The time-out value is a non-negative decimal integer, representing the time in minutes. This header must be preceded by an Accept-HTSessionheader, if not, it is ignored. If you omit the header, the default time-out value for the server is used. When a CGI program is ended because of a time-out, a message is logged in the error log of the server.

Considerations for using Persistent CGI Programs

You should be aware of the following considerations when using persistent CGI programs:
v The web administrator can limit the number of persistent CGI programs that the
server supports by using the MaxPersistentCGI configuration directive.
v There are some job or thread-level resources that the server code running in the
CGI job usually manipulates (directly or indirectly) on behalf of CGI programs. The following attributes will (potentially) change across calls:
Environment variables the server sets
Stdin/Stdout/Stderr file descriptors
User profile
Library list
v The server will not set the rest of the job attributes set by the server, and
therefore, will maintain state across calls if changed by the CGI program. Note, however, that the CGI program must restore the initial state of these values before ending its persistence in order to guarantee compatibility across subsequent server requests:
Job Language, Country, CCSID
Job Priority
Printer/Output Queue
Message Logging
Environment variables set by the CGI program
v For added security, web server administrators can protect their persistent CGI
programs using registered Internet users, thereby forcing authentication by the user before processing each request.
82 Web Programming Guide V4R5

Persistent CGI Program Example

The following example shows a counter that is increased each time the Persistent CGI program is called.
/***********************************************************************/ / This is a sample Persistent CGI program */ / This program is invoked by a URL */ / http://hostname/cgi-bin/samplePersistent.pgm?bin=1) */ /***********************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h>
#define BUFSIZE 1024 unsigned int MAXINPUT = BUFSIZE; /* Maximum input data.*/
int count=1;
int main() {
char *pt; char carac[2]=" "; int bin=1;
freopen("", "r", stdin); /* You need to re-open the stdin for the Persistent CGI Program
pt=getenv("QUERY_STRING"); carac[0]=pt[4]; bin=atoi(carac);
if(bin == 1) { printf("Accept-HTSession: webpg101101 \n"); printf("Content-type: text/html \n\n"); printf("<html><title>Test persistent CGI</title><body>"); printf("<h2> The first form</h2>"); printf("<form action=\"/cgi-bin/webpg101.pgm/webpg101101\" "); printf("method=\"GET\"> "); printf("<input type=HIDDEN NAME=BIN VALUE=2>"); printf("<input type=reset value=Reset>"); printf("</form></body></html>"); count++; } if(bin == 2) { pt=getenv("QUERY_STRING"); printf("Accept-HTSession: webpg101101 \n"); printf("Content-type: text/html \n\n"); printf("<html><title> Test persistent CGI</title><body>"); printf("<h2> The second form</h2>"); printf(" Valor count: %i",count); printf("Query string: %s",pt); printf("<form action=\"/cgi-bin/webpg101.pgm/webpg101101\" "); printf("method=\"GET\"> "); printf("<input type=HIDDEN NAME=BIN VALUE=3>"); printf("<h2>Persisten CGI si funcionan</h2>"); printf("<input type=submit value=Execute>"); printf("</form></body></html>"); count++; } if(bin == 3) { printf("Accept-HTSession: webpg101101 \n"); printf("Content-type: text/html \n\n"); printf("<html><title> Test persistent CGI</title><body>"); printf("<h2> The third form</h2>");
Chapter 4. Using Persistent CGI Programs 83
printf(" Valor count: %i",count); printf("<form action=\"/cgi-bin/webpg101.pgm?bin=4/webpg101101\" "); printf("method=\"GET\"> "); printf("<h2>Persisten CGI si funcionan</h2>"); printf("<input type=HIDDEN NAME=BIN VALUE=4>"); printf("<input type=submit value=Execute>"); printf("</form></body></html>"); count++; } if(bin == 4) { printf("Accept-HTSession: webpg101101 \n"); printf("Content-type: text/html \n\n"); printf("<html><title> Test persistent CGI</title><body>"); printf("<form action=\"/cgi-bin/webpg101.pgm?bin=5/webpg101101\" "); printf("method=\"GET\"> "); printf("<h2> The fourth form</h2>"); printf(" Valor count: %i",count); printf("<h2>Persisten CGI si funcionan</h2>"); printf("<input type=HIDDEN NAME=BIN VALUE=5>"); printf("<input type=submit value=Execute>"); printf("</form></body></html>"); count++; } if(bin == 5) { printf("Accept-HTSession: webpg101101 \n"); printf("Content-type: text/html \n\n"); printf("<html><title> Test persistent CGI</title><body>"); printf("<form action=\"/cgi-bin/webpg101.pgm?bin=6/webpg101101\" "); printf("method=\"GET\"> "); printf("<h2> The fifth form</h2>"); printf(" Valor count: %i",count); printf("<h2>Persisten CGI si funcionan</h2>"); printf("<input type=HIDDEN NAME=BIN VALUE=6>"); printf("<input type=submit value=Execute>"); printf("</form></body></html>"); count++; } (bin == 6) { printf("Accept-HTSession: webpg101101 \n"); printf("Content-type: text/html \n\n"); printf("<html><title> Test persistent CGI</title><body>"); printf("<h2> The sixth form</h2>"); printf(" Valor count: %i",count); printf("<h2>Persisten CGI si funcionan</h2>"); printf("</body></html>"); } fflush(stdout); return 0; }
84 Web Programming Guide V4R5

Chapter 5. Enabling your AS/400 to run CGI programs

How to enable the server to run CGI programs . . 85 Using directives for security and access control . . 86
Thedefaultfailrule ..........87
Explicit CGI enablement .........87
ServerrunsonlyCGIprograms.......87
CGIprogramconsiderations.........87
This chapter discusses the specific steps you need to take to enable your AS/400 for Common Gateway Interface (CGI) programs.

How to enable the server to run CGI programs

AS/400 stores some CGI programs in QSYS.LIB. You can write the programs in C++, Rexx, Java, ILE-C, RPG, or COBOL. If the UserID directive is not active, the server profile QTMHHTP1 needs access to the *PGM object and all objects the program accesses. If the UserID directive is active, the UserID profile needs access to the *PGM object and all objects the program accesses. The Exec directive is required in the HTTP configuration to run a CGI program on the server.
Here is a summary of the steps you need to take to enable your AS/400 system to run CGI programs:
1. Decide for which CGI mode you will write your program.
2. Write the C++, Rexx, Java, ILE-C, RPG, or COBOL program.
3. Compile your program.
4. Create the program object using CRTPGM. Add the Bind Service program,
QHTTPSVR/QZHBCGI when the program uses the server APIs (QtmhWrStOut, QtmhRdStdIn, QtmhCvtDB, QtmhGetEnv, QtmhPutEnv QzhbCgiParse, or QzhbCgiUtils).
5. Using the WRKHTTPCFG command, add an Exec directive that either
specifies the actual library where the program is stored or maps to the library where the program is stored. Specify the CGI mode for your program. The following directive is the library where the program is stored and also indicates to the server to use EBCDIC mode:
Exec /QSYS.LIB/nnnnnnnn.LIB/* %%EBCDIC%%
Where nnnnnnnn is the library where the CGI program is stored.
The following directive maps to the library where the program is stored.
Exec /CGI-BIN/* /QSYS.LIB/nnnnnnnn.LIB/* %%EBCDIC%%
The advantage of using the mapping directives is that the actual location of documents and programs is masked. Also, by setting the /cgi-bin values correctly for Pass, Exec and Redirect, there is less chance of finding the wrong directive.
Access to program object is *USE for QTMHHTP1 or *PUBLIC. You must set *USE for QTMHHTP1 for the access to the program object, or you must specify a user ID on a Userid directive in the server configuration. Setting the access to *PUBLIC *USE would enable the server to run the CGI program, regardless of whether you specify a user ID in the server configuration.
6. Store the HTML file on the AS/400 system by doing one of the following,
depending on the file system in which you wish to store the document:
v To store it in the AS/400 Source physical file:
© Copyright IBM Corp. 1997, 2000 85
a. Add a Pass directive using the WRKHTTPCFG command.
Pass /sample /qsys.lib/samplel.lib/samplef.file/samplem.mbr
Where samplel is the library, samplef is the file, and samplem is member name in which the AS/400 stores this document.
b. Set the source type of samplem member to HTML(CHGPFM).
Access to file is *USE for QTMHHTTP or *PUBLIC(GRTOBJAUT).
v To store it in the Integrated File System webtest directory:
a. Add a Pass directive using the WRKHTTPCFG command.
Pass /sample /webtest/sample.html
where webtest is an integrated file system directory, and sample.html is the document.
b. Access to file is *R for QTMHHTTP or *PUBLIC(CHGAUT).
v To store it in IFS QOpenSys/webtest directory:
a. Add a Pass directive using the WRKHTTPCFG command.
Pass /sample /qopensys/webtest/sample.html
where webtest is an integrated file system directory in QOpenSys file system.
b. Access to file is *R for QTMHHTTP or *PUBLIC(CHGAUT).
v To store it in the QDLS folder:
a. Add a Pass directive using the WRKHTTPCFG command.
Pass /sample /qdls/webtest/sample.htm
Where webtest is a QDLS folder, and sample.htm is the document.
b. Access to file is *R for QTMHHTTP or *PUBLIC(CHGAUT).
7. Add QTMHHTTP to AS/400 directory entry(WRKDIRE).
8. Finally, still using WRKHTTPCFG, enable POST in your HTTP configuration
file. POST must be enabled in order for the server to serve CGI programs that read standard input.
9. Start or restart the server.
10. Point your web browser to the URL for the HTML document on the server
where hostname is the fully qualified host domain name of your AS/400 system.
http://hostname/sample
Note: For REXX programs, you only need to indicate in the EXEC directive the
path and the file name. REXX CGI execs must reside in database files named REXX or QREXSRC. For example:
EXEC /rexx/* /QSYS.LIB/AS400CGI.LIB/QREXSRC.FILE/*
The URL is :
http://hostname/rexx/samplecgi.rexx

Using directives for security and access control

The server administrator controls the behavior of the server. The server will not do anything that the server administrator has not explicitly configured it to do.
Several features of the server ensure that the administrator maintains this control:
86 Web Programming Guide V4R5
v The default fail rule means that only requests that are authorized by the web
administrator are honored; other requests will fail.
v Explicit CGI enablement means that no CGI programs will run unless
specifically authorized
v Only CGI programs are run
v Only the read HTTP methods GET, POST, and HEAD are supported

The default fail rule

The server rejects, by default, all incoming requests unless the URL, as translated by any preceding Map directives, matches a Pass, Redirect, or Exec directive that has been explicitly coded by the server administrator:
v A match with a Pass directive enables the server to serve a document.
v A match with a Redirect directive causes the server to return a 302 response,
found in the HTTP response to the client application. This HTTP response header field contains a location with the redirect request. The HTTP request that matches a Redirect directive causes no data to be accessed. A subsequent request generated by a client could cause data to be accessed.
v A match with an Exec directive enables the server to run a CGI program on
behalf of the client.
v A match with a Service directive enables the server to run a server API program
on behalf of the client.

Explicit CGI enablement

The server will not run a user-defined CGI program unless the server administrator has explicitly enabled it by coding an Exec directive. The server administrator can, for example, limit CGI requests to a specific library in QSYS.LIB.
Important!
It is the server administrators responsibility to verify that any CGI program that is enabled does not violate the customers security policies for the AS/400 system on which the server is running.
IBM recommends that the HTTP administrator move the DB2WWW *PGM (the Net.Data CGI program) from the QHTTPSVR library to its own CGI library. This allows users to run the CGI program while limiting access to the QHTTPSVR library. Do not move any Include files from the QHTTPSVR
library.

Server runs only CGI programs

To run properly, programs that are called by the server must conform to the server CGI interface. When the server is enabled to call a particular program on behalf of a remote HTTP client application, the program is called and the output is returned through the server CGI interface.

CGI program considerations

You need to understand that the security environment defined by the server configuration directives that apply to your CGI programs.
Chapter 5. Enabling your AS/400 to run CGI programs 87
If the CGI program is covered by a protection directive that calls for basic authentication, the user must supply a user ID and password before the CGI program is allowed to run. The other protection subdirectives determine the following:
v How the server validates the user ID and password
v What security environment the CGI program runs in
The subdirectives might tell the browser to treat the user ID as an AS/400 user profile and to validate the password against it. In addition, the Userid subdirective might be used to cause the server job to run under a specified AS/400 user profile or the one the user entered. The following example protection setup would cause the user ID to be treated as an AS/400 user profile, and to switch to that profile when starting the CGI program:
Protection example1 {
AuthType Basic Userid %%CLIENT%% PasswdFile %%SYSTEM%%
}
If Userid %%SERVER%% had been specified, the CGI program will run under the QTMHHTP1 user profile. If Userid FRED had been specified, the CGI program would run under the FRED user profile.
Alternatively, the PasswdFile subdirective can identify a validation list. For example:
PasswdFile qgpl/valist1
Validation lists contain a set of user IDs, their associated password, and optionally other application-specific information. In this example, the server would authenticate the user by comparing the specified user ID and password against the specified validation list. If the user ID exists in the validation list and the password matches, the CGI program would run under the QTMHHTP1 user profile.
Validation lists can be created through the CRTVLDL command. CGI or other programs can add, remove, find, or change entries through a set of APIs documented in the programming topic in the AS/400 Information Center. By using validation lists, the CGI program can registerusers and associate other information with each entry while at the same time using the basic authentication functions of the HTTP server to authenticate requests.
88 Web Programming Guide V4R5

Chapter 6. Sample programs (in Java, C, and RPG)

This chapter contains samples of coding in Java, C, and RPG languages.
You can locate other programming samples through the following uniform resource locator (URL):
http://www.as400.ibm.com/tstudio/index.htm

Example of Java language CGI program

The samplejava program takes environmental and form variables and displays them back to the browser.
import java.io.DataInputStream; import java.util.Hashtable; import java.util.StringTokenizer;
class samplejava {
int x; int index; Hashtable cgi_vars = null;
// String table with all the Environment Variables
String[] EnvVar = { "GATEWAY_INTERFACE",
"AUTH_TYPE",
"SERVER_NAME", "SERVER_SOFTWARE", "SERVER_PROTOCOL", "SERVER_PORT", "PATH_INFO", "PATH_TRANSLATED", "SCRIPT_NAME", "DOCUMENT_ROOT", "REMOTE_HOST", "REMOTE_ADDR",
"REMOTE_USER", "REMOTE_IDENT", "HTTP_FROM", "HTTP_ACCEPT", "HTTP_USER_AGENT", "HTTP_REFERER", "REQUEST_METHOD", "CONTENT_TYPE", "CONTENT_LENGTH", "QUERY_STRING"};
© Copyright IBM Corp. 1997, 2000 89
samplejava() {
String userMethod; String cl; cl = new String(); // Get the REQUEST_METHOD variable (POST or GET) userMethod = System.getProperty("REQUEST_METHOD");
if (userMethod != null) {
} else {
if (userMethod.equalsIgnoreCase("POST")) {
System.out.println("Server method not supporting"); System.exit(0);
} else {
// if the method is GET if (userMethod.equalsIgnoreCase("GET")) {
// Get the Value of Query String
cl = System.getProperty("QUERY_STRING"); } else {
errMsg("Invalid REQUEST_METHOD specified"); System.exit(0);
}
}
// Print No method errMsg ("No REQUEST_METHOD specified"); System.exit(0);
}
if (cl == null ) {
} else {
}
}
errMsg ("No user data"); System.exit(0);
// fill the Hash table with the user values
cgi_vars = parseArguments(cl);
90 Web Programming Guide V4R5
Loading...