TCP V2
TCP V2
User’s Manual
Volume 2
041001 • 019-0144-A
This manual (or an even more up-to-date revision) is available for free download
at the Z-World website: www.zworld.com.
Dynamic C TCP/IP User’s Manual
Volume 2
Part Number 019-0144–A • Printed in U.S.A.
©2004 Z-World Inc. • All rights reserved.
Z-World reserves the right to make changes and
improvements to its products without providing notice.
Trademarks
Dynamic C is a registered trademark of Z-World Inc.
Windows® is a registered trademark of Microsoft Corporation
Z-World, Inc.
2900 Spafford Street
Davis, California 95616-6800
USA
Telephone: 530.757.3737
Fax: 530.757.3792 or 530.753.5141
www.zworld.com
The TCP/IP User’s Manual is intended for embedded system designers and support professionals
who are using a Rabbit-based controller board. Most of the information contained here is meant
for use with Ethernet-enabled boards, but using only serial communication is also an option.
Knowledge of networks and TCP/IP (Transmission Control Protocol/Internet Protocol ) is
assumed. For an overview of these two topics a separate manual is provided, An Introduction to
TCP/IP. A basic understanding of HTML (HyperText Markup Language) is also assumed. For
information on this subject, there are numerous sources on the Web and in any major book store.
The Dynamic C implementation of TCP/IP comprises several libraries. The main library is
DCRTCP.LIB. As of Dynamic C 7.05, this library is a light wrapper around DNS.LIB,
IP.LIB, NET.LIB, TCP.LIB and UDP.LIB. These libraries implement DNS (Domain Name
Server), IP, TCP, and UDP (User Datagram Protocol). This, along with the libraries ARP.LIB,
ICMP.LIB, IGMP.LIB and PPP.LIB are the transport and network layers of the TCP/IP pro-
tocol stack.
The Dynamic C libraries:
• BOOTP.LIB
• FTP_SERVER.LIB
• FTP_CLIENT.LIB
• HTTP.LIB
• POP3.LIB
• SMNP.LIB
• SMTP.LIB
• TFTP.LIB
• VSERIAL.LIB
implement application-layer protocols. Except for BOOTP, which is described in volume 1 of the
manual, these protocols are described in volume 2.
All user-callable functions are listed and described in their appropriate chapter. Example programs
throughout both volumes of the manual illustrate the use of all the different protocols. The sample
code also provides templates for creating servers and clients of various types.
To address embedded system design needs, additional functionality has been included in Dynamic
C’s implementation of TCP/IP. There are step-by-step instructions on how to create HTML forms,
allowing remote access and manipulation of information. There is also a serial-based console that
can be used with TCP/IP to open up legacy systems for additional control and monitoring. The
console may also be used for configuration when a serial port is available. The console and HTML
forms are discussed in volume 2.
Multiple interfaces are supported starting with Dynamic C version 7.30.
Introduction 1
2 TCP/IP User’s Manual
2. Web-Enabling Your Application
This chapter, and the next two, describe how to add web browser control to your application. Web-
enabling is a logical and appealing choice for adding a user interface to your application, since the
necessary hardware (an Ethernet or serial port) is available on all Z-World core modules and
SBCs. Most users of your application will be familiar with at least one web browser (Netscape,
Mozilla, Internet Explorer, Opera), with its graphical user interface, so they will be ready to start
controlling your application with minimal training.
This chapter provides an overview of the steps you will need to take to web-enable an application.
Knowledge of browsers, and something of their capability, is assumed. With this knowledge, you
can understand the concepts described in this chapter. The following chapters go into more detail
about the specific libraries; but for simple programs, you may be able to use just the information in
this chapter along with the sample code to write a working application.
Dynamic C provides libraries that implement most of the functions required to implement a web
server, more formally known as an HTTP (HyperText Transfer Protocol) server. (The browser is
formally called an HTTP client). You only need to write code specific to your application, such as
dealing with I/Os and the Rabbit peripheral devices, and possibly some code to help the HTTP
server generate the appropriate responses back to the user’s web browser. In addition, there is a
small amount of “boilerplate” that needs to be written to include and configure the HTTP server
and any ancillary libraries such as the TCP/IP suite and filesystems.
Application
Compile-Time Run-Time Main Application CGI
Initialization Initialization Loop Specifics, I/O Functions
#web
Variables
Metadata
Resources Requests,
MIME Context
Table
Zserver TCP/IP
Rule (Resource Manager)
Table
Authorization
File Systems
Static Dynamic
Resource Resource FS2 FAT
Table Table
Storage
Second Battery-
Program Backed Serial
Flash Flash RAM Flash
2. Runtime initialization. Your main() function needs to call some specific library functions,
once only, when it starts:
• sock_init(). This is always mandatory. It initializes the TCP/IP networking
system.
• sspec_automount(). This is optional. It initializes the available filesystems (FS2
and/or FAT) for use by the resource manager, Zserver.
• http_init(). This is mandatory. It initializes the HTTP server.
• Various functions for setting up a user ID table, the rule table and/or the dynamic
resource table. These are optional, but would be used in the majority of applications.
The user ID table can only be initialized at run time, unlike the other tables that may, at
least partially, be initialized at compile-time.
3. Main loop. The final code in the main() function continuously calls http_handler() and
possibly other functions. This is mandatory, since it allows the HTTP server to process requests
from the network. Other functions may be specific to your application. For example, you may
need to poll an I/O device in order to obtain best performance.
1. This is a necessary optimization. There may be hundreds of individual users; however, the
majority of these would be considered to be in a single “class,” with that class giving equal
access to all its members. Considering the class, i.e., group, as the entity that is requesting a
resource reduces the amount of information that needs to be stored.
Application
Compile-Time Run-Time Main Application CGI
Initialization Initialization Loop Specifics, I/O Functions
#web
Variables
Metadata
Resources Requests,
MIME Context
Table
Zserver TCP/IP
Rule (Resource Manager)
Table
Authorization
File Systems
Static Dynamic
Resource Resource FS2 FAT
Table Table
Storage
Second Battery-
Program Backed Serial
Flash Flash RAM Flash
Application
Compile-Time Run-Time Main Application CGI
Initialization Initialization Loop Specifics, I/O Functions
#web
Variables
Metadata
Resources Requests,
MIME Context
Table
Zserver TCP/IP
Rule (Resource Manager)
Table
Authorization
Optional File Systems
Static Dynamic
Resource Resource FS2 FAT
Table Table
Storage
Figure 2.3. Minimum components for a web-enabled application with dynamic content.
The easiest way to introduce dynamic content is to use the RabbitWeb module and the associated
scripting language. RabbitWeb is included with the RCM3300. It is also available as a Dynamic C
add-on module starting with Dynamic C 8.50. If you do not have RabbitWeb, you can use SSI
instead, which is described in Section 4.5.2.1 ”SSI Feature.” This example, illustrated in
Figure 2.3, assumes that you have RabbitWeb.
The differences between the above code and the toy example in the previous section are in bold-
face. All the differences relate to the use of RabbitWeb. The first addition is a #define of
USE_RABBITWEB. This is necessary in order to include the necessary library code.
Next, there is a modification to the MIME table. The SSPEC_MIME_FUNC macro defines an
entry that says that if the resource name ends with “.html” then the MIME type is text/html (as
before), and there is a special scripting function that must be run by the HTTP server. This script-
ing function is called zhtml_handler; it is provided by the HTTP library. ZHTML is the
unique embedded scripting language that converts script files into ordinary HTML so the browser
can understand it.1
1. Most applications will want to use a different resource suffix to distinguish between “ordinary”
HTML files and script files. The samples provided with dynamic C use .zhtml for script files,
and .html for plain HTML. In this sample, we only have script files, so it is convenient to retain
the .html suffix. The other reason for this relates to the way the HTTP server handles requests
for a directory. If given a URL of “/”, the HTTP server will append “index.html” to determine
the actual resource. We take advantage of this default behavior so that this sample would work
as expected.
This looks like plain HTML, and it is. The only difference is the existence of special commands
flanked by “<?z” and “?>.” In this case, the command simply echos the current value of the web
variable that was registered. The value (binary in the global variable) is converted to ASCII text
by a default printf() conversion, in this case “%d” because the variable is an integer. When
the browser gets the results returned by the HTTP server, it will see
<HTML><HEAD><TITLE>Web Variables</TITLE></HEAD>
<BODY><H1>Web Variables</H1>
<P>The current value of io_state is
50
</P>
</BODY></HTML>
Where the “50” represents the current variable value—of course, it may be any decimal value that
an integer variable could take: -32768 through 32767.
This is still a trivial example, but it is infinitely more real-world than the toy example. We have
introduced the concept of dynamic content, which is required for embedded type applications. One
thing that has been glossed over is how (and even whether) the variable can be updated from the
browser, rather than just within the application. Yes, all #web variables may be updated via the
browser. This requires use of HTML forms, which is a subject covered in the detailed documenta-
tion for RabbitWeb, and in the HTTP library chapter. We will not go over this again here; however,
the possibility of remote updating introduces us to the topic of the next section, access control.
Resources in the static and dynamic resource tables may be set up to have their own specific per-
missions, independent of the rule table itself. Resources in a filesystem may be very numerous
hence a simple one-to-one table would waste a lot of storage. To solve this problem, the rule table
uses a name prefix matching algorithm. Using this technique, entire directories of resources need
only have one rule table entry provided that all resources therein use the same permissions.
Application
Compile-Time Run-Time Main Application CGI
Initialization Initialization Loop Specifics, I/O Functions
#web
Variables
Metadata
Resources Requests,
MIME Context
Table
Zserver TCP/IP
Rule (Resource Manager)
Table
Authorization
File Systems
Static Dynamic
Resource Resource FS2 FAT
Table Table
Storage
Second Battery-
Program Backed Serial
Flash Flash RAM Flash
The main difference between this and the previous diagram is that the Rule Table and User Table
blocks have been activated.
The first parameter specifies the name of the resource to which this rule applies; or rather, the first
characters in the resource name. For clarity, the sample shows the full name. In practice, since
there is only one resource, it would be acceptable to use just “/” instead of “/index.html.”
The second parameter, “Pet,” is an arbitrary string called the “realm.” This is presented to the
browser’s user when prompted for the password, as shown here.
The third and fourth parameters indicate the group(s) that have read and write access to the
resource. Both groups are allowed read access, and none write (0). Note that the resource in this
case is the index.html page, not the variables which may or may not be displayed on it. Since
this web page (actually a ZHTML script) is in program flash, it is obviously not modifiable.
The SERVER_HTTP parameter indicates that this resource is only visible from the HTTP server.
This would be more relevant is there was another server, such as FTP, running concurrently.
1. In this example we also choose to use a rule table. This is not strictly necessary since no filesys-
tem is in use. The alternative is to use a different form of initializing the static resource table,
namely by using the SSPEC_RESOURCE_P_XMEMFILE macro, which allows permission
information to be stored in the static table instead of in the rule table. See Section 3.2.5.3.
This is a nested function call. sauth_adduser() is called first, to add a user called “admin”
with password “dog.” This user is visible to all servers (SERVER_ANY).
The result of this function call is a userID handle, which is the first parameter to
sauth_setusermask(). This function explicitly assigns a group mask to the user. You can
omit this call; however, the default method of assigning group masks is designed to be backward
compatible with old versions of the library, and may not be what you want when using new fea-
tures. You should always use the sauth_setusermask() function for each user ID.
In this example, we have added access control to the code. We do not need to change the ZHTML
script, although in reality you would probably want to. Using the script unchanged, when the user
tries to retrieve index.html, the browser will prompt for a userid and password. If one of the
valid users is entered, then the page will be displayed. Otherwise, the browser will print an error
message saying that access was denied.
If you run the above sample with this script, then the user will be able to attempt an update to the
#web variable, io_state. If the user was “monitor,” that is, not able to make an update, then
the “Sorry” message will be printed. Recall that the access to io_state was set up when the
variable was registered with #web.
You may be asking how the application notices when the #web variable is updated by the
browser, not just in the my_io_polling() function. This is a good question, since the HTTP
server updates the variable just like a normal C variable. The solution to this requires that you
specify an “update” callback function in the #web variable registration. This is described in detail
in the Dynamic C Module document titled, “RabbitWeb: Web-Enabling Your Application;” for the
purposes of this section please just remember that it is easy to do.
Application
Compile-Time Run-Time Main Application CGI
Initialization Initialization Loop Specifics, I/O Functions
#web
Variables
HTTP-X SSI
HTTP
Metadata
Resources Requests,
MIME Context
Table
Zserver TCP/IP
Rule (Resource Manager)
Table
Authorization
File Systems
Static Dynamic
Resource Resource FS2 FAT
Table Table
Storage
As mentioned previously, Zserver implements a virtual filesystem that can be used by an applica-
tion for a clean, consistent interface to the various available methods of resource organization. An
application can also bypass the resource manager and access a filesystem directly. (Note that there
is no arrow in the diagram showing this line of communication.)
When defining user IDs that can use the upload, don't forget to give those users overall write
access using e.g.,
sauth_setwriteaccess(uid, SERVER_HTTP);
Another way to design this application is to have a separate HTML file that contains the form for
the file upload; then instead of having the form for the file upload on the current HTML page, you
put a link to the new page and then apply a permission to allow the new page to be displayed, such
as:
sspec_addrule(“/newpage.html”, “Pet”, admin_group,
admin_group, SERVER_HTTP, SERVER_AUTH_BASIC, NULL);
Application
Compile-Time Run-Time Main Application CGI
Initialization Initialization Loop Specifics, I/O Functions
#web
Variables
Metadata
Resources Requests,
MIME Context
Table
Zserver TCP/IP
Rule (Resource Manager)
Table
Authorization
File Systems
Static Dynamic
Resource Resource FS2 FAT
Table Table
Storage
Battery-
Program Second Backed Serial
Flash Flash RAM Flash
The first change is the substitution of the new server-parsed tags with SSI tags. The next change is
the absence of any error checking. Without RabbitWeb, it is difficult to achieve this same function-
ality. The CGI responsible for the processing the variable update would need to do it. Which
brings us to the next change in this HTML page, the need for a second CGI function.
The ACTION attribute in the FORM tag identifies the new CGI by name, update.cgi. The
FORM tag also has a parameter for the encoding type. When no encoding type is specified, it
defaults to URL-encoded. All new-style CGIs must set the encoding type in the FORM tag to
“multipart/form-data” as shown above.
The other change on this page is the NAME attribute in the first INPUT tag of the second form.
When uploading to an FS2 partition, the mount-point “/fs2” must be prepended to the filename.
The /ext1 part is also prepended to the filename and refers to the second flash. The default CGI
function can now store an uploaded file in a valid FS2 partition.
This chapter is intended to be a detailed description of the resource manager, Zserver, and how it
interfaces to other libraries, such as servers (HTTP, FTP etc.) and filesystems (FS2, FAT). For an
overview, please see Chapter 2. “Web-Enabling Your Application.”
The resource manager, Zserver.lib, contains the structures, functions, and constants to allow
HTTP (Hypertext Transfer Protocol) and FTP (File Transfer Protocol) servers to share data and
user authentication information while running concurrently.
In general, you do not need to know some of the details of Zserver described in this chapter if you
are using the server libraries provided with Dynamic C. Such sections are marked as “advanced,”
and you may skip them unless you are writing a server or filesystem. Some sections are marked
“historical.” They are included to describe how previous versions of the library worked. These
may be skipped for new code.
The basic facility provided by Zserver is the ability to translate resource names (URLs in the case
of HTTP) into references to filesystem and memory objects. The term resource refers to the
objects (files, functions and variables) that are manipulated by the Zserver library on behalf of the
server. A file resource refers specifically to a resource of type file, as opposed to the actual file that
is manipulated by an underlying filesystem (which may not be a resource as such).
Support for HTML forms is also included in Zserver.lib. Starting with Dynamic C 8.50, an
enhanced HTTP server (RabbitWeb) is available that has an easy-to-use interface for form genera-
tion and no limitations on the form layout. See the document titled "RabbitWeb, To Web-Enable
Embedded Applications" for more information on this enhanced HTTP server.
Zserver supports the concept of a virtual file system. This is modeled on the Unix directory struc-
ture.
typedef struct {
char extension[10];
char type[HTTP_MAXNAME];
int (*fptr)(/* HttpState* */);
} MIMETypeMap;
For example, to create an HTTP server that can serve files with html or gif extensions, the follow-
ing declaration is required in the application code:
SSPEC_MIMETABLE_START
SSPEC_MIME(".html", "text/html"),
SSPEC_MIME(".gif", "image/gif"),
SSPEC_MIMETABLE_END
Use of the above macros is the recommended method for maintaining forward compatibility. For
more information, see Section 3.2.5.2 "Static MIME Type Table." All these macros are doing is
generating the correct C syntax for a static constant initializer.
Note that servers that do not implement MIME, such as FTP, do not require a MIME table to be
defined. Currently, this table is required only for HTTP.
The structure fields are described below. The #ifdef expression adds some fields to the
ServerSpec structure if the HTML form functionality provided by Zserver is included by the
web server application. These fields are not described below. For more details, Section 4.5.4
"HTML Forms Using Zserver.lib."
Starting with Dynamic C 8.50, enhanced support is provided for HTML forms with the purchase
of the Dynamic C RabbitWeb Module. This module provides an easy to develop web interface for
your embedded device and allows for complete flexibility in form layout. See the document titled
"RabbitWeb, To Web-Enable Embedded Applications" for more information on this enhanced
HTTP server.
In older versions of Dynamic C, it was necessary to explicitly create the static resource table by
doing something like this:
const HttpSpec http_flashspec[] = {
...
};
in your main application code (filling in the entries, of course). Starting with Dynamic C 8.50,
there is new recommended syntax for creating these resources, using the
SSPEC_RESOURCETABLE* series of macros. This new method is recommended for maintain-
ing future compatibility. For more information, see Section 3.2.5.3 "Static Resource Table."
type This field tells the server if the entry is a file, variable or function
(SSPEC_FILE, SSPEC_VARIABLE , SSPEC_FUNCTION,
etc.).
format sprintf() format for a variable, or form title for a form, or base
address for SSPEC_ROOTFILE. For SSPEC_LINK, points to a
string containing the linked-to resource name.
There are some other fields that are conditionally included if HTTP forms are in use. These are not
generally relevant. See the library source for details.
realm Pointer to realm string of the resource. It is only used by HTTP serv-
ers, but can be used for other purposes.
servermask A 16-bit mask with a bit set for each server that can access this re-
source. NB: for backwards compatibility, if this is set to zero then
all servers are allowed.
mimetype MIME type for this resource, or NULL. If NULL, the MIME type
will be derived from the file name using the MIMETypeMap table
called http_types. If not found in that table, the first entry in
that table will be used (for backward compatibility.)
prefix Prefix of resource name(s) which are associated with this rule table
entry. If there are multiple entries which match a resource name,
then the rule with the longest matching prefix is used.
server This field identifies the server, for example, SERVER_HTTP. This
is one of the few cases where only a single server bit should be set.
rootdir This field is a pointer to the root directory This is usually “/” if the
whole namespace is tobe accessible. Otherwise, it may be, for ex-
ample, “/A” to restrict access to just the first DOS FAT partition.
The first and last character must be “/”!
cwd[] This field is an array containing the current working directory. This
would normally contain the root directory as a prefix. The first and
last character must be “/”!
dfltname This field points to a file name to be used as a resource name suffix
when the first parameter refers to a directory name.
The ServerContext structure helps support more powerful resource access control. It is
needed by several of the new API functions that deal with resource retrieval and control, as well as
functions that perform directory navigation.
There are two functions that return a ServerContext struct: http_getcontext() and
http_getContext(). The latter is for use in CGI functions.
These functions can be used with other API functions that need the context structure. For example:
sspec_open(“MyFile”, http_getcontext(servno), O_READ, 0);
will open “MyFile” for reading for the server instance identified by servno.
flags A 16-bit mask that passes information about the file resource. The
flags field can be any number of the following:
• SSPEC_ATTR_MDTM - have modification date/time
• SSPEC_ATTR_LENGTH - have current length
• SSPEC_ATTR_WRITE - file is writable
• SSPEC_ATTR_EXEC - file is "executable"
• SSPEC_ATTR_HIDDEN - "Hidden" attribute bit
• SSPEC_ATTR_SYSTEM - "System" attribute bit
• SSPEC_ATTR_ARCHIVE - "Archive" attribute bit
• SSPEC_ATTR_DIR - directory name
• SSPEC_ATTR_COMPRESSED - stored in compressed format
• SSPEC_ATTR_MAXLENGTH - have maximum length
• SSPEC_ATTR_SEEKABLE - resource is randomly accessible
• SSPEC_ATTR_EXTENSIBLE - File may be expanded at end
mdtm Modification date/time (SEC_TIMER format), this field is only val-
id if SSPEC_ATTR_MDTM is set.
maxlength The maximum allowable file size; this field is only valid if
SSPEC_ATTR_MAXLENGTH is set.
Note that when used with sspec_automount(), some of the above fields may be set to non-
NULL in order to indicate to sspec_automount() that the application has already initialized
some or all of the FAT.
The developer can specify whether the variable is set through a text entry field or a pull-down
menu, and if the variable should be considered read-only.
This FormVar array is placed in a ServerSpec structure using the function
sspec_addform(). ServerSpec entries that represent variables will be added to the
FormVar array using sspec_addfv. Properties for these FormVar entries (for example, the
integrity-checking properties) can be set with various other functions. Hence, there is a level of
indirection between the variables in the forms and the actual variables themselves. This allows the
same variable to be included in multiple forms with different ranges for each form, and perhaps be
read-only in one form and modifiable in another.
HTTP_NO_FLASHSPEC
SSPEC_NO_STATIC
When defined, these macros saves space by not compiling in code that supports a static
resource table. Presumably the application is using only the dynamic resource table, or
filesystems are in use. Historical note: the name of HTTP_NO_FLASHSPEC implies
HTTP, however it actually applies to Zserver as a whole, not any specific server. Dy-
namic C 8.50 introduces SSPEC_NO_STATIC, an alias for
HTTP_NO_FLASHSPEC.
SAUTH_MAXNAME
Maximum length of the name and password strings in the ServerAuth structure. De-
fault is 20. Strings must include a NULL character, so with its default value of 20,
strings in this structure may be at most 19 characters long.
SERVER_PASSWORD_ONLY
This is set to a bitmask of the server mask bits for each server that supports the concept
of a password-only user, that is, no user name. Defaults to zero since currently no serv-
ers are implemented that use this facility.
SSPEC_DEFAULT_READGROUPS
SSPEC_DEFAULT_WRITEGROUPS
SSPEC_DEFAULT_SERVERMASK
SSPEC_DEFAULT_REALM
SSPEC_DEFAULT_METHOD
This group of macros establishes global default permissions for resources that do not
have a rule associated. SSPEC_DEFAULT_READGROUPS is “0xFFFF” which means
“all users.” For writegroups, this is “0” meaning “no users.” The servermask defaults
to SERVER_ANY (all servers can access). realm defaults to “” that is, an empty string,
or no realm. SSPEC_DEFAULT_METHOD defaults to no authentication method re-
quired.
SSPEC_MAX_FATDRIVES
Determine the maximum number of independent FAT filesystem “drives.” Defaults to
1. Each drive takes 8 bytes of root storage (plus whatever is required by the filesystem
itself). Each drive can have up to 4 partitions. This macro is only relevant if you use the
FAT library.
SSPEC_MAXNAME
Define the maximum name length of each dynamic or static resource. Defaults to 20.
You can minimize memory usage by choosing short names for all resources, and reduc-
ing the value of this macro.
SSPEC_MAXRULES
Define the maximum number of dynamically added “rules.” Defaults to 10, but you can
explicitly define it to zero if all the rule table entries are static (see
SSPEC_RULETABLE_* macros). Each rule takes up 13 bytes of root storage, plus
whatever storage is required for the realm and prefix strings (which must be null-termi-
nated, and in static storage, since pointers to these are stored in the rule table).
SSPEC_MAXSPEC
Define to the number of dynamic (RAM) resource table entries to allocate for the global
array, server_spec. Each entry takes SSPEC_MAXNAME + 23 bytes of root mem-
ory (or SSPEC_MAXNAME + 33 if FORM_ERROR_BUF is defined).
Defaults to 10 entries (approximately 530 bytes). Do not set higher than 511.
SSPEC_XMEMVARLEN
Defines the size of the stack-allocated buffer used by sspec_readvariable()
when reading a variable in xmem. It defaults to 20.
SSPEC_FLASHRULES
Define this if your application is using static rules. You must define this if you want to
use the macro SSPEC_RULETABLE_START. If you define SSPEC_FLASHRULES,
and you do not need dynamic rules, you can define the macro SSPEC_MAXRULES to
zero to recover the root memory that would be wasted otherwise.
SSPEC_RULETABLE_START
SSPEC_RULE(prefix, realm, rg, wg, sm)
SSPEC_MM_RULE(prefix, realm, rg, wg, sm, method, mimetype)
SSPEC_RULETABLE_END
This sequence of macros is used to define static rules. See the documentation with the
sspec_addrule() function for more information. You must define
SSPEC_FLASHRULES to use these macros.
SSPEC_MIMETABLE_START
SSPEC_MIME(extension, type)
SSPEC_MIME_FUNC(extension, type, function)
SSPEC_MIMETABLE_END
This sequence sets up the MIME type mapping table. Currently only a static MIME ta-
ble is supported. Though you cannot dynamically add new MIME types to this table, it
is possible to allocate new MIMETypeMap structures in RAM and assign them to spe-
cific resources using sspec_addrule() or sspec_setpermissions().
Such entries will not be accessed using the default resource name extension method.
HTTP_NO_FLASHSPEC
Define if there is to be NO static resource table, that is, all resources are in the dynamic
(RAM) table or in the filesystem(s). If you define this, then there is no point in using
the SSPEC_RESOURCE_* series of macros below.
SSPEC_RESOURCETABLE_START
SSPEC_RESOURCE_ROOTFILE(name, addr, len)
SSPEC_RESOURCE_XMEMFILE(name, addr)
SSPEC_RESOURCE_ZMEMFILE(name, addr)
SSPEC_RESOURCE_FSFILE(name, fnum)
SSPEC_RESOURCE_ROOTVAR(name, addr, type, format)
SSPEC_RESOURCE_XMEMVAR(name, addr, type, format)
SSPEC_RESOURCE_FUNCTION(name, addr)
SSPEC_RESOURCE_CGI(name, addr)
SSPEC_RESOURCE_P_ROOTFILE(name, addr, len, realm, rg, wg, sm, meth)
SSPEC_RESOURCE_P_XMEMFILE(name, addr, realm, rg, wg, sm, meth)
SSPEC_RESOURCE_P_ZMEMFILE(name, addr, realm, rg, wg, sm, meth)
SSPEC_RESOURCE_P_FSFILE(name, fnum, realm, rg, wg, sm, meth)
SSPEC_RESOURCE_P_ROOTVAR(name, addr, type, format, realm, rg, wg,
sm, meth)
SSPEC_RESOURCE_P_XMEMVAR(name, addr, type, format, realm, rg, wg,
sm, meth)
SSPEC_RESOURCE_P_FUNCTION(name, addr, realm, rg, wg, sm, meth)
SSPEC_RESOURCE_P_CGI(name, addr, realm, rg, wg, sm, meth)
SSPEC_RESOURCETABLE_END
These macros are used to initialize the static resource table. Prior to Dynamic C 8.50
this had to be done by explicitly using C language initialization of a table declared as:
const HttpSpec http_spec[]
These macros perform the same function. It is recommended to use them instead of stat-
ic initializers in order to maintain forward compatibility.
The macros with _P_ in the name are the same as the others, except that they explicitly
allow all the server permissions information (except for the MIME type mapping) to be
initialized. See sspec_addrule() for more information on the parameters.
The name parameter to all these macros is the resource name. This usually starts with
a “/” for files, but not for variables. The string length should be less than or equal to
SSPEC_MAXNAME.
DESCRIPTION
This function adds a user to the user table. It fills in the fields of the ServerAuth
structure associated with this user. Three of the field are specified by the parameters
passed into the function. Two other fields, one for the user group mask and the other for
the write access mask, are given default values.
The default for the user group mask is the assigned index number (0 to
SAUTH_MAXNAME-1) as a bit number; that is, 1<<index. This effectively creates
each user in a unique (single) group. Since this does not offer any real control over the
assigned group mask, it is recommended to use sauth_setusermask() after this
to assign the correct access masks.
The default for the write access mask is the user has no write access to any server. To
assign this permission, call the function sauth_setwriteaccess() with the user
table index returned by sauth_adduser().
PARAMETERS
RETURN VALUE
-1: Failure.
≥0: Success; index into user table (id passed to sauth_getusername()).
LIBRARY
ZSERVER.LIB
SEE ALSO
sauth_authenticate, sauth_getwriteaccess, sauth_setusermask,
sauth_setwriteaccess, sauth_removeuser
DESCRIPTION
Authenticate user and return the user index representing the authenticated user, that is,
the user table index. This performs only a plaintext comparison of the userid and pass-
word. Servers probably will have their own, more sophisticated, checks.
If username is NULL, or empty string, then password-only matching is attempted for
servers who allow this type of authentication (as defined by the
SERVER_PASSWORD_ONLY macro).
PARAMETERS
RETURN VALUE
-1: Failure or user not authorized.
≥0: Success, array index of the ServerAuth structure for authenticated user.
LIBRARY
ZSERVER.LIB
SEE ALSO
sauth_adduser
DESCRIPTION
Get the password for a user.
PARAMETER
RETURN VALUE
!=NULL: password string
NULL: Failure
LIBRARY
ZSERVER.LIB
SEE ALSO
sauth_setpassword
sauth_getserver
DESCRIPTION
Returns whether or not a user is visible to particular server(s).
PARAMETER
RETURN VALUE
0: This user is visible to all servers
>0: Visible to select servers. One bit is set for each server that knows about this user.
-1: Failure; for example, sauth is an invalid index into the user table.
SEE ALSO
sauth_setserver
DESCRIPTION
Gets the user index for a user.
PARAMETERS
username User's name. If this name is not found, then the list is re-scanned
looking for an entry with an empty user name ("") and a password
that matches username. The second pass is only done for servers
that allow password-only matching. Such servers must be speci-
fied by defining a symbol SERVER_PASSWORD_ONLY to be a
bitmask of such servers.
server Server(s) for which we are looking up. Use SERVER_ANY if not
concerned with the server mask.
RETURN VALUE
≥0: Success, index of user in the user table.
-1: Failure.
LIBRARY
ZSERVER.LIB
DESCRIPTION
Get the group access bit(s) and/or authorization data for a given user ID.
PARAMETERS
groupbits Pointer to bitmask that will be set to group(s) of which this user is
a member. If NULL, this information is not retrieved.
authdata Pointer to void* that is set to arbitrary server data. If NULL, this
information is not retrieved.
RETURN VALUE
0: OK
-1: Failed: userid not valid.
DESCRIPTION
Returns the name of the user, a character string from the ServerAuth structure asso-
ciated with userid.
PARAMETERS
userid The user’s id, that is, the index into the user table.
RETURN VALUE
NULL: Failure.
!NULL: Success, pointer to the user’s name string.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getusername
DESCRIPTION
Checks whether or not a user has write access to any server's resources. This is an “in
principle” test. Each resource is individually protected from write access: this is not
checked. In other words, this function may return TRUE even when none of the re-
sources are writable to this user.
PARAMETERS
RETURN VALUE
0: User does not have write access.
1: User has write access.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sauth_setwriteaccess
DESCRIPTION
Remove the given user from the user list. IMPORTANT: Any associations of the given
user with web pages should be changed. Otherwise, no one will have access to the un-
changed web pages. Authentication can be turned off for a page with
sspec_setrealm(sspec, "").
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sauth_adduser
DESCRIPTION
Sets the password for a user.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sauth_getpassword
DESCRIPTION
Sets whether a user is visible to the specified server(s).
PARAMETERS
server Server bitmask, with bit set to 1 to make this user “known” to the
server. If this parameter is zero, then the user is visible to ALL
servers, however it is recommended to pass the value
SERVER_ANY in this case.
RETURN VALUE
0: Success
-1: Failure
SEE ALSO
sauth_getserver
DESCRIPTION
Set the group access bit(s) and authorization data for a given user ID.
PARAMETERS
RETURN VALUE
0: OK
-1: Failed: userid not valid.
DESCRIPTION
Set whether or not a user has write access with the specified server(s).
PARAMETERS
writeaccess Server bitmask, with bit set to 1 for write access, 0 for no write
access. This is a bitwise OR of the server macros,
SERVER_HTTP, etc., that you want the user to have write ac-
cess to.
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sauth_getwriteaccess
DESCRIPTION
Test access to a given resource by a specified user. The userid is set in
context->userid, or -1 for testing access by the server in general.
PARAMETERS
RETURN VALUE
≥0: Success. The return value is a bitmask of the following values:
• O_READ - user+server has read access
• O_WRITE - user+server has write access
• 0 (zero) - no access
The following return values are negatives of the values defined in errno.lib.
• -ENOENT - The resource was not found.
• -EINVAL - The resource name was malformed (e.g., too long), or context
was NULL, or the resource was not a file type.
SEE ALSO
sspec_read, sspec_write, sspec_seek, sspec_tell, sspec_close,
sspec_checkpermissions
DESCRIPTION
Add a CGI function to the RAM resource list. This function is currently only useful for
the HTTP server, in which case the function is registered as a CGI processor. Make sure
that SSPEC_MAXSPEC is large enough to hold this new entry.
PARAMETERS
fptr Pointer to the function. The prototype for this function is:
int (*fptr)(HttpState * state);
There is a specific documented interface that must be used when
specifying this type of CGI handler function. See the manual for
details.
RETURN VALUE
≥0: Successfully added spec index
-1: Failed to add function.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addfsfile, sspec_addfunction, sspec_addrootfile,
sspec_addvariable, sspec_addxmemvar, sspec_addxmemfile
sspec_aliasspec, sspec_addform
DESCRIPTION
Adds a form (set of modifiable variables) to the TCP/IP servers’ object list. Make sure
that SSPEC_MAXSPEC is large enough to hold this new entry. This function is current-
ly only useful for the HTTP server.
PARAMETERS
form Pointer to the form array. This is a user-defined array to hold infor-
mation about form variables.
RETURN VALUE
≥0: Success; location of form in server spec list.
-1: Failed to add form.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addfsfile, sspec_addfunction, sspec_addrootfile,
sspec_addvariable, sspec_addxmemvar, sspec_addxmemfile
sspec_aliasspec, sspec_addfv
DESCRIPTION
Adds a file, located in the FS2 filesystem, to the RAM resource list. Make sure that
SSPEC_MAXSPEC is large enough to hold this new entry. This function associates a
name with the file.
This creates an alias entry for /fs2/file<n>.
Note that all FS2 files are automatically accessible. There is no need to call this function
unless it is desired to assign a name to an FS2 file other than the default, which is
file1, file2 etc.
For more information regarding the FS2 filesystem, please see the Dynamic C User’s
Manual.
PARAMETERS
filenum Number of the file in the file system (1-255) . This is the number
passed in as the second parameter to fcreate() or the return
value from fcreate_unused().
servermask Bitmask representing servers for which this entry will be valid
(e.g., SERVER_HTTP, SERVER_FTP).
RETURN VALUE
-1: Failure.
≥0: Success; location of file in TCP/IP servers’ object list.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addrootfile, sspec_addfunction, sspec_addvariable,
sspec_addxmemfile, sspec_addform, sspec_aliasspec
DESCRIPTION
Adds a function to the RAM resource list. Make sure that SSPEC_MAXSPEC is large
enough to hold this new entry. This function is currently only useful for HTTP servers.
NOTE: If using HTTP upload facility and/or the new CGI interface, use
sspec_addCGI() instead.
PARAMETERS
RETURN VALUE
-1: Failure.
≥0: Success, location of the function in the TCP/IP servers’ object list.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addform, sspec_addfsfile, sspec_addrootfile,
sspec_addvariable, sspec_addxmemvar, sspec_addxmemfile,
sspec_aliasspec
DESCRIPTION
Adds a variable to a form.
PARAMETERS
var spec index of the variable to add (which must have been previous-
ly created using sspec_addvariable())
RETURN VALUE
-1: Failure.
≥0: Success; next available index into the FormVar array.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addform
DESCRIPTION
Adds a file that is located in root memory to the dynamic resource table. Make sure that
SSPEC_MAXSPEC is large enough to hold this new entry.
PARAMETERS
name Name of the new file. This must be unique, but this function does
not check. The name should not conflict with the virtual filesystem
hierarchy. That is, it should not start with /fs2/, /A/, /B/ etc.
servermask Bitmask representing servers for which this entry will be valid
(e.g., SERVER_HTTP, SERVER_FTP).
RETURN VALUE
-1: Failure.
≥0: Success; file index into the resource list.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addfsfile, sspec_addxmemfile, sspec_addxmemvar,
sspec_addvariable, sspec_addfunction, sspec_addform,
sspec_aliasspec, sspec_resizerootfile
DESCRIPTION
Add a rule to the dynamic resource rule table. Resource rules are used to associate ac-
cess information with resource names matching the specified prefix string. The most
specific, that is, the longest, matching string is used.
Normally, the rule table is consulted only for resource names that belong in a file sys-
tem (FS2 or FAT). You can also cause the rule table to be consulted for flash- or RAM-
table entries if you leave the realm field as NULL in the entry. If the realm field is
not NULL, then the rule table is not consulted for that entry. If the realm field was
NULL, and there was no applicable entry in the rule table, then the resource table per-
missions are used (with NULL realm).
Do not attempt to use a very large number of rule table entries, since the table must be
searched exhaustively for each initial resource access. There should be no need for a
large number of entries provided that the resource name hierarchy is organized in a rea-
sonably efficient manner. For example, keep the resources for a particular user or realm
in one directory, and just add an entry for that directory instead of an entry for each re-
source. This works because the full path name is always used for matching, and the di-
rectory will always be a prefix string of the files that reside in that directory.
As an alternative to this function, you can statically initialize a rule table using the fol-
lowing macros:
#define SSPEC_FLASHRULES // Required.
#use "zserver.lib" // this lib
SSPEC_RULETABLE_START
SSPEC_RULE("prefix", realm, rg, wg, sm)
SSPEC_RULE("prefix", realm, rg, wg, sm)
SSPEC_MM_RULE("prefix", realm, rg, wg, sm, meth, mime)
SSPEC_MM_RULE("prefix", realm, rg, wg, sm, meth, mime)
...
SSPEC_RULETABLE_END
The SSPEC_MM_RULE macro parameters are basically the same parameters as would
be passed to this function. These macros define and initialize a constant rule table
named f_rule_table. SSPEC_RULE just omits the (rarely used) method and
mimetype fields.
When using a static rule table, the dynamically added entries are searched before the
static ones.
pfx Prefix of resource name. This must include the initial “/” charac-
ter, since all matching is done using absolute path names. If this
prefix string exactly matches an existing entry in the table, that en-
try is replaced. Otherwise, a new entry is created (if possible). This
string is not copied, only the pointer is stored. Thus, pfx must
point to static storage, that is, a string constant or a global variable.
Initial characters other than “/” are reserved for future use.
readgroups A word with a bit set for each group that can access this resource
for reading. A maximum of 16 different user groups can exist.
writegroups A word with a bit set for each group that can access this resource
for writing. The user must also be given write permission to re-
sources in the userid table entry for the appropriate server(s).
servermask The server(s) that are allowed to access this resource. Servers have
predefined bits. This parameter should be a combination of
• SERVER_HTTP: web server
• SERVER_FTP: file transfer protocol server
• SERVER_SMTP: email
• SERVER_HTTPS: secure web server
• SERVER_SNMP: SNMP agent
• SERVER_USER: user-defined server
• SERVER_ANY: for all servers.
method Allowable authentication method(s) to be used when accessing
this resource. If zero, then the resource has no particular authenti-
cation method requirements. This is a bitwise combination of:
• SERVER_AUTH_BASIC: plaintext userid/password
• SERVER_AUTH_DIGEST: challenge-response protocol
• SERVER_AUTH_PK: public key (such as SSL/TLS)
mimetype An appropriate MIME type to use. If NULL, then the default table
(called http_types) will be consulted.
RETURN VALUE
≥0: OK
-1: Error. For example, out of space in rule table; increase SSPEC_MAXRULES.
SEE ALSO
sspec_removerule, sspec_getMIMEtype
DESCRIPTION
Add to the read permission mask for the given resource. The groups that userid is
a member of are ORed into the existing permission mask for the resource. The write
permissions are not modified.
NOTE: This is not used to create new userids. For that, see sauth_adduser().
Adds a user to the list of users that have access to the given spec entry. Up to
SSPEC_USERSPERRESOURCE users can be added. Any more than that will result in
this function returning -1.
This function is deprecated as of Dynamic C 8.50. Use the more general
sspec_setpermissions() function instead.
PARAMETERS
RETURN VALUE
≥0: Success, index of userid added for given spec entry.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setuser, sspec_getusername, sspec_getuserid,
sspec_removeuser, sspec_setpermissions
DESCRIPTION
Adds a variable to the dynamic resource table (aka, the RAM resource list). Make sure
that SSPEC_MAXSPEC is large enough to hold this new spec entry. This function is
currently only useful for the HTTP server.
PARAMETERS
name Name of the new variable. This must be unique, but this function
does not check. The name should not conflict with the virtual file-
system hierarchy. That is, it should not start with /fs2/, /A/,
/B/ etc. Variables appear in a directory listing of the root directo-
ry “/” however, they cannot be opened using sspec_open().
servermask Bitmask representing servers for which this function will be valid
(currently only useful with SERVER_HTTP).
RETURN VALUE
-1: Failure.
≥0: Success, the index of the variable in the resource list.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addfsfile, sspec_addrootfile, sspec_addxmemfile,
sspec_addxmemvar, sspec_addfunction sspec_addform,
sspec_aliasspec
DESCRIPTION
Adds a file, located in extended memory, to the RAM resource list. Make sure that
SSPEC_MAXSPEC is large enough to hold this new entry.
PARAMETERS
name Name of the new file. This must be unique, but this function does
not check. The name should not conflict with the virtual filesystem
hierarchy. That is, it should not start with /fs2/, /A/, /B/ etc.
fileloc Location of the beginning of the file. The first 4 bytes of the file
must represent the length of the file (#ximport does this auto-
matically).
servermask Bitmask representing servers for which this entry will be valid
(e.g., SERVER_HTTP, SERVER_FTP).
RETURN VALUE
-1: Failure.
≥0: Success, the location of the file in the dynamic resource list.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addfsfile, sspec_addrootfile, sspec_addvariable,
sspec_addxmemvar, sspec_addfunction, sspec_addform,
sspec_aliasspec
DESCRIPTION
Add a variable located in extended memory to the RAM resource list. Make sure that
SSPEC_MAXSPEC is large enough to hold this new entry. Currently, this function is
useful only for the HTTP server.
PARAMETERS
name Name of the new variable. This must be unique, but this function
does not check. The name should not conflict with the virtual file-
system hierarchy. That is, it should not start with /fs2/, /A/,
/B/ etc. Variables appear in directory listing of the root directory
“/” however, they cannot be opened using sspec_open().
RETURN VALUE
-1: Failure.
≥0: Success, the index of the variable in the resource list.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addfsfile, sspec_addrootfile, sspec_addvariable,
sspec_addfunction, sspec_addform, sspec_addxmemfile,
sspec_aliasspec
DESCRIPTION
Creates an alias to an existing ServerSpec structure. Make sure that
SSPEC_MAXSPEC is large enough to hold this new entry.
This is NOT a deep copy. That is, any file, variable, or form that the alias (the new spec
entry) references will be the same copy of the file, variable, or form that already exists
in the old spec entry. This should be called only when the original entry has been com-
pletely set up.
NOTE: do not attempt to alias a sspec handle that was returned by sspec_open(),
because the handle may be dynamically allocated. In such a case, the alias will not work
once the original handle is closed. You can test whether such a "virtual" handle has been
returned using the macro SSPEC_IS_VIRT(sspec).
PARAMETERS
RETURN VALUE
-1: Failure.
≥0: Success; return location of alias, i.e., new index.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addform, sspec_addfsfile, sspec_addfunction,
sspec_addrootfile, sspec_addvariable, sspec_addxmemfile
DESCRIPTION
This function automatically initializes and mounts the specified filesystem(s) for use by
Zserver. Mounting a filesystem creates an entry point to that filesystem for the server.
You must #use the appropriate filesystem library (for example, FS2.LIB) otherwise
the filesystem will not be mountable.
If using the FAT library, you must include one or more “driver libraries” (such as
sflash_fat.lib) before #use fat.lib. Only the default device from the first
driver library will be initialized and used by this routine. If you need to use any other
devices, you will need to initialize them individually and call the
sspec_fatregister() function. SSPEC_MAX_FATDRIVES will also need to
be increased from its default value of one.
For the FAT library, this routine calls fat_Init() and mounts the first available FAT
partition on that drive (if any). If the first available partition is the first partition on the
drive, then it will be mounted at mount point “/A”. If it is the second partition, it will
be mounted at “/B” etc. Up to four partitions are scanned. If none are found (or none
are FAT12 or FAT16 partitions) then an error is returned.
For FS2, all logical extents will be initialized via the fs_init() function.
PARAMETERS
RETURN VALUE
0: OK
Otherwise, if a filesystem fails to mount, the return code is the bitwise OR of the
SSPEC_MOUNT_* constants of those filesystem(s) that failed to initialize.
SEE ALSO
sspec_fatregister, sspec_fatregistered
DESCRIPTION
Change the current working directory in the ServerContext structure. This func-
tion may be used by servers that support the concept of a current directory, such as FTP
(but not HTTP). Standard Unix-like path names are used, including support for “.” and
“..” directory components.
The resulting directory name is not allowed to be closer to the root directory than
context->rootdir. If there is any specification error, then the current directory is
not changed. The resulting absolute directory name cannot be longer than
SSPEC_MAXNAME, including a leading and trailing “/” character.
PARAMETERS
RETURN VALUE
0: OK.
Any other negative values indicate an error:
-E2BIG: Resulting directory name too long
-EACCES: Attempt to change above root directory
-ENOENT: 3rd parameter was TRUE, and the directory did not exist.
SEE ALSO
sspec_pwd
DESCRIPTION
This function checks whether or not the specified user has permission to access the
specified resource in the resource table. Only read access is checked.
This function is deprecated as of Dynamic C 8.50. Use the function
sspec_checkpermissions() instead.
PARAMETERS
RETURN VALUE
0: User does not have access.
1: User has access.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_needsauthentication, sspec_checkpermissions
DESCRIPTION
Returns the access permissions for the given server and user, for the given resource.
sspec_access() performs the same function, except that a resource name can be
given (rather than an open resource handle).
PARAMETERS
RETURN VALUE
≥0: Bitwise combination of:
• O_READ: resource is readable
• O_WRITE: resource has write permission. This does NOT necessarily mean
that the resource can actually be written, only that the permission bits allow it.
<0: Error. For example, no permissions can be located or the sspec handle is invalid.
SEE ALSO
sspec_setpermissions, sspec_getpermissions, sspec_access
DESCRIPTION
Close a file resource. This function must be called by servers when they have completed
operations on the file, otherwise there will be a resource leak and future open calls will
fail.
PARAMETER
sspec Open file handle. This must be a handle that was returned by
sspec_open().
RETURN VALUE
≥0: Success.
The following return values are negatives of the values defined in errno.lib.
• -EBADF: The specified handle was not open or invalid.
• Other negative values indicate an error in closing the file resource.
SEE ALSO:
sspec_read, sspec_write, sspec_seek, sspec_tell, sspec_open
DESCRIPTION
Delete a resource by name. See sspec_open() for a detailed description of param-
eters.
PARAMETERS
RETURN VALUE
0: OK.
The following return value is a negative of the values defined in errno.lib. Any
other negative values indicate an error.
• -ENOENT: The specified resource did not exist.
SEE ALSO
sspec_mkdir, sspec_rmdir, sspec_open
DESCRIPTION
Return formatted directory listing line. To use this function, call it with item = 0 the
first time, then keep calling it with item = <previous return value> until it returns neg-
ative. This allows you to iterate through all entries in a directory.
The ServerContext structure contains the current user ID, server, and the name of
the directory to list.
Note: For a given directory, you should call this function with item = 0, followed by
more calls until it returns -1. If you want to terminate the directory listing without iter-
ating through every entry, pass the SSPEC_LIST_END option flag (see below). This
allows Zserver to release any temporary resources acquired for the purpose of iterating
through the directory. This is especially important for FAT filesystem listings. After this
function returns negative, you must start the next directory listing from the top, that is,
item = 0.
If you do not complete the listing, then your application may not be able to perform fur-
ther listings owing to internal resource leakage. This is similar to the need to close file
resources that are opened. See the second example below.
Pass the same ServerContext structure for the entire directory list sequence, since
Zserver keeps track of state information in this structure.
EXAMPLE
To iterate through all resources under “/A/”:
ServerContext ctx;
int item;
char buf[80];
word opts;
word n;
ctx.rootdir = "/";
ctx.server = SERVER_FTP;
ctx.userid = sauth_getuserid("foo", SERVER_FTP);
sspec_cd("/A", &ctx);
for (item = 0; item >= 0; ) {
item = sspec_dirlist(item, buf, sizeof(buf), &ctx,
SSPEC_LIST_LONG);
if (item >= 0)
printf(buf);
} // finished now, can re-use ctx.
PARAMETERS
item Directory entry to list. If zero, this always returns the first entry in
the directory. Thereafter, pass the return value from the previous
call to this function to get the next item(s). NOTE: the return value
does not necessarily count up 1, 2, 3 etc. Apart from 0, the only
values you should pass in this parameter are previous return val-
ues, otherwise the results will be undefined.
line Points to buffer that is filled with resulting string. The string will
be terminated with \r\n (CRLF) then a NULL.
linelen Length of the above buffer. If it is not long enough, then the line
will be truncated (however it will still have the terminating CRLF
+ null). The minimum reasonable value is about 15 for format 0,
and 80 for format 1.
context Server context. This structure will have the following fields initial-
ized:
userid: current user who is doing the listing, or -1 if no spe-
cific user.
server: mask bit of the server who is performing the listing.
cwd[]: set to the directory to list. The sspec_cd() func-
tion can be used to set this field correctly.
This struct must be the same instance for all calls in a single direc-
tory listing sequence.
RETURN VALUE
-EEOF: there were no (more) entries in this directory.
Any other negative value: parameter or I/O error.
Otherwise (non-negative): the return value should be passed back to this function as the
item parameter value, to retrieve the next entry.
SEE ALSO
sspec_cd
DESCRIPTION
This function must be used to register all FAT partitions that will be accessible to
Zserver.lib. Partitions are numbered consecutively from 0, and they correspond
to mount points /A, /B, /C etc.
It is assumed that by the time this function is called the required drives and partitions
have been mounted. For example, call fat_EnumDrive() followed by as many
fat_MountPartition() calls as required. The fat_part pointer returned by
fat_MountPartition() should be passed to this function. Up to
SSPEC_MAX_PARTITIONS can be registered. This number can be changed indirect-
ly by defining SSPEC_MAX_FATDRIVES before #use zserver.lib. This de-
faults to one drive, and the number of partitions is set to 4 times this number (hence the
default allows up to four partitions).
PARAMETERS
RETURN VALUE
≥0: Success.
-ENXIO : partno outside the allowable range of 0 .. SSPEC_MAX_PARTITIONS-1.
LIBRARY
ZSERVER.LIB
SEE ALSO
fat_EnumDrive, fat_EnumPartition, fat_MountPartition,
sspec_automount, sspec_fatregistered
DESCRIPTION
Test whether a FAT partition has been registered with Zserver.
PARAMETER
RETURN VALUE
NULL: Not registered.
Otherwise: Registered, and this is the fat_part pointer.
SEE ALSO
fat_EnumDrive, fat_EnumPartition, fat_MountPartition,
sspec_automount, sspec_fatregister
DESCRIPTION
Finds the index of a form variable in a given form.
PARAMETERS
RETURN VALUE
-1: Failure.
≥0: Success; the index of the form variable in the array of type FormVar.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addfv
DESCRIPTION
Find the spec entry with a name field that matches the given name and is allowed with
the specified server(s). Note that a leading slash in the given name and/or in the re-
source name is ignored for backwards compatibility.
PARAMETERS
RETURN VALUE
-1: Failure.
≥0: Success, spec index. The special value SSPEC_VIRTUAL is returned if the name
refers to part of the virtual filesystem hierarchy. In this case, the server mask is not con-
sulted. SSPEC_VIRTUAL is not a valid handle for other functions.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_findnextfile
DESCRIPTION
Find the server spec entry for filenum. The entry must be of type SSPEC_FSFILE
and be allowed with the specified server.
PARAMETERS
filenum File to search for. This value is the number passed in as the 2nd
parm to fcreate() or the return value from
fcreate_unused().
RETURN VALUE
-1: Failure.
≥0: Success, index into resource list.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_findname
DESCRIPTION
Find the first spec file entry at or following the start spec that is accessible by the
given server. When the end of the RAM entries is reached, the flash entries are
searched. Virtual filesystem entries are not considered. Only entries for which
sspec_gettype() would return SSPEC_FILE are considered.
If you are using this function to iterate through the available resources, then the caller
is responsible for incrementing the starting point. To do this, you can call the function
sspec_nexthandle() which will return the next valid handle after the given one
(or -1 if no more handles).
PARAMETERS
start The array index at which to begin the search. -1 starts searching the
RAM entries.
RETURN VALUE
-1: Failure.
≥0: Success, index of requested ServerSpec structure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_findname, sspec_gettype
DESCRIPTION
PARAMETERS
RETURN VALUE
≥0: Success, location of the file.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfiletype, sspec_getlength
DESCRIPTION
Get the type of a file represented by the given spec index.
PARAMETERS
sspec spec index of the file in the resource list, that is, the index into the
array of ServerSpec structures.
RETURN VALUE
SSPEC_ROOTFILE: root memory data
SSPEC_XMEMFILE: xmem data
SSPEC_ZMEMFILE: compressed xmem data
SSPEC_FSFILE: FS2 file
SSPEC_ERROR: failure - not a file, or invalid handle
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfileloc, sspec_gettype
DESCRIPTION
Gets the title for an automatically generated form.
PARAMETERS
RETURN VALUE
NULL: Failure.
!NULL: Success, title string.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setformtitle
DESCRIPTION
Returns a pointer to the function represented by the sspec index. The entry must have
been created as a SSPEC_FUNCTION or as a SSPEC_CGI.
PARAMETERS
RETURN VALUE
NULL: Failure.
!NULL: Success, pointer to requested function.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addfunction
DESCRIPTION
Gets the description of a variable that is displayed in the HTML form table.
PARAMETERS
RETURN VALUE
NULL: Failure.
!NULL: Success, description string.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setfvdesc
DESCRIPTION
Gets the type of form entry element that should be used for the given variable.
PARAMETERS
RETURN VALUE
-1: Failure;
Type of form entry element on success:
HTML_FORM_TEXT is a text box.
HTML_FORM_PULLDOWN is a pull-down menu.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setfventrytype
DESCRIPTION
Gets the length of a form variable (the maximum length of the string representation of
the variable).
PARAMETERS
RETURN VALUE
-1: Failure.
≥0: Success, length of the variable.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setfvlen
DESCRIPTION
Gets the name of a variable that is displayed in the HTML form table.
PARAMETERS
RETURN VALUE
NULL: Failure.
!NULL, name of the form variable.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setfvname
DESCRIPTION
Gets the number of variables in a form.
PARAMETERS
RETURN VALUE
-1: Failure.
≥0: Success, number of form variables.
LIBRARY
ZSERVER.LIB
DESCRIPTION
Gets the numbered option (starting from 0) of the form variable. This function is only
valid if the form variable has the option list set.
PARAMETERS
RETURN VALUE
NULL: Failure.
!NULL: Success, form variable option.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setfvoptlist, sspec_getfvoptlistlen
DESCRIPTION
Gets the length of the options list of the form variable. This function is only valid if the
form variable has the option list set.
PARAMETERS
RETURN VALUE
-1: Failure.
>0: Success, length of the options list.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfvopt, sspec_setfvoptlist
DESCRIPTION
Checks if a form variable is read-only.
PARAMETERS
RETURN VALUE
0: Not read-only.
1: Read-only.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setfvreadonly
DESCRIPTION
Gets the server_spec index of a variable in a form.
PARAMETERS
RETURN VALUE
-1: Failure.
≥0: Success, index of the form variable in the resource list.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addfv
DESCRIPTION
Gets the length of the file associated with the specified ServerSpec structure. Get
the length of the file specified by the sspec index. Note that compressed files
(#zimport) return -1 because their expanded length is not known until they are pro-
cessed.
PARAMETERS
RETURN VALUE
-1: Failure (compressed file, or other type whose effective length is not known).
≥0: Success, length of the file in bytes.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_readfile, sspec_getfileloc
DESCRIPTION
Return the MIME type information for a specified resource name, in the given server
context.
Note that the available MIME types are set up by defining a global variable (or con-
stant) table using the definition (for example),
const MIMETypeMap http_types[] =
{
{ ".html", "text/html", NULL},
{ ".gif", "image/gif", NULL}
};
The name http_types is required for backward compatibility even though servers
other than HTTP can make use of MIME types.
When searching for the appropriate type, the rule table is consulted first. Only if this
results in a NULL MIME type pointer is the http_types table consulted.
See sspec_open() for a detailed description of the parameters.
PARAMETER
RETURN VALUE
Pointer to the appropriate table entry. MIMETypeMap is defined as:
typedef struct {
char extension[10]; // File extension or suffix.
char type[SSPEC_MAXNAME]; // MIME type e.g., "text/html"
int (*fptr)(); // Server-specific processing, e.g., SSI.
} MIMETypeMap;
A valid pointer is always returned. If the appropriate table entry cannot be located by the
resource's extension (or using a rule (see sspec_addrule)) then the first table entry
is returned.
SEE ALSO
sspec_addrule
DESCRIPTION
Returns the name of the spec entry represented by the sspec index
This only works for RAM and flash table entries.
PARAMETERS
RETURN VALUE
NULL: Failure.
!NULL: Success, pointer to name string.
LIBRARY
ZSERVER.LIB
DESCRIPTION
Get the permission (access control) attributes of a resource.
Except for sspec, all parameters are pointers to variables that will be set to the appro-
priate return value. If the parameter is NULL, then that information is not retrieved.
NOTE: The data at **realm and **mimetype should not be altered by the caller.
The data is read-only.
PARAMETERS
RETURN VALUE
0: Success.
<0: Failure. For example, an invalid sspec handle
SEE ALSO
sspec_setpermissions, sspec_checkpermissions, sspec_access
DESCRIPTION
Gets the user function that will be called just before HTML form generation. This func-
tion is useful mainly for custom form generation functions.
PARAMETERS
RETURN VALUE
NULL: No user function.
!NULL: Pointer to user function.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setpreformfunction, sspec_setformfunction
DESCRIPTION
Returns the realm of the spec entry represented by sspec.
PARAMETERS
RETURN VALUE
NULL: Failure.
!NULL: Success, pointer to the realm string.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setrealm
DESCRIPTION
Gets the server mask for the given spec entry. This is the bitmask passed in when the
entry is created with the sspec_add*() functions.
This function only works for RAM and flash table entries.
PARAMETERS
RETURN VALUE
0: Success
-1: Failure
DESCRIPTION
Returns the type (SSPEC_FILE, SSPEC_VARIABLE, etc.) of the spec entry repre-
sented by sspec. This is a generic type, in that, SSPEC_FILE is returned for any type
(SSPEC_ROOTFILE, SSPEC_FSFILE etc.) that has file properties and
SSPEC_VARIABLE is returned for SSPEC_ROOTVAR or SSPEC_XMEMVAR. Other
types are returned without translation.
PARAMETERS
RETURN VALUE
SSPEC_ERROR: Failure.
!SSPEC_ERROR: Success, type as described above.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfiletype, sspec_getvartype
DESCRIPTION
Returns a userid for the given sspec resource. Since a resource can have multiple use-
rids associated with it, index indicates which userid should be returned. Note that
index should follow the relation 0 ≤ index < SSPEC_USERSPERRESOURCE.
If there is no userid for a given index, -1 will be returned. If -1 is returned for an index,
then -1 will also be returned for all higher indices.
This function may be used to iterate through all users that have read access to a
particular resource.
This only works for RAM and flash table entries.
Starting with Dynamic C 8.50, access control is done by user groups rather than indi-
vidual users; therefore, sspec_getuserid() may not work as expected.
PARAMETERS
RETURN VALUE
-1: Error, or no such userid.
≥ 0: Success, userid is returned.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getusername, sauth_getusername
DESCRIPTION
Gets the username field of the first user in the user table that has read access to the
resource indexed by sspec. If multiple users are associated with this resource, the first
user's username will be returned. See sspec_getuserid() to get all userids for a
resource, and sauth_getusername() to convert the userids to usernames.
Starting with Dynamic C 8.50, access control is done by groups rather than individual
users, therefore, sspec_getusername() may not work as expected.
This only works for RAM and flash table entries.
PARAMETERS
RETURN VALUE
NULL: Failure, or no user has read access to this resource.
!=NULL: Success, pointer to username.
LIBRARY
ZSERVER.LIB
SEE ALSO
sauth_adduser, sspec_setuser, sauth_getuserid,
sauth_getusername
DESCRIPTION
Returns a pointer to the requested variable in the resource list.
PARAMETERS
RETURN VALUE
NULL: Failure.
!NULL: Success, pointer to variable.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_readvariable
DESCRIPTION
Returns the kind of variable represented by sspec.
PARAMETERS
RETURN VALUE
0: Failure.
On success, returns one of:
• INT8 - single character
• INT16 - 2-byte integer
• PTR16 - string in root memory
• INT32 - 4-byte (long) integer
• FLOAT32 - floating point variable
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getvaraddr, sspec_getvartype, sspec_gettype
DESCRIPTION
Gets the type of variable represented by the spec index.
PARAMETERS
RETURN VALUE
SSPEC_ERROR: Failure.
SSPEC_ROOTVAR or SSPEC_XMEMVAR: Success.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getvaraddr, sspec_getvarkind, sspec_gettype
sspec_getxvaraddr
DESCRIPTION
Returns a pointer to the variable in xmem represented by the sspec index.
PARAMETER
RETURN VALUE
≥ 0: Variable pointer.
-1: Failure.
SEE ALSO
sspec_readvariable
DESCRIPTION
Create a named directory in the FAT filesystem.
PARAMETERS
RETURN VALUE
0: OK.
-EPERM: Not a filesystem that supports creation of new directories.
-EACCES: Not authorized
Any other negative values indicate an error.
SEE ALSO
sspec_delete, sspec_rmdir, sspec_open
DESCRIPTION
Checks if the item represented by the spec entry needs authentication for access. This
is defined by having a non-NULL “realm” string for the resource.
This function is deprecated starting with Dynamic C 8.50 in favor of
sspec_checkpermissions(). It is retained for cases where the permissions
structure for a resource contains an authentication method of
SERVER_AUTH_DEFAULT.
PARAMETERS
RETURN VALUE
0: Does NOT need authentication.
1: Does need authentication.
-1: Failure, no permissions struct assigned or invalid sspec handle.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getrealm, sspec_checkpermissions
DESCRIPTION
Open a file resource by name. The name may refer to a flash- or RAM-spec entry, or
may be the name of a file in a filesystem.
The resource namespace is specified as a directory hierarchy, similar to a Unix-like file-
system. The root directory, “/”, is the base for all named resources.
If fs2.lib is included, then files stored in the FS2 filesystem are accessible under a
mount point called “/fs2.” FS2 files do not have native names. Instead, each file is
numbered from 1 to 255. Zserver assigns names to FS2 files by appending the file num-
ber (in decimal) to the string “file.” For example, FS2 file number 99 has a complete
resource name of “/fs2/file99.”
If fat.lib is included, then all DOS FAT files are mounted under a drive letter. The
first partition of the first DOS FAT filesystem is called “/A” and the second partition (if
any) is called “/B” etc. For example, if the FAT filesystem has a file called “/system/ad-
min.htm” then the complete resource name will be “/A/system/admin.htm”.
NOTE: Forward slashes are required. Do not use backslashes as is customary with
DOS filesystems.
If the resource name does not begin with “/fs2” or “/A” etc., then the resource is located
in the static resource table (“flashspec” that is, the http_flashspec global table)
or in the dynamic (RAM) table.
To access the file resource, the return value from this function must be passed to other
functions, such as sspec_read(). A few functions do not work with resources
opened with this function. These cases are documented with the function.
NOTE: When the application has finished accessing the resource, it must be closed
using sspec_close(). This must be done because there is a limited amount of stor-
age for maintaining the necessary file handles.
PARAMETERS
The following return values are negatives of the values defined in errno.lib.
• -ENOENT: The resource was not found when it was expected to exist.
• -EACCES: The context->userid field was not -1, and the specified user
is not allowed to access the resource using the specified mode.
• -EINVAL: The resource name was malformed (e.g., too long), or context was
NULL, or the resource was not a file type, or O_CREAT, O_TRUNC or
O_APPEND were specified without O_WRITE.
• -ENOMEM: Insufficient storage for handle or buffers. Increase definition of
SSPEC_MAX_OPEN.
• -EPERM: Operation not permitted, for example., opening an xmem file for
writing.
SEE ALSO
sspec_read, sspec_write, sspec_seek, sspec_tell, sspec_close
DESCRIPTION
Print the current working directory in the ServerContext structure to the specified
buffer. The context->cwd field contains the CWD. This function removes the root
directory component (context->rootdir) and copies the result. This makes
rootdir invisible to the end user.
The leading slash is included, but the trailing slash is omitted from the result (unless the
result is just “/”).
For example, if
context->rootdir points to “/A/” and
context->cwd[] contains “/A/ftpfiles/”
“/ftpfiles” will be the result returned in buf.
PARAMETERS
buf Points to buffer that is filled with resulting string. This buffer is as-
sumed to be dimensioned at least SSPEC_MAXNAME chars long,
and it will be null terminated on return.
RETURN VALUE
The buf parameter is returned.
SEE ALSO
sspec_cd
DESCRIPTION
Read the next byte(s) from the given file resource.
PARAMETERS
sspec Open file handle. This must be a handle that was returned by
sspec_open().
buf Buffer into which data is copied.
len Length of the above buffer. If len is zero, then the return value
will be the minimum number of characters that could be read at the
current position, which is usually at least 1 except at EOF (0).
Thus, this function can be used to test for end-of-file (EOF), that
is, if
(sspec_read(sspec, NULL, 0) == 0)
is TRUE, then EOF has been reached in the file identified by
sspec.
RETURN VALUE
0: No data is currently available. If the len parameter was zero, then a return value of
zero definitely means end-of-file has been reached. If len > 0, there may be data avail-
able in the future, e.g., because the underlying filesystem is socket-based and this host
has read all available data, but the socket is still open to receive more data.
1..len: the specified number of characters has been copied to the supplied buffer,
and the current file position has been advanced by that many bytes. Possibly less than
len bytes may be read, in which case the server should test for EOF.
>len: no data was copied, because the underlying filesystem is unable to return a par-
tial record and maintain its current position. The return value is the minimum sized
buffer that should be passed on the next call. Note: this sort of return is not currently
implemented by any of the file systems, however servers should be coded to handle this
case for future anticipated systems which have record-level access rather than byte-lev-
el.
The following return values are negatives of the values defined in errno.lib.
• -EINVA: len parameter was < 0.
• -EBADF: The specified handle was not open or invalid.
• Any other negative values indicate an error.
SEE ALSO
sspec_close, sspec_write, sspec_seek, sspec_tell, sspec_open
DESCRIPTION
Read a file (represented by the sspec index) into buffer, starting at offset, and
only copying len bytes. For xmem files, this function automatically skips the first 4
bytes. Hence, an offset of 0 marks the beginning of the file contents, not the file length.
This function is intended for file types that do not require explicit open or close calls,
that is, root or xmem files. It can also be called for FS2 files, but this is not recommend-
ed since each call requires the file to be opened, seeked, read then closed. Instead, use
sspec_open(), sspec_read() and sspec_close() calls which are the
most efficient.
sspec_readfile() has the advantage of being “stateless,” but the price to pay is
great loss of efficiency (especially when sequential access is all that is required.)
This function will NOT work for compressed xmem files or DOS FAT files.
PARAMETERS
offset The offset from the start of the file, in bytes, at which copying
should begin.
RETURN VALUE
-1: Failure.
≥0: Success, number of bytes copied.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getlength, sspec_getfileloc
DESCRIPTION
Formats the variable associated with the specified ServerSpec structure, and puts a
NULL-terminated string representation of it in buffer. The macro
SSPEC_XMEMVARLEN (default is 20) defines the size of the stack-allocated buffer
when reading a variable in xmem.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getvaraddr
DESCRIPTION
Removes a spec entry (by marking it unused). In the case of files, note that this function
does not actually remove the file, only the reference to the file in the spec structure.
This only works for RAM table entries.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure (i.e., the index is already unused).
LIBRARY
ZSERVER.LIB
DESCRIPTION
Remove a rule from the dynamic resource rule table.
PARAMETER
pfx Prefix of resource name. This must be an exact match to one of the
rules previously added using sspec_addrule().
RETURN VALUE
≥0: OK
-1: Error. For example, the rule was not found, or maybe the rule was in the flash table
(f_rule_table).
SEE ALSO
sspec_addrule
DESCRIPTION
Removes the user group(s) that userid belongs to from the read and write access
masks for the specified resource. This will deny access to other users who have the
same group(s) as the current user.
This function is deprecated as of Dynamic C 8.50. Use the more general
sspec_setpermissions() function instead.
PARAMETERS
RETURN VALUE
0: Success, user was removed.
-1: Failure, no such userid found.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setuser, sspec_adduser, sspec_getusername,
sspec_getuserid, sspec_setpermissions
DESCRIPTION
Change the byte size of a SSPEC item stored in root memory. Item must be a
ROOTFILE, thus the item must have been created with sspec_addrootfile().
PARAMETERS
RETURN VALUE
≥0: Successfully adjust size of item.
-1: Failed to adjust size.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_addrootfile
DESCRIPTION
Restores the TCP/IP servers’ object list and the TCP/IP users list (and some user-spec-
ified data if set up with sspec_setsavedata()) from the file system. This does
not restore the actual files and variables, but only the structures that reference them. If
the files are stored in flash, then the references will still be valid. Files in volatile RAM
and variables must be rebuilt through other means.
RETURN VALUE
0: Successfully restored the server_spec and server_auth tables.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_save, sspec_setsavedata
DESCRIPTION
Delete a named directory in the FAT filesystem.
PARAMETERS
RETURN VALUE
0: OK.
-EPERM: Not a filesystem that supports deletion of directories.
-EACCES: Not authorized
Any other negative values indicate an error.
SEE ALSO
sspec_delete, sspec_mkdir, sspec_open
DESCRIPTION
Saves the servers’ object list and server authorization list (along with some user-speci-
fied data if set up with sspec_setsavedata()) to the file system. This does not
save the actual files and variables, but only the structures that reference them. If the files
are stored in flash, then the references will still be valid. Files in volatile RAM and vari-
ables must be rebuilt through other means.
RETURN VALUE
0: Successfully save the server_spec and server_auth tables.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_restore, sspec_setsavedata
DESCRIPTION
Seek to specified offset in the file resource. The next sspec_read() or
sspec_write() call will start at this position.
Note that offsets that are not in the file are clamped to the start or end of the file as ap-
propriate.
Clamp is terminology meaning that a value past the end is set to the end, or a value be-
fore the beginning is set to the beginning. For example, if a file is actually 10 bytes, then
seek to position 20 is actually a seek to position 10. Likewise, seek to -20 is set to po-
sition 0.
PARAMETERS
sspec Open file handle. This must be a handle that was returned by
sspec_open().
RETURN VALUE
0: OK.
The following return values are negatives of the values defined in errno.lib.
• -EINVAL: whence parameter was invalid.
• -EBADF: The specified handle was not open or invalid.
• -EPERM: Operation not permitted on this file resource. This is usually
because the resource is not seekable (such as a compressed file).
• Any other negative values indicate an error.
SEE ALSO:
sspec_close, sspec_write, sspec_read, sspec_tell, sspec_open
DESCRIPTION
Sets the user-specified function that will be called when the form has been successfully
submitted. This function can, for example, execute a cgi_redirectto to redirect
to a specific page. It should accept HttpState *state as an argument, return 0
when it is not finished, and 1 when it is finished (i.e., behave like a normal CGI func-
tion).
PARAMETERS
function spec index of the function to call when the specified form has been
successfully submitted. This is the return value of the function
sspec_addfunction().
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setformprolog
DESCRIPTION
Sets the function that will generate the form.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
DESCRIPTION
Allows a user-specified function to be called just before form variables are updated.
This is useful for implementing locking on the form variables (which can then be un-
locked in the epilog function), so that other code will not update the variables during
form processing. The user-specified function should accept HttpState *state as
an argument, return 0 when it is not finished, and 1 when it is finished (i.e., behave like
a normal CGI function).
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setformepilog
DESCRIPTION
Sets the title for an automatically generated form.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getformtitle
DESCRIPTION
Sets a function that can be used to check the integrity of a variable. The function should
return 0 if there is no error, or !0 if there is an error.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setfvfloatrange, sspec_setfvoptlist, sspec_setfvrange
DESCRIPTION
Sets the description of a variable that is displayed in the HTML form table.
PARAMETERS
desc Description of the variable. This text will display on the HTML
page.
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfvdesc
DESCRIPTION
Sets the type of form entry element that should be used for the given variable.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfventrytype
DESCRIPTION
Sets the range of a float variable.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setfvrange, sspec_setfvoptlist
DESCRIPTION
Sets the length of a form variable (the maximum length of the string representation of
the variable). Note that for string variables, len should not include the NULL termi-
nator.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfvlen
DESCRIPTION
Sets the name of a variable that is displayed in the HTML form.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfvname
DESCRIPTION
Sets an enumerated list of possible values for a string variable.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfvopt, sspec_getfvoptlistlen, sspec_setfvfloatrange,
sspec_setfvrange
int sspec_setfvrange( int form, int var, long low, long high );
DESCRIPTION
Sets the range of an integer variable.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_setfvfloatrange, sspec_setfvoptlist
DESCRIPTION
Sets the form variable to be read-only.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getfvreadonly
DESCRIPTION
Set the permission (access control) attributes of a resource.
This only works for RAM table entries. For entries in a filesystem, use
sspec_addrule().
PARAMETERS
servermask Servers that can access this resource (or SERVER_ANY for all
servers).
RETURN VALUE
0: Success.
<0: Failure. For example, not a RAM spec handle.
SEE ALSO
sspec_checkpermissions, sspec_getpermissions, sspec_access
DESCRIPTION
Sets a user function that will be called just before form generation. The user function is
not called when the form is being generated because of errors in the form input. The
user function must have the following prototype:
void userfunction(int form);
The function may not use the form parameter, but it is useful if the same user function
is used for multiple forms.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getpreformfunction
DESCRIPTION
Sets the realm field of a ServerSpec structure for HTTP authentication purposes.
Setting this field enables authentication for the given spec entry . Authentication can be
turned off again by passing "" as the realm parameter to this function.
Note: realm must NOT point to an auto variable, since only the pointer is stored. The
string is NOT copied.
PARAMETERS
sspec spec index - this must refer to the RAM resource table
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_getrealm
DESCRIPTION
Sets user-supplied data that will be saved in addition to the spec and user authentication
tables when sspec_save() is called.
PARAMETERS
RETURN VALUE
0: Successfully set up the user-supplied data.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sspec_save, sspec_restore
DESCRIPTION
Set the read permission mask of a spec entry (usually a file). The permissions for this
resource are set to readable only by the group(s) which this user is a member of. Write
access is set to “none.”
This function is deprecated in Dynamic C 8.50. Use sspec_setpermissions()
instead.
PARAMETERS
RETURN VALUE
0: Success.
-1: Failure.
LIBRARY
ZSERVER.LIB
SEE ALSO
sauth_adduser, sspec_getusername, sspec_setpermissions
DESCRIPTION
Get information about a resource by name. The name may refer to a flash- or ram-spec
entry, or may be the name of a file in a filesystem. See sspec_open() for a more
detailed description of the name and context parameters.
PARAMETERS
RETURN VALUE
≥0: Success.
The following return values are negatives of the values defined in errno.lib.
• -ENOENT: The resource was not found.
• -EINVAL: The resource name was malformed (for example, too long), or con-
text was NULL, or the resource was not a file type.
SEE ALSO
sspec_open, sspec_delete, sspec_close
DESCRIPTION
Return the current read/write offset in the file resource. This will be a non-negative val-
ue unless there was an error.
PARAMETER
sspec Open file handle. This must be a handle that was returned by
sspec_open().
RETURN VALUE:
≥0: Offset in the file resource.
The following return value is a negative of the value defined in errno.lib. Any oth-
er negative values indicate an error.
• -EBADF: The specified handle was not open or invalid.
SEE ALSO:
sspec_close, sspec_write, sspec_read, sspec_tell, sspec_open
DESCRIPTION
Write byte(s) to the given file resource. The data is written to the current position, then
the current position is advanced by the number of bytes written.
PARAMETERS
sspec Open file handle. This must be a handle that was returned by
sspec_open().
RETURN VALUE
0: No data was written because len was zero or because a local buffer is full (e.g.,
when writing to an underlying filesystem that streams data to a peer).
1..len: The specified number of characters has been copied from the supplied buffer,
and the current file position has been advanced by that many bytes. Possibly less than
len bytes may be written, in which case the server should attempt to write the remain-
ing data later.
The following return values are negatives of the values defined in errno.lib.
• -EINVAL: len parameter was < 0.
• -EBADF: The specified handle was not open or invalid.
• -ENOSPC: There is insufficient space in the underlying filesystem, or the file
cannot be extended.
• -EPERM: The file resource does not support writing (e.g. xmem files, or a
read-only filesystem).
Any other negative values indicate an error.
SEE ALSO
sspec_close, sspec_read, sspec_seek, sspec_tell, sspec_open
This chapter is intended to be a detailed description of the HTTP server, and how it interfaces to
other libraries, such as Zserver and TCP/IP. For an overview of how these libraries interface with
one another and with your application, please see Chapter 2. “Web-Enabling Your Application.”
An HTTP (Hypertext Transfer Protocol) server makes HTML (Hypertext Markup Language)
pages and other resources available to clients (that is, web browsers). HTTP is implemented by
HTTP.LIB, thus you need to write #use “http.lib” near the top of your program. HTTP
depends on the Dynamic C networking suite, which is included in your program by writing #use
“dcrtcp.lib”.
Setting up the network subsystem is a necessary pre-requisite for use of HTTP. This is described in
volume 1 of the manual. However, it can be quite simple for test applications and samples to ini-
tialize the network subsystem. In the file tcp_config.lib are predefined configurations that
may be accessed by a #define of the macro TCPCONFIG. For instructions on how to set up differ-
ent configurations, please see volume 1 of the manual or look in the file
\LIB\TCPIP\TCP_CONFIG.LIB.
HTTP makes use of the Zserver library to manage resources and access control. The previous
chapter discusses Zserver. When reading this chapter, it will help if you are familiar with Zserver,
its interfaces and capabilities.
Much of this chapter contains material that could be considered advanced usage. There is also
some material of a historical nature, with relevant sections marked as such.
4.1.1 HttpState
Use of the HttpState structure is necessary for CGI functions (whether or not they were writ-
ten prior to Dynamic C 8.50). Some of the fields are off-limits to developers. The field that are
available for use are described in the next section.
Historical note: prior to Dynamic C 8.50, it was sometimes necessary for CGI functions to access
directly the fields of this structure. New programs should not directly access the fields, since it
reduces the chance of upward compatibility. There is a new suite of macros (see
http_getAction() and related macros) that should be used instead. Where applicable, the
equivalent macro is documented with the field. Some fields do not have an equivalent macro (such
as the cookie field); for now, use read-only access to such fields.
A pointer to HttpState is the first (and only) parameter to all CGI functions. Most of the time,
this pointer should be passed on to other HTTP library functions.
Note that the HttpState structure is only valid within a CGI function that has been called from
the HTTP server. Outside of this (for example, in your main() function) none of the fields are
guaranteed to be meaningful or consistent.
s This is the socket associated with the given HTTP server. A devel-
oper can use this in a CGI function to output dynamic data (although
there are better, safer ways of doing this: see the section on "Writing
a CGI Function"). Any of the TCP functions can be used; however,
you should not use any functions that may wait for long periods, or
may change the state or mode of the socket (since the HTTP server
depends on it being a normal ASCII mode TCP socket).
It is recommended that you use the http_getSocket() macro
instead of directly accessing this field.
substate
subsubstate Intended for holding the current state of a state machine for a CGI
function. That is, if a CGI function relinquishes control back to the
HTTP server, then the values in these variables will be preserved for
the next http_handler() call, in which the CGI function will
be called again. These variables are initialized to 0 before the CGI
function is called for the first time. Hence, the first state of a state
machine using substate should be 0.
It is recommended that you use the macros http_getState()
and http_setState() to manipulate the substate field in-
stead of directly accessing it. subsubstate is not accessible via
these macros, but there are better alternatives.
main_timeout This value holds the timeout that is used by the web server. The web
server checks against this timeout on every call of
http_handler(). When the web server changes states, it resets
main_timeout. When it has stayed in one state for too long, it
cancels the current processing for the server and goes back to the ini-
tial state. Hence, a CGI function may want to reset this timeout if it
needs more processing time (but care should be taken to make sure
that the server is not locked up forever). This can be achieved like
this:
state->main_timeout=set_timeout(HTTP_TIMEOUT);
buffer[] A buffer that the developer can use to put data to be transmitted over
the socket. It is of size HTTP_MAXBUFFER (defaults to 256 bytes).
Note: It is not recommended to directly access “buffer” or “p” (be-
low). Use the new-style CGI functions and the http_write(),
http_getData() and http_getDataLength() functions
instead. These create a much easier-to-use and safer method of read-
ing/writing data to the client.
method This should be treated as read-only. It holds the method by which the
web request was submitted. The value is either
HTTP_METHOD_GET or HTTP_METHOD_POST, for the GET and
POST request methods, respectively.
Use http_getHTTPMethod() for new code.
url[] This should be treated as read-only. It holds the URL by which the
current web request was submitted. . If there is GET-style form in-
formation, then that information will follow the first NULL byte in
the url array. The form information will itself be NULL-terminated.
If the information in the url array is truncated to HTTP_MAXURL
bytes, the truncated information is also NULL-terminated.
Use http_getURL() for new code.
version This should be treated as read-only. This holds the version of the
HTTP request that was made. It can be HTTP_VER_09,
HTTP_VER_10, or HTTP_VER_11 for 0.9, 1.0, or 1.1 requests,
respectively.
Use http_getHTTPVersion() for new code.
content_length This should be treated as read-only. This variable holds the length
of the content sent by the client. It matches the value of the Con-
tent-Length header sent by the client.
Use http_getContentLength() for new code.
username[] Read-only buffer has username of the user making the request, if
authentication took place.
Note: New code should use the http_getContext() macro,
then use the results to look up the user details using the sauth_*
functions. See the documentation for the ServerContext Structure
in the previous chapter.
password[] Read-only buffer has password of the user making the request, if
authentication took place. See the above note.
HTTP_HOMEDIR
Specify the “home directory” for the server. This is the root directory to which all URLs
are appended. The default is “/”, which means that all resources are accessible. If this
is set to, say, “/htdocs”, then an incoming URL of “foo/bar.html” gets turned into “/ht-
docs/foo/bar.html”. You can use this to restrict the HTTP server’s access to all but a spe-
cific “branch” of resources.
Note: the string value for this macro must start and end with a “/” character.
HTTP_DFLTFILE
Specify the default file name to append to the URL if the URL refers to a directory. This
is only applicable if the URL is “/”, or is in a filesystem (not the static or dynamic re-
source tables). The default setting is “index.html”. The value must not start or end with
a “/” character.
HTTP_SOCK_BUF_SIZE
This macro is not defined by default. If you define it, then it specifies the amount of
extended memory to allocate (xalloc()) for each HTTP server instance. If you do
not define it, then socket buffers are allocated from the usual pool. See
tcp_extopen() for more details.
HTTP_MAXBUFFER
This is the size of the buffer accessible through the HttpSpec structure. It defaults to
256 bytes. The size of this buffer affects the speed of the HTTP server; the larger the
buffer (up to a point), the faster the server will run. The buffer size is also important for
use in CGI functions because it is a work space the programmer can use.
HTTP_MAXBUFFER must be at least 180 bytes for CGI functionality.
HTTP_MAX_COND
Support for conditional SSI (error feedback etc.). It defaults to 4. This is the maximum
number of state variables that may be accessed using the http_getCond() or
http_setCond() macros.
HTTP_MAX_NONCES
This macro is used when USE_HTTP_DIGEST_AUTHENTICATION is set to one.
Defined to 5 by default, it specifies the number of nonces the HTTP server will allow
as valid at any one time. This value should be somewhat larger than the maximum num-
ber of clients expected to be accessing the server simultaneously. Otherwise perfor-
mance could suffer as clients are forced to retry authorization in order to acquire a fresh
nonce.
HTTP_MAXSERVERS
This is the maximum number of HTTP servers listening on port 80. The default is 2.
You may increase this value to the maximum number of independent entities on your
page. For example, for a Web page with four pictures, two of which are the same, set
HTTP_MAXSERVERS to 4: one for the page, one for the duplicate images, and one for
each of the other two images. By default, each server takes 2500 bytes of RAM. This
RAM usage can be changed by the macro SOCK_BUF_SIZE (or
tcp_MaxBufSize which is deprecated as of Dynamic C ver. 6.57). Another option
is to use the tcp_reserveport() function and a smaller number of sockets.
HTTP_MAXURL
This macro defines the maximum incoming URL. This could be important if someone
is allowing GET requests with a large number of parameters.
HTTP_IFACE
This macro allows the user to override the default listening network interface. The de-
fault is IF_ANY, meaning that the HTTP server(s) will listen for incoming network
connections on all interfaces which are up. You can restrict the HTTP servers to a single
interface by overriding this macro to the specific interface number (for example,
IF_ETH0).
HTTP_TIMEOUT
Defines the number of seconds of no activity that can elapse before the HTTP server
closes a connection. The default is 16 seconds.
HTTP_USERDATA_SIZE
This macro causes "char userdata[]" to be added to the HttpState structure. Define
your structure before the statement #use HTTP.LIB.
struct UserStateData {char name[50]; int floor; int model;};
#define HTTP_USERDATA_SIZE (sizeof(struct UserStateData))
#use http.lib
USE_HTTP_DIGEST_AUTHENTICATION
Set to 1 to enable digest authentication, 0 to disable digest authentication. Set to 0 by
default.
USE_HTTP_BASIC_AUTHENTICATION
Set to 1 to enable basic authentication, 0 to disable basic authentication. Set to 1 by de-
fault.
In the real world, the user may need to check the number of bytes available to be sure they don't
overwrite the buffer. The buffer must end with "\r\n" and be NULL-terminated.
The local timezone offset may be defined using the TIMEZONE macro, or it may be obtained
automatically from a DHCP server if you are using DHCP to configure the network interface.
Failing that, it defaults to zero.
If the RTC is already set to UTC (not local time), then you must define the macro RTC_IS_UTC,
in which case the local timezone offset will be ignored.
For many reasons, including the fact that daylight savings transitions are more manageable, it is
better to set the RTC to UTC, however some users prefer the clock to run in local time.
See the documentation for rtc_timezone() for more details. To do this, use the function
lookup feature in Dynamic C or refer to the Dynamic C Function Reference Manual.
tcp_reserveport(80);
while (1) {
http_handler();
}
}
In the media-types document located there, the text in the type column would precede the “/”, and
the subtype column would directly follow. Find the type subtype entry that matches your extension
and add it to the http_types table.
When you compile and run ssi.c, you see the LNK light on the board come on. Point your
browser at the controller (e.g., http://10.10.6.100/). The ACT light will flash a couple of times and
your browser will display the page.
This program displays pictures of LEDs. Their state is toggled by pressing the image of a button.
This program uses Server Side Includes (SSI) and the old style of CGI
(SSPEC_RESOURCE_FUNCTION). Use of SSI is explained in greater detail below.
In an shtml file, the “<!--#echo var="led1" -->“ is replaced by the value of the variable
led1 from the static resource table.
SSPEC_RESOURCETABLE_START
...
SSPEC_RESOURCE_ROOTVAR("led1", led1, PTR16, "%s"),
SSPEC_RESOURCE_ROOTVAR("led2", led2, PTR16, "%s"),
SSPEC_RESOURCE_ROOTVAR("led3", led3, PTR16, "%s"),
SSPEC_RESOURCE_ROOTVAR("led4", led4, PTR16, "%s"),
...
SSPEC_RESOURCETABLE_END
shtml_handler (which is the built-in script processor for SSI) looks up led1 and replaces it
with the text output from:
printf("%s",(char*)led1);
The led1 variable is either ledon.gif or ledoff.gif. When the browser loads the page, it
replaces
<img SRC="<!--#echo var="led1"-->">
with
<img SRC="ledon.gif">
When the user clicks on the button, the browser will request the /led1tog.cgi entity. This
causes the HTTP server to examine the contents of the http_flashspec structure looking for
/led1tog.cgi. It finds it and notices that led1toggle() needs to be called.
The led1toggle function changes the value of the led1 variable, then redirects the browser
back to the original page. When the original page is reloaded by the browser, the LED image will
have changed states to reflect the user’s action.
This sample demonstrates the so-called “old-style” CGI. New-style CGIs are easier to write (espe-
cially when they are doing something non-trivial). They are described in Section 4.6 "HTTP File
Upload."
case 4:
strcpy(state->buffer,"<p>Go <a
href=\"/\">home</a></body> </html>\r\n");
state->length = strlen(state->buffer);
state->substate++;
break;
default:
state->substate = 0;
return 1;
}
}
return 0;
}
Since we will not be using the static resource table, we can define the following macro, to remove
some code for handling this table from Zserver.
#define HTTP_NO_FLASHSPEC
These lines are part of the standard TCP/IP and MIME table configuration.
#memmap xmem
#use "dcrtcp.lib"
#use "http.lib"
SSPEC_MIMETABLE_START
SSPEC_MIME(".html", "text/html")
SSPEC_MIMETABLE_END
These are the declarations of the variables that will be included in the form.
int temphi;
int tempnow;
int templo;
float humidity;
char fail[21];
An array of type FormVar must be declared to hold information about the form variables. Be
sure to allocate enough entries in the array to hold all of the variables that will go in the form. If
more forms are needed, then more of these arrays can be allocated.
FormVar myform[5];
These variables will hold the indices in the TCP/IP servers’ object list for the form and the form
variables.
int var;
int form;
This array holds the possible values for the fail variable. The fail variable will be used to make a
pulldown menu in the HTML form.
temphi = 80;
tempnow = 72;
templo = 65;
humidity = 0.3;
strcpy(fail, "Page");
The next line adds a form to the dynamic resource table. The first parameter gives the name of the
form. When a browser requests the page “myform.html” the HTML form is generated and pre-
sented to the browser. The second parameter gives the developer-declared array in which form
information will be saved. The third parameter gives the number of entries in the myform array
(this number should match the one given in the myform declaration above). The fourth parameter
indicates that this form should only be accessible to the HTTP server, and not the FTP server.
SERVER_HTTP should always be given for HTML forms. The return value is the index of the
newly created form in the dynamic resource table.
The following line adds a variable to the resource table. It must be added to this table before being
added to the form. The first parameter is the name to be given to the variable, the second is the
address of the variable, the third is the type of variable (this can be INT8, INT16, INT32,
FLOAT32, or PTR16), the fourth is a printf-style format specifier that indicates how the variable
should be printed, and the fifth is the server for which this variable is accessible. The return value
is the handle of the variable in the resource table.
The following line adds a variable to a form. The first parameter is the index of the form to add the
variable to (the return value of sspec_addform()), and the second parameter is the index of
the variable ( the return value of sspec_addvariable()). The return value is the index of
the variable within the developer-declared FormVar array, myform.
This function sets the name of a form variable that will be displayed in the first column of the form
table. If this name is not set, it defaults to the name for the variable in the resource table (“temphi”,
in this case). The first parameter is the form in which the variable is located, the second parameter
is the variable index within the form, and the third parameter is the name for the form variable.
This function sets the description of the form variable, which is displayed in the third column of
the form table.
This function sets the length of the string representation of the form variable. In this case, the text
box for the form variable in the HTML form will be 5 characters long. If the user enters a value
longer than 5 characters, the extra characters will be ignored.
This function sets the range of values for the given form variable. The variable must be within the
range of 60 to 90, inclusive, or an error will be generated when the form is submitted.
This concludes setting up the first variable. The next five lines set up the second variable, which
represents the current temperature.
Since the value of the second variable should not be modifiable via the HTML form (by default
variables are modifiable,) the following line is necessary and makes the given form variable read-
only when the third parameter is 1. The variable will be displayed in the form table, but can not be
modified within the form.
These lines set up the low temperature variable. It is set up in much the same way as the high tem-
perature variable.
This code begins setting up the string variable that specifies what to do in case of air conditioning
failure. Note that the variable is of type PTR16, and that the address of the variable is not given to
sspec_addvariable(), since the variable fail already represents an address.
This function sets the type of form element that is used to represent the variable. The default is
HTML_FORM_TEXT, which is a standard text entry box. This line sets the type to
HTML_FORM_PULLDOWN, which is a pull-down menu.
Finally, this code sets up the last variable. Note that it is a float, so FLOAT32 is given in the
sspec_addvariable() call. The last function call is sspec_setfvfloatrange()
instead of sspec_setfvrange(), since this is a floating point variable.
These calls create aliases in the dynamic resource table for the HTML form. That is, the same
form can now be generated by requesting “index.html” or “/”. Note that
sspec_aliasspec() should be called after the form has already been set up. The aliasing is
done by creating a new entry in the resource table and copying the original entry into the new
entry. Note that aliasing can also be done for files and other types of server objects.
sspec_aliasspec(form, "index.html");
sspec_aliasspec(form, "/");
These lines complete the sample program. They initialize the TCP/IP stack and web server, and
run the web server.
sock_init();
http_init();
while (1) {
http_handler();
}
}
The order of the above statements is important. A possible exception is that the order of
dcrtcp.lib and fat.lib may be interchanged, since these libraries are independent. How-
ever, it is recommended you use the given ordering since future releases of the FAT may be able to
use networking services.
The construction of this page is outlined below, but it has been simplified and reformatted slightly.
A blow-by-blow description of each line is added in italics.
CGI Syntax
All CGI functions are C functions with the following prototype:
int my_CGI(HttpState * s);
The HttpState parameter is a pointer to the internal state variables of the HTTP server instance
that is handling the current request. You can have one or more server instances. If there is more
than one, the same CGI may be invoked at the same time for more than one client (if both happen
to press the submit button at about the same time). Thus, it is important to write the CGI function
so that it is re-entrant. This basically means that the function should not update global or static
variables. The CGI should not attempt to modify directly any of the fields in the HttpState
structure, otherwise the server may become inoperable.
API Functions
The HTTP library provides a set of API functions that can be called safely from the CGI. The list
of safe functions is in the index under “Function Reference, CGI.”
It is unwise to make direct calls to TCP/IP functions, especially functions that may not return for a
long time such as sock_read().
The above blank line is significant; it indicates the end of the initial header lines, and the start of
data.
--3vAL1QsFOUg2GsY3p6n3YQ
This is the first boundary. Boundary strings are always prefixed by an additional -- sequence. The
following lines are header lines for the individual part. The actual data follows the first empty line.
Content-Disposition: form-data; name="/A/new.htm"; filename="test.txt"
The Content-Disposition header indicates the presentation of the data. The only type which is rele-
vant is “form-data”. The name= parameter indicates the field name (which was originally part of
the name= parameter of the <input> element). The filename= parameter is only set if this is an
uploaded file. It gives the name of the file on the remote (client) side. This is not usually relevant to
the server. The name of the file as it is stored on the server is not specified (since the browser does
not know it or have control over where the file is stored). We are using the convention that the field
name indicates the local file name, but this is just a convention!
Content-Type: text/plain
Content-Type indicates the type of information. The default is plain (i.e. ascii) text, however it could
also be set to image/gif for a GIF file, text/html for HTML etc. The following blank line indicates the
end of headers for this part.
test file contents, first line
This is the actual file or form field content.
--3vAL1QsFOUg2GsY3p6n3YQ
The boundary string terminates the data for the previous part. Headers for the next part immediately
follow.
When writing the CGI, you do not have to worry about parsing the headers and boundary separa-
tors. This is already done by the HTTP server. However, you do need to be aware of the stream-
oriented nature of the incoming data. The HTTP server separates out the parts (and parses the
headers). As it does this, it calls the defined CGI with the data for each section.
Finally, at the end of all the parts, the action code is set to CGI_EOF.
Most CGIs should also handle a special action code called CGI_ABORT. This code only occurs if
the upload is terminated early by a network problem (or by the user pressing the browser’s cancel
or stop button).
Let’s examine a simple CGI that handles these five action codes. This is the minimum require-
ment; however, there are some additional codes that may be used by more advanced CGIs. The
switch statement ignores action codes that are not listed. This is deliberate, since any other action
codes may be safely ignored.
int my_CGI(HttpState * s)
{
switch(http_getAction(s)) {
case CGI_START:
break;
case CGI_DATA:
break;
case CGI_END:
break;
case CGI_EOF:
break;
case CGI_ABORT:
break;
}
return 0;
}
First, the open file handle is retrieved from the cond variable. This works because the HTTP server
does not touch these variables between calls. The only time the server changes the cond variables
is at the start of a completely new form submission, in which case they are usually set to zero. But
don’t depend on them being zero, since a form submission can sometimes contain syntax that sets
them to non-default values. You can rely on http_getState() returning zero on the very first
call; thereafter, it is not touched, but can be manipulated by the CGI calling the function
http_setState().
This is quite simple. We simply retrieve the handle, and close it.
The cgi_redirectto() function tells the HTTP server to stop calling this CGI function, and
tell the client to retrieve its next web page from the specified location (in this case, the
index.html page on the current server). The onus is on the client (browser) to go and get that
page. It will come straight back to this server, but the CGI does not have to worry about it. Easy!
In this example, we simply close the handle, possibly leaving the file with partially written con-
tents. It is important to do this, since if the handle is left open, then that handle is lost forever (or
until the next reboot). The CGI_ABORT code can happen at any time, so the CGI must handle it if
it ever uses “leakable” resources.
If you are alert, you noticed that CGI_ABORT may be called when there is no open handle. We
must guard against the possibility of trying to close an “invalid” handle, since it may happen to
belong to another active CGI. We can do this by ensuring the value in the cond variable is “-1” if
the handle is not open.
In the case of an error, the handle is closed, then the HTTP server presents the upld_err.html
page to the client. The current CGI is abandoned, including any pending data that is still incoming.
This is why the handle is explicitly closed (since upld_err.html probably doesn’t know any-
thing about it!). Naturally, upld_err.html is a web page that tells the user that something
went wrong. In practice, this would usually be an SSI rather than a static web page, since you
would probably want to give the user different feedback depending on the exact type of error.
The final consideration is what to do if sspec_write() can only write some (or perhaps none)
of the data it was given. The normal course of action is to just retry later, with the data that was not
written. You could just sit in a loop in the CGI function waiting for the data to be written. This
may be satisfactory in some cases, but often this will unnecessarily reduce system performance
(since nothing else will get a chance to run except interrupts). It is preferable to return to the HTTP
server, which in turn can return to the application before coming back into the CGI.
This defines a static resource table with two entries. The first is a static web page for the form
(index.html) and the second points to the CGI that will be used to process the uploaded data.
Important: use SSPEC_RESOURCE_CGI, not SSPEC_RESOURCE_FUNCTION - this defines
the CGI as new-style. SSPEC_RESOURCE_XMEMFILE specifies a file that has been imported in
the server’s flash memory using the #ximport directive. For example,
#ximport "samples/tcpip/http/pages/upload.html" index_html
index_html is a placeholder (a long int) for the start of the file. This is mentioned in the
resource table entry so that the server knows where to get it.
The second entry above specifies a “new-style” CGI function, which has been the subject of the
preceding sections. You must use the SSPEC_RESOURCE_CGI macro to specify this type of
CGI. The URL (string) parameter is whatever is mentioned in the <form action=...> parameter of
the initial web page. The other parameter is the function pointer to the CGI that will process the
upload.
If you do not wish to write a CGI just for handling file uploads, you could specify
http_defaultCGI() as the CGI function.
SSPEC_MIMETABLE_START
SSPEC_MIME(".htm", "text/html"),
SSPEC_MIME(".html", "text/html"),
SSPEC_MIME(".gif", "image/gif"),
SSPEC_MIME(".cgi", "")
SSPEC_MIMETABLE_END
This method of creating the MIME type mapping table is new with Dynamic C version 8.5.
By default, every other file in the filesystem(s) that is not covered by this rule is denied write
access. In general, a rule is only required when it is desired to permit write access (not deny it).
All error handling has been pared out of the above code. For full details, please refer to the sample
program samples\tcpip\http\upld_fat.c.
cgi_continue
DESCRIPTION
Called from a CGI function after processing any data submitted. This function contin-
ues creating a response as if from a normal GET request to the specified local URL.
NOTE: the CGI function must NOT have sent any data to the socket.
PARAMETERS
localurl The URL string, which must be a URL defined in the server spec
table (otherwise the browser will see a "not found" message).
RETURN VALUE
The return value from this function should be used as the return value from the CGI
handler function that calls it.
LIBRARY
HTTP.LIB
DESCRIPTION
This utility function may be called in a CGI function to redirect the user to another page.
It sends a user to the URL stored in url. You should immediately issue a “return
0;” after calling this function. The CGI is considered finished when you call this, and
will be in an undefined state.
The http samples work correctly with cgi_redirectto() because they use macro
constants to define the URL parameter. If you manipulate the url string, please be aware
of the following issues:
• The library function sets a pointer to the 2nd parameter - url. The calling routine is
responsible for ensuring that the location represented by the pointer remains valid
after the call. This is because the URL string will not be processed until after the
CGI function is finished.
• If the application has MAX_TCP_SOCKET_BUFFERS and
HTTP_MAXSERVERS set to more than one, it is possible that the CGI function
will be called successively with different server states serving different client
requests. In these circumstances it is necessary to ensure that the pointer to the url
is valid for each of the server states.
• After the cgi function has called cgi_redirecto() and returns 0, the
http_handler then causes the server response to be sent to the browser. The infor-
mation is sent as follows:
1. HTTP header response containing the redirection information response code
302.
2. A human readable redirection html page telling the user that redirection has
taken place, and to click "here" to go to the new URL. This is for browsers
that do not recognize the redirection 302 command in the header.
This may cause a problem for browsers which do recognize the 302 redirection
command. Some browsers immediately issue a GET request to the new location
while still reading in the human readable page. If MAX_TCP_SOCKET_BUFFERS
and HTTP_MAXSERVERS are set to one, the server will not receive the GET
request because it is busy sending out the human-readable page. The symptom is
that the browser appears to time-out. (This timing problem may be masked when a
proxy server is used.) Set MAX_TCP_SOCKET_BUFFERS and
HTTP_MAXSERVERS to a value more than one to prevent this problem.
RETURN VALUE
None - sets the state, so the CGI must immediately return with a value of 0.
LIBRARY
HTTP.LIB
SEE ALSO
cgi_sendstring
cgi_sendstring
DESCRIPTION
Sends a string to the user. You should immediately issue a “return 0;” after calling
this function. The CGI is considered finished when you call this, and will be in an un-
defined state. This function greatly simplifies a CGI handler because it allows you to
generate your page in a buffer, and then let the library handle writing it to the network.
PARAMETERS
RETURN VALUE
None - sets the state, so the CGI must immediately return with a value of 0.
LIBRARY
HTTP.LIB
SEE ALSO
cgi_redirectto
DESCRIPTION
Terminate this CGI request. The client will receive an error message indicating the con-
nection was closed.
The CGI should not make any further HTTP calls after calling this function. It should
clean up any resources that it opened, since no further calls are made to this CGI for this
request.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
0
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction, http_skipCGI, http_switchCGI, http_finishCGI,
http_write
DESCRIPTION
Adds a file to the dynamic resource table.
PARAMETERS
RETURN VALUE
0: Success.
1: Failure.
LIBRARY
HTTP.LIB
SEE ALSO
http_delfile
DESCRIPTION
Converts a string to include HTTP transfer-coding tokens (such as @ (decimal) for
at-sign) where appropriate. Encodes these characters: ''<>@%#&''
Source string is NULL-byte terminated. Destination buffer is bounded by len. This
function is reentrant.
PARAMETERS
RETURN VALUE
dest: There was room for all conversions.
NULL: Not enough room.
LIBRARY
HTTP.LIB
SEE ALSO
http_urldecode
DESCRIPTION
Print the date (time zone adjusted) into the given buffer. This assumes there is room!
PARAMETERS
buf The buffer to write the date into. This requires at least 30 bytes in
the destination buffer.
RETURN VALUE
A pointer to the string.
LIBRARY
HTTP.LIB
SEE ALSO
http_handler
DESCRIPTION
This function should not be called directly by the application. It is intended to be used
as a new-style CGI for handling file uploads. See "samples\tcpip\http\upld_fat.c" for an
example of using this function.
This CGI function accepts POST requests from the client (browser) which may contain
one or more files that are being uploaded. It looks at the field name of the form data in
the request. If the field name starts with “/”, it is assumed to be the name of a resource
which is to be created (if it does not already exist) and overwritten with the uploaded
file contents.
There are three steps required to use this CGI:
1. Define a CGI resource in the flash- or ram-spec table. If using flashspec, for
example, there would be an entry like
SSPEC_RESOURCETABLE_START
SSPEC_RESOURCE_XMEMFILE("/index.html",index_html),
SSPEC_RESOURCE_CGI("/upload.cgi", http_defaultCGI)
SSPEC_RESOURCETABLE_END
There may be other resources, but at least two are normally required. One
resource is a web page (see below) that contains a form the user can fill in
with the name of the file to upload. The other resource (CGI) is a reference to
this function, giving it a URL name that identifies it to the browser.
2. Create a web page which contains a form like the following skeleton exam-
ple:
<FORM ACTION="/upload.cgi" METHOD="POST"
enctype="multipart/form-data">
<INPUT TYPE="FILE" NAME="/A/incoming/new.htm">
<INPUT TYPE="SUBMIT" VALUE="Upload">
</FORM>
in the <FORM> element, the ACTION= parameter specifies the URL
assigned to this CGI. In the <INPUT TYPE= "FILE"> element, the NAME=
parameter specifies the resource name used to contain the uploaded file con-
tents. In this example, the resource is called "/A/incoming/new.htm", which
will work if you are using the FAT filesystem.
If uploading to a subdirectory, “incoming” in the above example, the subdi-
rectory must already exist. If not, the upload will fail.
PARAMETERS
newURL The resource name to present to the client. This may be another
CGI, or any other type of resource that could be presented to the
client in response to an HTTP GET or POST request. The resource
must exist in the flash- or ram-spec table, or in a filesystem.
RETURN VALUE
See documentation for "writing a data handler CGI"
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction, http_skipCGI, http_switchCGI, http_finishCGI,
http_write
DESCRIPTION
Deletes a file from the RAM spec table.
PARAMETERS
RETURN VALUE
0: Success;
1: Failure (not found).
LIBRARY
HTTP.LIB
SEE ALSO
http_addfile
DESCRIPTION
Finds the occurrence of the given variable in the HTML form error buffer, and returns
its location.
PARAMETERS
RETURN VALUE
NULL: Failure.
!NULL: Success, location of the variable in the error buffer.
LIBRARY
HTTP.LIB
DESCRIPTION
Finds a spec entry, searching first in RAM, then in flash.
This function is deprecated as of Dynamic C 8.50. Use sspec_findname().
PARAMETERS
RETURN VALUE
The spec entry.
LIBRARY
HTTP.LIB
DESCRIPTION
Indicate to the HTTP server that this CGI has finished processing data from this multi-
part data stream. The server reads (and discards) data to the end of the entire stream (in-
cluding epilog). The next call to the CGI function will have an action code of
CGI_EOF (or possibly CGI_ABORT if there was a stream error).
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
0
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction, http_skipCGI, http_abortCGI, http_switchCGI, ,
http_write
DESCRIPTION
Return the current CGI action. This should be called only from a CGI function regis-
tered as a SSPEC_CGI resource in the zserver resource table.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Action code. One of the following values:
• CGI_START - start of a part in a multi-part transfer.
• CGI_DATA - binary data for this part
• CGI_END - end of a part
• CGI_HEADER - header line of a part
• CGI_PROLOG - binary data before the first part
• CGI_EPILOG - line of data after the last part
• CGI_EOF - normal end of all parts and epilog
• CGI_ABORT - abnormal termination. CGI should recover and/or close any
open resources.
• CGI_CONTINUE - being called from the HTTP server after the CGI previously
returned CGI_MORE.
LIBRARY
HTTP.LIB
SEE ALSO
(functions mentioned above), http_defaultCGI
DESCRIPTION
Return the current HTTP condition state variable (aka., cond variable). There are
HTTP_MAX_COND of these integer state variables, thus idx must be between 0 and
HTTP_MAX_COND-1, inclusive.
Use of cond variables is entirely up to the application; however, they are initialized by
the HTTP server under certain conditions. By default, they are set to zero at the start of
each request from the client. If the client request includes URL GET-type parameters
of the form http://host/resource.html?A=1&B=2&C=3 etc. then cond state 0 is set to
the value for 'A', cond state 1 is set to the value for 'B' etc. The values must be integers,
which are coerced into 16 bit signed integers.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Value of cond variable idx.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction, http_setCond
DESCRIPTION
Return the current disposition of the data which is being provided by the client. This is
one of the following enumerated values:
• MIME_DISP_NONE: unspecified disposition
• MIME_DISP_INLINE: the content is to be displayed "inline"
• MIME_DISP_ATTACHMENT: the content is only to be displayed if there is
some action by the user
• MIME_DISP_FORMDATA: the content is form field data (or an uploaded file).
Of these, only NONE and FORMDATA are really relevant to HTTP. It is only valid to call
this when the action code is CGI_START, CGI_DATA or CGI_END.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Content disposition code, as documented above.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the length of data in the current part of a multi-part data stream. The return value
is interpreted differently, depending on the action code.
It is only valid to call this when the action code is CGI_START, CGI_DATA or
CGI_END.
When CGI_START, this returns the value of the ContentLength header for this part (or
-1 if there was no such header).
When CGI_DATA or CGI_END, it is the total number of bytes that have actually been
read and presented to the CGI. This increases for each CGI_DATA call, until it repre-
sents the total content length when action is CGI_END.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Length of part data.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the current content type of the data which is being provided by the client. This
is a MIME type string e.g. "text/html" or "image/jpeg".
The CGI might need to look at this to determine the appropriate way to process the data.
Normal form fields will usually contain "text/plain", however uploaded files may con-
tain any type of data.
It is only valid to call this when the action code is CGI_START, CGI_DATA or
CGI_END.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Null terminated string containing the MIME type name.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the ServerContext struct for the specified HTTP server instance.
PARAMETER
RETURN VALUE
NULL: invalid server instance.
Otherwise, pointer to this server's ServerContext.
LIBRARY
HTTP.LIB
DESCRIPTION
Return the current HTTP server context. The context pointer is required by many zserv-
er resource handler functions.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Pointer to the HTTP server's context structure. See zserver documentation.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return a pointer to the data that is available. It is only valid to call this if the action code
is one of CGI_DATA, CGI_PROLOG, CGI_EPILOG, CGI_HEADER or CGI_EOF.
When CGI_DATA, this is the next chunk of data received as the content of the current
part of a multi-part transfer. The data arrives in arbitrary amounts. CRLF boundaries (if
any) are not respected, and the data may contain NULLs and other binary values. THE
CGI MUST CONSUME ALL DATA PROVIDED since the data will not be presented
again on the next call.
When CGI_PROLOG, this is data that occurs before the first boundary (part) but after
the main HTTP headers. This data (like that for CGI_DATA) is not line-oriented.
When CGI_EPILOG, CGI_HEADER or CGI_EOF, the data will be a complete line of
input (with the terminating CRLF stripped off). The returned string will also be null-
terminated. When CGI_EOF, the data (if any) is technically part of the epilog.
Prolog data is lines of input that were provided before the first "official" part of the
multi-part data. Most HTTP clients will not provide any prolog data. Epilog data is lines
of data after the last official part. Again, HTTP clients do not usually generate it. It is
always safe to ignore prolog and epilog data, since it is usually provided only for non-
MIME compliant servers.
Data provided when the action is CGI_HEADER is a line of header data provided at the
start of each part of the multi-part data. It is safe for the CGI to ignore header lines, since
the HTTP server also processes the ones that it needs. The CGI is given these header
lines so that it can extract useful or customized information if desired.
The length of the data may be obtained using http_getDataLength().
The CGI is allowed to overwrite data at the returned area, provided that it writes no
more than HTTP_MAXBUFFER bytes.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Pointer to the first character of data.
SEE ALSO
http_getAction
DESCRIPTION
Return the length of data that is available. It is only valid to call this if it is valid to call
http_getData(). That is, if the action code is one of CGI_DATA, CGI_PROLOG,
CGI_EPILOG, CGI_HEADER or CGI_EOF.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Length of available data. This will range from 0 to HTTP_MAXBUFFER. 0 will only be
returned for PROLOG and EPILOG when a blank line is read.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the current form field name. This function should only be called when the action
code is CGI_START, CGI_DATA or CGI_END.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Null-terminated string containing the current field name. The field name is the name of
a form element, specified using, for example,
<INPUT TYPE="TEXT" NAME="srv_file">
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the HTTP request method of the current request protocol. The CGI might need
to look at this to generate the correct response headers.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
One of the following codes:
• HTTP_METHOD_GET - "GET" i.e., normal retrieval, without making any per-
manent state update.
• HTTP_METHOD_POST - "POST" i.e., uploading some information to be stored,
or making some permanent state change. This is the normal method for invoking
CGIs.
• HTTP_METHOD_HEAD - "HEAD" i.e., the client only wants the headers, not
the actual content e.g. it might be trying to determine the most recent modifica-
tion date.
Other codes may be returned in the future.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the HTTP version number of the current request protocol. The CGI might need
to look at this in order to generate the correct response headers.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
One of the following codes:
• HTTP_VER_09 - version 0.9
• HTTP_VER_10 - version 1.0
• HTTP_VER_11 - version 1.1
Other codes may be returned in the future.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the remaining length of the incoming data stream. This length includes all parts
(not just the current part) and also includes the boundary separators and epilog data.
Normally, this value will be zero when the action code is CGI_EOF. If the value is neg-
ative, then the client might not have indicated the total data length, or might not have
set the right value.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Length of remaining data, or negative if not known.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the current HTTP server socket. The socket may be written/read; however, this
is inadvisable since it may interfere with the server's use of it.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Pointer to the HTTP server's TCP socket structure.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the current primary HTTP CGI state variable.
Use of this state variable is entirely up to the application; however, it is initialized by
the HTTP server to zero before calling the CGI for the first time.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Value of primary state variable.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the current encoding of the data which is being provided by the client. This is
one of the following enumerated values:
• CTE_BINARY The default
• CTE_7BIT 7-bit safe ASCII
• CTE_8BIT 8-bit ASCII
• CTE_QP Quoted printable
• CTE_BASE64 Base 64
Of these, the CGI is only likely to see CTE_BINARY, since HTTP is an 8-bit protocol,
and most clients (browsers) will not bother to encode the data. Encoding is only an issue
for internet mail, which sometimes has to cross interfaces that do not support full 8-bit
binary transfers.
If the CGI detects a transfer encoding that requires non-null operation (that is, CTE_QP
or CTE_BASE64) then it should either reject the transfer, or decode the data as it
comes in.
It is only valid to call this when the action code is CGI_START, CGI_DATA or
CGI_END.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Transfer encoding code, as documented above.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Return the URL of the current HTTP client request. In a CGI, this will usually be some-
thing like foo.cgi.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Null-terminated string containing the URL. Note that GET-style form parameters will
be stripped off: for example, the URL, foo.cgi?A=99&D=-45, will be returned as
foo.cgi.
The GET parameters are available using http_getCond().
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Get the "user state" area of the HTTP server structure. This is an area of memory that
can be used by the CGI to keep track of its internal state, from call to call.
The size of this area is HTTP_USERDATA_SIZE. If that macro is not defined, it de-
faults to zero, so use of the http_getUserState macro will result in a compile-
time error.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Returns the address of the first byte of the user area. This should be cast to the appro-
priate structure type.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
This is the basic control function for the HTTP server, a tick function to run the HTTP
daemon. It must be called periodically for the daemon to work. It parses the requests
and passes control to the other handlers, either html_handler, shtml_handler,
or to the developer-defined CGI handler based on the request’s extension.
LIBRARY
HTTP.LIB
SEE ALSO
http_init
DESCRIPTION
Query to see if any HTTP servers are active.
RETURN VALUE
0: at least one HTTP server is active
1: all HTTP servers are idle
LIBRARY
HTTP.LIB
SEE ALSO
http_handler
DESCRIPTION
Initializes the HTTP daemon. This must be called after sock_init(), and before
calling http_handler() in a loop.
This sets the root directory to "/" and sets the default file name to index.html. You
can change these defaults by calling http_set_path() after this function.
You can override these defaults at compile-time by defining the macros
#define HTTP_HOMEDIR "/"
#define HTTP_DFLTFILE "index.html"
to be something other than these defaults. If you do this, then there is no need to invoke
the http_set_path() function.
RETURN VALUE
0: Success.
LIBRARY
HTTP.LIB
SEE ALSO
http_handler, http_shutdown, http_status, http_set_path
DESCRIPTION
Gets the information for the next variable in the HTML form error buffer. If any of the
last four parameters in the function call are NULL, then those parameters will not have
a value returned. This is useful if you are only interested in certain variable information.
PARAMETERS
start Pointer to the variable in the buffer for which we want to get infor-
mation.
next Return location for a pointer to the variable after this one.
RETURN VALUE
None, although information is returned in the last four parameters.
LIBRARY
HTTP.LIB
DESCRIPTION
Parses the returned form information. It expects a POST submission. This function is
useful for a developer who only wants the parsing functionality and wishes to generate
forms herself. Note that the developer must still build the array of FormVars and use
the server_spec table. This function will not, however, automatically display the
form when used by itself. If all variables satisfy all integrity checks, then the variables’
values are updated. If any variables fail, then none of the values are updated, and error
information is written into the error buffer If this function is used directly, the developer
must process errors.
PARAMETERS
state The HTTP server with which to parse the POSTed data.
RETURN VALUE
0: There is more processing to do;
1: Form processing has been completed.
LIBRARY
HTTP.LIB
int http_safe( char * to, char * from, int tolen, int fromlen );
DESCRIPTION
Convert a http-unsafe string in from (length fromlen ) into a properly escaped
string. For example, the string "hello&goodbye<>" would be changed to
"hello&goodbye<>".
Returns non-zero if result could not fit in tolen-1 bytes. A null is always added, thus
tolen should account for this. Double quotes are escaped since the result may itself
be quoted.
Newline characters are turned into HTML line break "<BR>" markup. Control charac-
ters (codes less than 32) are turned into "&#xx;" where "xx" is the hexadecimal control
char value. The source string can contain null character(s) which is why its length is
passed in the parameter fromlen.
PARAMETERS
RETURN VALUE
0 on success
non-zero if resulting string (plus its null terminator) could not fit in the provided buffer.
LIBRARY
HTTP.LIB
SEE ALSO
http_handler
DESCRIPTION
This function allows you to scan a buffer with a POST response for the key/value pairs.
This function is reentrant.
PARAMETERS
RETURN VALUE
0: Successful
!0: Not successful
LIBRARY
HTTP.LIB
DESCRIPTION
Set the “anonymous” user ID. This is the assumed user ID when no credentials are pro-
vided by the client (browser). A typical use of this function would be:
int anon;
anon = sauth_adduser("anonymous", "",
SERVER_FTP|SERVER_HTTP);
sauth_setusermask(uid, WORLD_GROUP, NULL);
http_set_anonymous(uid);
ftp_set_anonymous(uid); // if using FTP too
which defines an “anonymous” login for the HTTP and, optionally, the FTP servers.
(Since FTP also requires an anon user, you can use the same user ID for both FTP and
HTTP).
When a web browser initially requests a resource, it may not pass any user credentials
(i.e., user name and password). The HTTP server will assume that the user is anony-
mous, and apply the access permissions tests on that basis. If access is denied, then the
browser will prompt the user for a real user name and password, and the request will be
re-tried.
You do not always need to define an anonymous user to HTTP. But it is required if you
have some resource which is (say) protected for write access, but you want any user to
be able to retrieve the resource without requiring a user name/password.
NOTE: This function is non-reentrant. It sets a global variable which is accessed by all
HTTP server instances. For this reason, you should call this function once only before
starting to call http_handler().
PARAMETER
uid The userID to use as the anonymous user. This should have been
defined using sauth_adduser(). Pass -1 to set no anony-
mous user. In this case, only resources which are completely free
of any access controls will be accessible to users who do not pro-
vide credentials.
RETURN VALUE
Same as the uid parameter, except -1 if uid invalid.
LIBRARY
HTTP.LIB
SEE ALSO
sauth_adduser, ftp_set_anonymous, sauth_setusermask
DESCRIPTION
Sets the type of authentication to be used globally by the HTTP server. By default, this
is set to the strongest available type of authentication available (in order of weakest to
strongest: HTTP_NO_AUTH, HTTP_BASIC_AUTH, HTTP_DIGEST_AUTH. This
function returns the type of authentication that was actually configured. If the type of
authentication that you ask for was not compiled in at compile time, then the type of
authentication will not be changed.
NOTE: this function only sets the "default" authentication method for resources who
have their authentication method set to SERVER_AUTH_DEFAULT (or, none speci-
fied).
PARAMETERS
LIBRARY
HTTP.LIB
DESCRIPTION
Set the value of an HTTP condition state variable (aka., cond variable). There are
HTTP_MAX_COND of these integer state variables, thus idx must be between 0 and
HTTP_MAX_COND-1, inclusive.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Returns the new value of the cond variable, i.e., val.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction, http_getCond
DESCRIPTION
This utility generates a cookie on the client. This will store the text in value into a
cookie-generation header that will be written to buf. The header placed in buf is not
automatically sent to the web client. It is the caller’s responsibility to send the header
in buf, along with any other HTTP headers, to the client.
When a page is requested from the client, and the cookie is already set, the text of the
cookie will be stored in state->cookie[]. This is a char*, and if no cookie was
available, state->cookie[0] will equal '\0'.
PARAMETERS
buf Buffer to store cookie-generation header, that is, the name of the
cookie.
value Text to store in cookie-generation header, that is, the value of the
cookie.
LIBRARY
HTTP.LIB
DESCRIPTION
Set the default root directory and resource name for all HTTP server instances. In gen-
eral, this function should be called once only, after http_init() but before
http_handler().
The root directory is the base directory and is used as a prefix for all resource requests
from clients. For example, if the root directory is set to "/A/" then a client request for
http://<hostname>/foo.htm will look up the resource called /A/foo.htm
on this server.
The default resource name is used if the client's URL requests a directory. For example,
if dfltname is set to "index.htm" (and rootdir is "/A/") then a client request for
“http://<hostname>/admin" will look up the resource called "/A/admin". If that
resource is actually a directory, then it will look up a resource called
"/A/admin/index.htm". If it is not a directory, then the default name is not used.
PARAMETERS
RETURN VALUE
0: OK
-E2BIG: rootdir was too long. It should be limited to less than about 12 characters, but
you can increase the value of SSPEC_MAXNAME if necessary.
-EINVAL: rootdir was NULL, or did not start and end with a forward slash character.
LIBRARY
HTTP.LIB
SEE ALSO
http_handler, http_init
DESCRIPTION
Set the current primary HTTP CGI state variable.
Use of this state variable is entirely up to the application; however, it is initialized by
the HTTP server to zero before calling the CGI for the first time.
PARAMETER
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Returns the new value, that is, val.
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction
DESCRIPTION
Shut down the http daemon. Use http_init() to restart.
PARAMETER
If non-zero, current connections are allowed to terminate normally. Otherwise, any
open connections are reset.
RETURN VALUE
0
LIBRARY
HTTP.LIB
SEE ALSO
http_handler, http_init, http_status
DESCRIPTION
Indicate to the HTTP server that the CGI has finished processing this part of a multi-
part data stream. The server reads (and discards) data from the stream until the next part
is found (or the epilog). When the next part is found, the server continues calling the
CGI function as before.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
0
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction, http_abortCGI, http_switchCGI,
http_finishCGI, http_write
DESCRIPTION
HTTP wrapper function for sock_bytesready(). This function may be used by
CGI applications to determine if there is data waiting on the socket associated with a
particular HTTP server.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
-1: no bytes waiting to be read
0: in ASCII mode, a blank line is waiting to be read,
or, for UDP, an empty datagram is waiting to be read
>0: number of bytes waiting to be read
LIBRARY
HTTP.LIB
DESCRIPTION
HTTP wrapper function for sock_fastread(), that is for non-blocking reads
(root). This function can be used to read data from a socket associated with a particular
HTTP server. This function is intended for use in CGI applications.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
>0: the number of bytes read
-1: error
LIBRARY
HTTP.LIB
DESCRIPTION
HTTP wrapper function for sock_fastwrite(), that is, for non-blocking writes.
This function can be used to write data from a root buffer to a socket associated with a
particular HTTP server. This function is intended for use in CGI applications.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
>0: the number of bytes written
-1: error
LIBRARY
HTTP.LIB
DESCRIPTION
HTTP wrapper function for sock_gets(). This function can be used by CGI appli-
cations to retrieve a string waiting on an ASCII-mode socket associated with a partic-
ular HTTP server.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
0: if buffer is empty, or
if no “\r” or “\n” is read, but buffer had room and
the connection can get more data!
>0: is the length of the string
-1: error
LIBRARY
HTTP.LIB
SEE ALSO
http_sock_mode
DESCRIPTION
HTTP socket wrapper function for socket mode. This function can be used by CGI ap-
plications to set the mode of a socket associated with a particular HTTP server.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
mode HTTP mode to use for the socket. Valid values for mode are:
• HTTP_MODE_ASCII - Sets the associated socket to
ASCII mode.
• HTTP_MODE_BINARY - Sets the associated socket to
BINARY.
RETURN VALUE
None
LIBRARY
HTTP.LIB
DESCRIPTION
HTTP wrapper function for sock_tbleft(). This function may be used by CGI ap-
plications to determine how much space is left in the HTTP socket's transmit buffer.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Number of bytes of free space remaining in the transmit buffer.
LIBRARY
HTTP.LIB
DESCRIPTION
HTTP wrapper function for blocking writes. This function can be used to write data
from a root buffer to a socket associated with a particular HTTP server. This function
is intended for use in CGI applications.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Number of bytes of written or -1 if there was an error
LIBRARY
HTTP.LIB
DESCRIPTION
HTTP wrapper function for sock_fastxread(), that is, for non-blocking reads
(xmem). This function can be used to read data from a socket associated with a partic-
ular HTTP server. This function is intended for use in CGI applications.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Number of bytes of read or -1 if there was an error
LIBRARY
HTTP.LIB
DESCRIPTION
HTTP wrapper function for sock_xfastwrite(), that is for non-blocking writes.
This function can be used to write the contents of an xmem buffer to a socket associated
with a particular HTTP server.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
RETURN VALUE
Number of bytes of written or -1 if there was an error
LIBRARY
HTTP.LIB
DESCRIPTION
Determine whether the HTTP server is allowing connections.
RETURN VALUE
0: server is currently disabled
non-zero: server is enabled.
LIBRARY
HTTP.LIB
SEE ALSO
http_handler, http_init, http_shutdown
DESCRIPTION
Tell the HTTP server to switch processing to a different CGI function or resource.
The CGI is responsible for generating the correct HTTP response header(s) using
http_write() etc. If this function is used to pass control to a different CGI, then
both CGIs must coordinate so that only one header is written. You can use the HTTP
state variable (http_setState() and http_getState()) and/or
http_getUserState() to achieve the necessary coordination.
If newURL refers to a file or SSI resource (not a CGI), then the CGI function must NOT
have already written the HTTP response header(s)—the headers will be generated
when the new resource is opened.
If newURL refers to a new-style CGI (that is, a CGI resource added using
SSPEC_CGI, not SSPEC_FUNCTION) then that CGI is presented with the remaining
content of the current request data stream.
If newURL refers to an old-style CGI (that is, a CGI added using SSPEC_FUNCTION
or HTTPSPEC_FUNCTION) then the HTTP server abandons parsing of the request
data stream, since old-style CGIs are expected to read the HTTP socket themselves.
Rather than calling http_switchCGI(), it is often more convenient to call
cgi_redirectto(), which tells the client to retrieve the next resource rather than
the resource being provided in the current connection. Using redirect is less efficient,
however.
PARAMETERS
state HTTP state pointer, as provided in the first parameter to the CGI
function.
newURL The resource name to present to the client. This may be another
CGI, or any other type of resource that could be presented to the
client in response to an HTTP GET or POST request. The resource
must exist in the flash- or ram-spec table, or in a filesystem.
RETURN VALUE
0
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction, http_skipCGI, http_abortCGI, http_finishCGI,
http_write
DESCRIPTION
Converts a string with URL-escaped ''tokens'' (such as %20 (hex) for space) into actual
values. Changes "+" into a space. String can be NULL terminated; it is also bounded by
a specified string length. This function is reentrant.
PARAMETERS
RETURN VALUE
dest: if all conversion was good.
NULL: if some conversion had trouble.
LIBRARY
HTTP.LIB
SEE ALSO
http_contentencode
DESCRIPTION
Write data back to the client. This function either sends all of the given data or none of
it. If the data cannot be sent (for example, because the socket transmit buffer is already
full) then a special return code indicates that the CGI should try again on the next call.
Often, the CGI itself will not need to write anything to the client—the
http_switchCGI() function takes care of most needs. If this function is used,
then the CGI is responsible for generating the correct HTTP response (including head-
ers) and http_switchCGI() and similar functions should NOT be called.
Use of this function can often be avoided. Instead, the CGI can copy a string to the
pointer provided by http_getData(), then return CGI_SEND. This will cause the
server to send out the (null terminated) string in the buffer, and not call the CGI until
the string is sent to the client. See the source to http_defaultCGI() for an exam-
ple of this method.
PARAMETERS
LIBRARY
HTTP.LIB
SEE ALSO
http_getAction, http_skipCGI, http_switchCGI, http_finishCGI,
http_abortCGI, http_defaultCGI
DESCRIPTION
Adds a CGI/SSI-exec function for making dynamic web pages to the RAM resource ta-
ble.
PARAMETERS
RETURN VALUE
0: Success;
1: Failure (no room).
LIBRARY
HTTP.LIB
SEE ALSO
shtml_delfunction
DESCRIPTION
This function adds a variable so it can be recognized by shtml_handler().
PARAMETERS
RETURN VALUE
0: Success.
1: Failure (no room).
LIBRARY
HTTP.LIB
SEE ALSO
shtml_delvariable
DESCRIPTION
Deletes a function from the RAM resource table.
PARAMETERS
RETURN VALUE
0: Success;
1: Failure (not found).
LIBRARY
HTTP.LIB
SEE ALSO
shtml_addfunction
DESCRIPTION
Deletes a variable from the RAM resource table.
PARAMETERS
RETURN VALUE
0: Success;
1: Failure (not found).
LIBRARY
HTTP.LIB
SEE ALSO
shtml_addvariable
The library FTP_CLIENT.LIB implements the File Transfer Protocol (FTP) for the client side
of the connection.
This library supports a single FTP session at any one time since the session state is maintained in a
single global structure in root memory.
You can upload and download files to either a static buffer in root data memory (for simple appli-
cations) or, starting with Dynamic C version 7.20, you can have the data passed to, or generated
by, a data handler callback function that you specify. The data handler function can implement
large file transfers in extended memory buffers, or it can be used to generate or process data on-
the-fly with minimal buffering.
Starting with Dynamic C 7.20, you can specify “passive” mode transfers. This is most important
for clients which are inside a firewall. Passive mode is specified by passing the
FTP_MODE_PASSIVE option to ftp_client_setup(). When passive mode is specified,
the client will actively open the data transfer port to the server, rather than the other way around.
This avoids the need for the server to penetrate the firewall with an active connection from the out-
side, which is most often blocked by the firewall. For this reason, it is recommended that your FTP
client application uses passive mode by default, unless overridden by an end-user.
FTP_MAX_DIRLEN
The default is 64, which is the maximum string length of a directory name.
FTP_MAX_FNLEN
The default is 16, which is the maximum string length of a file name.
FTP_MAX_NAMELEN
The default is 16 which is the maximum string length of usernames and passwords.
FTP_MAXLINE
The default is 256, which is both the maximum command line length and data chunk
size that can be passed between the FTP data transfer socket and the data handler (if
any defined).
FTP_TIMEOUT
The default is 16, which is the number of seconds that pass before a time out occurs.
ftp_client_setup
DESCRIPTION
Sets up a FTP transfer. It is called first, then ftp_client_tick() is called until it
returns non-zero. Failure can occur if the host address is zero, if length is negative,
or if the internal control socket to the FTP server cannot be opened (e.g., because of
lack of socket buffers).
PARAMETERS
buffer Buffer to get/put the file from/to. Must be NULL if a data handler
function will be used. See ftp_data_handler() for more
details.
LIBRARY
FTP_CLIENT.LIB
SEE ALSO
ftp_client_tick, ftp_data_handler
DESCRIPTION
Tick function to run the FTP daemon. Must be called periodically. The return codes
are not very specific. You can call ftp_last_code() to get the integer value of
the last FTP message received from the server. See RFC959 for details. For example,
code 530 means that the client was not logged in to the server.
RETURN VALUE
FTPC_AGAIN (0): still pending, call again.
FTPC_OK (1): success (file transfer complete).
FTPC_ERROR (2): failure (call ftp_last_code() for more details).
FTPC_NOHOST (3): failure (Couldn't connect to remote host).
FTPC_NOBUF (4): failure (no buffer or data handler).
FTPC_TIMEOUT (5): warning (Timed out on close: data may or may not be OK).
FTPC_DHERROR (6): error (Data handler error in FTPDH_END operation).
FTPC_CANCELLED (7): FTP control socket was aborted (reset) by the server.
LIBRARY
FTP_CLIENT.LIB
SEE ALSO
ftp_client_setup, ftp_client_filesize, ftp_client_xfer,
ftp_last_code
DESCRIPTION
Returns the byte count of data transferred. This function is deprecated in favor of
ftp_client_xfer(), which returns a long value.
If the number of bytes transferred was over 32767, then this function returns 32767
which may be misleading.
RETURN VALUE
Size, in bytes.
LIBRARY
FTP_CLIENT.LIB
SEE ALSO
ftp_client_setup, ftp_data_handler, ftp_client_xfer
DESCRIPTION
Returns the byte count of data transferred. Transfers of over 232 bytes (about 4GB) are
not reported correctly.
RETURN VALUE
Size, in bytes.
LIBRARY
FTP_CLIENT.LIB
SEE ALSO
ftp_client_setup, ftp_data_handler, ftp_client_filesize
DESCRIPTION
Sets a data handler for further FTP data transfer(s). This handler is only used if the
"buffer" parameter to ftp_client_setup() is passed as NULL.
The handler is a function which must be coded according to the following prototype:
int my_handler(char *data, int len, longword offset, int
flags, void *dhnd_data);
This function is called with data pointing to a data buffer, and len containing the
length of that buffer. offset is the byte number relative to the first byte of the entire
FTP stream. This is useful for data handler functions that do not wish to keep track of
the current state of the data source. dhnd_data is the pointer that was passed to
ftp_data_handler().
flags contains an indicator of the current operation:
• FTPDH_IN: data is to be stored on this host (obtained from an FTP download).
• FTPDH_OUT: data is to be filled with the next data to upload to the FTP server.
• FTPDH_END: data and len are irrelevant: this marks the end of data, and gives the
function an opportunity to e.g., close the file. Called after either in or out process-
ing.
• FTPDH_ABORT: end of data; error encountered during FTP operation. Similar to
END except the transfer did not complete. Can use this to e.g., delete a partially
written file.
The return value from this function depends on the in/out flag. For FTPDH_IN, the
function should return len if the data was processed successfully and download
should continue; -1 if an error has occurred and the transfer should be aborted. For
FTPDH_OUT, the function should return the actual number of bytes placed in the data
buffer, or -1 to abort. If zero is returned, then the upload is terminated normally. For
FTPDH_END, the return code should be zero for success or -1 for error. If an error is
flagged, then this is used as the return code for ftp_client_tick(). For
FTPDH_ABORT, the return code is ignored.
PARAMETERS
dhnd_data A pointer which is passed to the data handler function. This may
be used to point to any further data required by the data handler
such as an open file descriptor.
LIBRARY
FTP_CLIENT.LIB
SEE ALSO
ftp_client_setup
DESCRIPTION
Returns the most recent message code sent by the FTP server. RFC959 describes the
codes in detail. This function is most useful for error diagnosis in the case that an FTP
transfer failed.
RETURN VALUE
Error code; a number between 0 and 999. Codes less than 100 indicate that an internal
error occurred e.g., the server was never contacted.
LIBRARY
FTP_CLIENT.LIB
SEE ALSO
ftp_client_setup, ftp_client_tick
This chapter documents the FTP server. The following information is included:
• configuration macros
• the default file handlers
• how to assign replacement file handlers
• what to do when there is a firewall
• API functions
• commands accepted by the server
• reply codes generated by the server
• sample code demonstrating a working FTP server
The library FTP_SERVER.LIB implements the File Transfer Protocol for the server side of a
connection. FTP uses two TCP connections to transfer a file. The FTP server does a passive open
on well-known port 21 and then listens for a client. This is the command connection. The server
receives commands through this port and sends reply codes. The second TCP connection is for the
actual data transfer.
Anonymous FTP is supported. Most FTP servers on the Internet use the identifier “anonymous.”
So since FTP clients expect it, this is the identifier that is recommended. But any string (with a
maximum length of HTTP_NO_FLASHSPEC SSPEC_NO_STATIC) may be used.
Dynamic C 8 includes some enhancements that basically let the FTP server act as a full FTP
server, where you can create, read and delete files at will. To use these enhancements, the configu-
ration macro FTP_USE_FS2_HANDLERS must be defined to enable FS2 support in the default
file handler functions. The structure that holds the association of filenames and FS2 file locations
is the server spec list—the global array defined in zserver.lib. It is stored in the User block
and the API functions ftp_save_filenames() and ftp_load_filenames() are used
for support of this.
NOTE: For a demonstration of the enhanced FTP server, see the sample program,
/SAMPLES/TCPIP/FTP/FTP_SERVER_FULL.C.
FTP_CMDPORT
This macro defaults to 21 which is the well-known FTP server port number. You can
override this to cause the server to listen on a non-standard port number.
FTP_CREATE_MASK
This macro specifies the mask that is passed into the servermask parameter in
sspec_addfsfile() calls when a new file is created. In particular, this defines
which servers will be allowed to access this file. By default, it is defined to
SERVER_FTP | SERVER_WRITABLE .
FTP_DTPTIMEOUT
The default is 16, the same as FTP_TIMEOUT. This applies to the data transfer port
instead of the command port. The data transfer port is involved with get/store com-
mands, as well as directory listings.
FTP_EXTENSIONS
The macro is not defined by default. Define it to allow the server to recognize the
DELE, SIZE and MDTM commands. If this macro is defined, then the FTP handler
structure (FTPhandlers) is augmented with pointers to mdtm and delete handlers.
FTP_INTERFACE
This macro defaults to IF_DEFAULT, i.e., the (single) default interface. Define to
IF_ANY if FTP sessions can be accepted on any active interface, or a specific interface
number (e.g., IF_ETH0) to allow sessions on that interface only. Note that you are cur-
rently limited to a single interface, or all interfaces. This macro is only relevant starting
with Dynamic C version 7.30.
FTP_MAXLINE
The default is 256: the number of bytes of the working buffer in each server. This is
also the maximum size of each network read/write. The default value of 256 is the min-
imum value that allows the server to function properly.
FTP_MAXSERVERS
The default is 1: the number of simultaneous connections the FTP server can support.
Each server requires a significant amount of RAM (4096 bytes by default, though this
can change through SOCK_BUF_SIZE or tcp_MaxBufSize (deprecated)).
FTP_NODEFAULTHANDLERS
This macro is undefined. Define it to eliminate the code for the default file handlers.
You must then provide your own file handlers. This macro is no longer needed starting
with Dynamic C version 7.20.
FTP_USE_FS2_HANDLERS
Define this to enable the full use of FS2 in the default FTP handler functions. Defining
this macro will automatically define FTP_WRITABLE_FILES to 1, as well.
FTP_USERBLOCK_OFFSET
This macro should be defined to a number that specifies the offset into the User block
at which the list of filenames will be saved. This list correlates the filenames with the
locations of the files in the filesystem (FS2). This macro defaults to 0. If the user is
putting other information in the User block, this offset may need to be adjusted to pre-
vent clobbering the other data.
FTP_WRITABLE_FILES
The defaults is 0. Define to 1 to provide support in ftp_dflt_open() for authen-
ticating a user for write access before a file is opened. This also provides support in the
file listing function, ftp_dflt_list(), to show the write permission for writable
files.
NOTE: The user will need to override both the write and close default file handlers to
provide full support for writing a file.
SSPEC_NO_STATIC
This macro must be defined in any FTP server application compiled with
Dynamic C 8.50 or later.
Starting with Dynamic C 7.30, all FTP server instances share the same set of data handlers. Before
this release, there was a separate copy of the handler pointers for each instance of the server. This
change does not affect your existing application except to slightly reduce memory usage. This
change does add flexibility because it gives any file handler the ability to call any other file
handler. In particular, ftp_dflt_list() may now call ftp_dflt_getfilesize() to
get the file’s size
int ftp_dflt_open( char *name, int options, int uid, int cwd );
DESCRIPTION
Opens a file. If a file is successfully opened, the returned value is passed to subsequent
handler routines to identify the particular file or resource, as the 'fd' parameter. If nec-
essary, you can use this number to index an array of any other state information needed
to communicate with the other handlers. The number returned should be unique with
respect to all other open resource instances, so that your handler does not get confused
if multiple FTP data transfers are active simultaneously.
Note that the specified file to open may be an absolute or relative path: if the handler
supports the concept of directories, then it should handle the path name appropriately
and not just assume that the file is in the current directory. If the filename is relative,
then the cwd parameter indicates the current directory.
PARAMETERS
RETURN VALUE
≥0: File descriptor of the opened file.
FTP_ERR_NOTFOUND: File not found.
FTP_ERR_NOTAUTH: Unauthorized user.
FTP_ERR_BADMODE: Requested option (2nd parameter) is not supported.
FTP_ERR_UNAVAIL: Resource temporarily unavailable.
In the first case, the returned value is passed to subsequent handler routines to identify
the particular file or resource, as the 'fd' parameter. If necessary, you can use this num-
ber to index an array of any other state information needed to communicate with the
other handlers. The number returned should be unique with respect to all other open
resource instances, so that your handler does not get confused if multiple FTP data
transfers are active simultaneously. Note that the given file name may be an absolute
or relative path: if the handler supports the concept of directories, then it should handle
the path name as appropriate and not just assume that the file is in the current directory.
If the filename is "relative," then the cwd parameter indicates the current directory.
DESCRIPTION
Return the length of the specified file. This is called immediately after open for a read
file. If the file is of a known constant length, the correct length should be returned. If
the resource length is not known (perhaps it is generated on-the-fly) then return -1. For
write operations, the maximum permissible length should be returned, or -1 if not
known.
PARAMETERS
RETURN VALUE
≥0: The size of the file in bytes.
-1: The length of the file is not known.
int ftp_dflt_read( int fd, char *buf, long offset, int len );
DESCRIPTION
Read file identified by fd. The file contents at the specified offset should be stored into
buf, up to a maximum length of len. The return value should be the actual number of
bytes transferred, which may be less than len. If the return value is zero, this indicates
normal end-of-file. If the return value is negative, then the transfer is aborted. Each suc-
cessive call to this handler will have an increasing offset. If the getfilesize handler re-
turns a non-negative length, then the read handler will only be called for data up to that
length — there is no need for such read handlers to check for EOF since the server will
assume that only the specified amount of data is available.
The return value can also be greater than len. This is interpreted as "I have not put any-
thing in buf. Call me back when you (the server) can accept at least len bytes of da-
ta." This is useful for read handlers that find it inconvenient to retrieve data from
arbitrary offsets, for example a log reader that can only access whole log records. If the
returned value is greater than the server can ever offer, then the server aborts the data
transfer. The handler should never ask for more than FTP_MAXLINE bytes.
PARAMETERS
RETURN VALUE
0: EOF.
>0: The number of bytes read into buf.
-1: Error, transfer aborted.
int ftp_dflt_write( int fd, char *buf, long offset, int len );
DESCRIPTION
The default write handler does nothing but return zero.
The specification states that the handler may write the file identified by fd. buf con-
tains data of length len, which is to be written to the file at the given offset within the
file. The return value must be equal to len, or a negative number if an error occurs
(such as out of space).
The FTP server does not handle partial writes: the given data must be completely writ-
ten or not at all. If the return code is less than len, an error is assumed to have occurred.
Note that it is up to the handler to ensure that another FTP server is not accessing a file
which is opened for write. The open call for the other server should return
FTP_ERR_UNAVAIL if the current server is writing to a file.
PARAMETERS
RETURN VALUE
≥0: The number of bytes written. If this is less than len, an error occurred.
-1: Error.
DESCRIPTION
The default close handler does nothing but return zero.
The handler may close the specified file and free up any temporary resources associated
with the transfer.
PARAMETERS
RETURN VALUE
0
int ftp_dflt_list( int item, char *line, int listing, int uid,
int cwd );
DESCRIPTION
Returns the next file for the FTP server to list. The file name is formatted as a string.
PARAMETERS
item Index number starting at zero for the first function call. Subsequent
calls should be one plus the return value from the previous call.
RETURN VALUE
≥0: File descriptor for last file listed.
-1: Error.
DESCRIPTION
Change to new "directory." This is called when the client issues a CWD command. The
FTP server itself has no concept of what a directory is —this is meaningful only to the
handler.
PARAMETERS
dir String that indicates the new directory that will become the current
directory. The interpretation of this string is entirely up to the han-
dler. The dir string will be passed as ".." to move up one level.
RETURN VALUE
0: No such directory exists.
-1: Root directory.
>0: Anything that is meaningful to the handler.
DESCRIPTION
Print the current directory, passed as cwd, as a string. The result is placed in buf,
whose length may be assumed to be at least (FTP_MAXLINE-6). The return value is
ignored.
PARAMETERS
RETURN VALUE
The return value is ignored.
DESCRIPTION
This handler function is called when the server receives the FTP command MDTM. The
return value of this handler function is the number of seconds that have passed since
January 1, 1980. A return value of zero will cause the reply code 213 followed by a
space and then the value 19800101000000 (yyyymmddhhmmss) to be sent by the serv-
er.
The FTP server assumes that this return value is in UTC (Coordinated Universal Time).
If SEC_TIMER is running in local time, the handler should make the necessary time
zone adjustment so that the return value is expressed in UTC.
The handler is only recognized if FTP_EXTENSIONS is defined.
PARAMETERS
RETURN VALUE
The number of seconds that have passed since January 1, 1980. The default handler al-
ways returns zero. The number of seconds will be converted to a date and time value
of the form yyyymmddhhmmss.
DESCRIPTION
The default handler does not support the delete command. It simply returns the error
code for an unauthorized user.
The delete handler is only recognized by the server if FTP_EXTENSIONS is defined.
It is called when the DELE command is received. The given file name (possibly relative
to cwd) should be deleted.
PARAMETERS
RETURN VALUE
0: File was successfully deleted .
FTP_ERR_NOTFOUND: File not found.
FTP_ERR_NOTAUTH: Unauthorized user.
FTP_ERR_BADMODE: Requested option (2nd parameter) is not supported.
FTP_ERR_UNAVAIL: Resource temporarily unavailable.
ftp_dflt_is_auth
DESCRIPTION
Determine amount of access to a file. If the FTP anonymous user has been set, then also
checks that. "options" is how to access the file. Currently, this value is ignored. If the
anonymous user ID has been set, then files it owns are globally accessible.
Returns whether the user can access it ("owner permission") or if access is because
there is an anonymous user ("world permission").
NOTE: This routine only determines accessibility of a name, not whether the user can
read and/or write the contents.
PARAMETERS
RETURN VALUE
0: No access.
1: uid only access.
2: anonymous access (user "anonymous" has been set).
SEE ALSO
sspec_checkaccess
DESCRIPTION
Initializes the FTP server. You can optionally specify a set of handlers for controlling
what the server presents to the client. This is done with function pointers in the
FTPhandlers structure. All FTP server instances share the same list of handlers.
The FTPhandlers structure is defined as:
typedef struct {
int (*open)(char *name, int options, int uid, int cwd);
int (*read)(int fd, char *buf, long offset, int len);
int (*write)(int fd, char *buf, long offset, int len);
int (*close)(int fd);
long (*getfilesize)(int fd);
int (*dirlist)(int item, char *line, int listing, int
uid, int cwd);
int (*cd)(int cwd, char *dir, int uid);
int (*pwd)(int cwd, char *buf);
[long (*mdtm)(int fd);]
[int (*delete)(char *name, int uid, int cwd);]
} FTPhandlers;
If you always provide all your own handlers, then you can define
FTP_NODEFAULTHANDLER to eliminate the code for the default handlers. The han-
dlers must be written to the specification described in Section 6.2.2. To use a default
handler, leave the field NULL. If you pass a NULL handlers pointer, then the all default
handlers will be used.
The defaults access the server spec list which is set up using the zserver functions
sspec_addxmemfile(), sauth_adduser() etc.
PARAMETERS
handlers NULL means use default internal file handlers. Otherwise, you
must supply a struct of pointers to the various file handlers (open,
read, write, close, getfilesize, list). To not override a particular
handler, leave it NULL in the structure.
LIBRARY
FTP_SERVER.LIB
SEE ALSO
ftp_tick
int ftp_load_filenames(void)
DESCRIPTION
This function is used in conjunction with the FTP_USE_FS2_HANDLERS macro. It
loads the data structure (i.e., the server spec list) that keeps track of the association of
filenames to file locations in the file system. The information is loaded from the User
block, from the offset given in FTP_USERBLOCK_OFFSET.
The function removes any entries from the server spec list that are not FS2 files.
RETURN VALUE
0: Success
-1: Failure (possibly due to the filenames having not yet been saved)
SEE ALSO
ftp_save_filenames
int ftp_save_filenames(void);
DESCRIPTION
This function is used in conjunction with the FTP_USE_FS2_HANDLERS macro.
This function saves the data structure (i.e., the server spec list) that keeps track of the
association of filenames to file locations in the file system. The information is saved to
the User block, at the offset given in FTP_USERBLOCK_OFFSET.
RETURN VALUE
0: Success.
-1: Failure, the information could not be saved (due to a write error).
SEE ALSO
ftp_load_filenames
DESCRIPTION
Set the "anonymous" user ID. Resources belonging to this userID may be accessed by
any user. A typical use of this function would be
ftp_set_anonymous (sauth_adduser("anonymous", "",
SERVER_FTP));
which defines an "anonymous" login for the FTP server. This only applies to the FTP
server. The username "anonymous" is recommended, since most FTP clients use this
for hosts that have no account for the user.
PARAMETER
uid The user ID to use as the anonymous user. This should have been
defined using sauth_adduser(). Pass -1 to set no
anonymous user.
RETURN VALUE
Same as the uid parameter, except -1 if uid is invalid.
LIBRARY
FTP_SERVER.LIB
SEE ALSO
sauth_adduser
DESCRIPTION
Close and cancel all FTP connections. If the server is connected to a client, forces the
QUIT state. If the application has called tcp_reserveport(), then it must call
tcp_clearreserve(). For a graceful shutdown, the application must call
tcp_tick() a few more times.
After the FTP sockets close, the application must call ftp_init() to again start the
server running.
PARAMETER
RETURN VALUE
None
LIBRARY
FTP_SERVER.LIB
SEE ALSO
ftp_init
DESCRIPTION
Once ftp_init() has been called, ftp_tick() must be called periodically to
run the server. This function is non-blocking.
LIBRARY
FTP_SERVER.LIB
SEE ALSO
ftp_init
Possible
Command Description
Reply Codes
Possible
Command Description
Reply Codes
Password for the user name (sent in clear text). It is accepted only
PASS 230, 530
after USER returns code 331
Requests a passive open on a port that is not the default data port.
PASV The server responds with the host and port address on which it is 227, 452
listening.
Changes the data port from the default port to the port specified in
PORT the command’s argument. The argument is the concatenation of a 200
32-bit internet host address and a 16-bit TCP port address.
PWD Prints the working directory name. 257
Closes the control connection. If a data transfer is in progress, the
QUIT 221
connection will not be closed until it has completed.
Transfers a copy of the file specified in the pathname argument 150, 226,
RETR
from the server to the client. 425, 550
213, 250,
SIZE Returns the size of the specified file.
450, 550
Stores a file from the client onto the server. The file will be 150, 226, 250
STOR overwritten if it already exists at the specified pathname, or it will 425, 450,
be created if it does not exist. 452, 550
Confirms the supported structure of a file. Only file-structure is
STRU 200, 504
supported: a continuous stream of data bytes.
SYST Sends the string “RABBIT2000.” 215
Confirms the transfer type. The types IMAGE (binary), ASCII and
TYPE 200, 504
Local with 8-bit bytes are all supported and are treated the same.
USER User name to use for authentication. 331, 530
The text used for the reply codes, may be slightly different than what is shown here. It will be con-
text specific.
TFTP.LIB implements the Trivial File Transfer Protocol (TFTP). This standard protocol (inter-
net RFC783) is a lightweight protocol typically used to transfer bootstrap or configuration files
from a server to a client host, such as a diskless workstation. TFTP allows data to be sent in either
direction between client and server, using UDP as the underlying transport.
This library fully implements TFTP, but as a client only.
Compared with more capable protocols such as FTP, TFTP:
• has no security or authentication
• is not as fast because of the step-by-step protocol
• uses fewer machine resources.
Because of the lack of authentication, most TFTP servers restrict the set of accessible files to a
small number of configuration files in a single directory. For uploading files, servers are usually
configured to accept only certain file names that are writable by any user. If these restrictions are
acceptable, TFTP has the advantage of requiring very little 'footprint' in the client host.
7.1 BOOTP/DHCP
In conjunction with DHCP/BOOTP and appropriate server configuration, TFTP is often used to
download a kernel image to a diskless host. The target TCP/IP board does not currently support
loading the BIOS in this way, since the BIOS and application program are written to non-volatile
flash memory. However, the downloaded file does not have to be a binary executable - it can be
any reasonably small file, such as an application configuration file. TFTP and DHCP/BOOTP can
thus be used to administer the configuration of multiple targets from a central server.
Using TFTP with BOOTP/DHCP requires minimal additional effort for the programmer. Just
#define the symbol DHCP_USE_TFTP to an integer representing the maximum allowable boot
file size (1-65535). See the description of the variables _bootpsize, _bootpdata and
_bootperror in volume 1 of the TCP/IP User’s Manual for further details.
// Following fields not used after initial request has been acknowledged.
char mode; // Translation mode (see below).
char file[129]; // File name on remote host (TFTP server)
// - NULL terminated. This field will be
// overwritten with a NULL-term error message
// from the server if an error occurs.
};
TFTP Session
A session can be either a single download (get) or upload (put). The functions ending with 'x' are
versions that use a data structure allocated in extended memory, for applications that are con-
strained in their use of root data memory.
DESCRIPTION
This function prepares for a TFTP session and is called to complete initialization of the
TFTP state structure. Before calling this function, some fields in the structure
tftp_state must be set up as follows:
ts->state =
<0 for read, 1 for write>
ts->buf_addr =
<physical address of xmem buffer>
ts->buf_len =
<length of physical buffer, 0-65535>
ts->my_tid =
<UDP port number. Set 0 for default>
ts->sock =
<address of UDP socket (udp_Socket *),or NULL to
use DHCP/BOOTP socket>
ts->rem_ip = <IP address of TFTP server host, or zero to use
default BOOTP host>
ts->mode = <one of the following constants:
TFTP_MODE_NETASCII (ASCII text)
TFTP_MODE_OCTET (8-bit binary)
TFTP_MODE_MAIL (Mail)>
strcpy(ts->file, <remote filename or mail address>)
Note that mail mode can only be used to write mail to the TFTP server, and the file name
is the e-mail address of the recipient. The e-mail message must be ASCII-encoded and
formatted with RFC822 headers. Sending e-mail via TFTP is deprecated. Use SMTP in-
stead since TFTP servers may not implement mail.
PARAMETERS
ts Pointer to tftp_state.
RETURN VALUE
0: OK.
-4: Error, default socket in use.
LIBRARY
TFTP.LIB
DESCRIPTION
This function is called to complete initialization of the TFTP state structure, where the
structure is possibly stored somewhere other than in the root data space. This is a wrapper
function for tftp_init(). See that function description for details.
PARAMETERS
RETURN VALUE
0: OK
-1: Error, default socket in use
LIBRARY
TFTP.LIB
DESCRIPTION
This function is called periodically in order to take the next step in a TFTP process. Ap-
propriate use of this function allows single or multiple transfers to occur without block-
ing. For multiple concurrent transfers, there must be a unique tftp_state structure,
and a unique UDP socket, for each transfer in progress. This function calls
sock_tick().
PARAMETERS
RETURN VALUE
1: OK, transfer not yet complete.
0: OK, transfer complete
-1: Error from remote side, transfer terminated. In this case, the ts_addr->file field
will be overwritten with a NULL-terminated error message from the server.
-2: Error, could not contact remote host or lost contact.
-3: Timed out, transfer terminated.
-4: (not used)
-5: Transfer complete, but truncated -- buffer too small to receive the complete file.
LIBRARY
TFTP.LIB
DESCRIPTION
This function is a wrapper for calling tftp_tick(), where the structure is possibly
stored somewhere other than in the root data space. See that function description for de-
tails.
PARAMETERS
RETURN VALUE
1: OK, transfer not yet complete.
0: OK, transfer complete
-1: Error from remote side, transfer terminated. In this case, the ts_addr->file field
will be overwritten with a NULL-terminated error message from the server.
-2: Error, could not contact remote host or lost contact.
-3: Timed out, transfer terminated.
-4: (not used)
-5: Transfer complete, but truncated -- buffer too small to receive the complete file.
LIBRARY
TFTP.LIB
int tftp_exec( char put, long buf_addr, word *len, int mode,
char *host, char *hostfile, udp_Socket *sock );
DESCRIPTION
Prepare and execute a complete TFTP session, blocking until complete.This function is a wrapper
for tftp_init() and tftp_tick(). It does not return until the complete file is transferred or
an error occurs. Note that approximately 750 bytes of free stack will be required by this function.
PARAMETERS
len Length of data buffer. This is both an input and a return parameter.
It should be initialized to the buffer length. On return, it will be set
to the actual length received (for a get), or unchanged (for a put).
RETURN VALUE
0: OK, transfer complete.
-1: Error from remote side, transfer terminated. In this case, ts_addr->file
will be overwritten with a NULL-terminated error message from the server.
-2: Error, could not contact remote host or lost contact.
-3: Timed out, transfer terminated
-4: sock parameter was NULL, but BOOTP socket was unavailable.
LIBRARY
TFTP.LIB
SMTP (Simple Mail Transfer Protocol) is one of the most common ways of sending e-mail. SMTP
is a simple text conversation across a TCP/IP connection. The SMTP server usually resides on
TCP port 25 waiting for clients to connect. (Define SMTP_PORT to override the default port num-
ber.)
Sending mail with the Dynamic C SMTP client library is a simple process, demonstrated in the
sample program shown in Section 8.3. Dynamic C 9 introduced SMTP authentication, described
below in Section 8.2.
test mail
.
250 Mail accepted
QUIT
221 mail.somehost.com QUIT
You can see a listing of the conversation between your controller and the mail server by defining
the SMTP_DEBUG macro at the top of your program. Note that there must be a blank line after the
line “Subject: test mail.”
AUTH PLAIN
The client sends "AUTH PLAIN <token>" where <token> is the Base64-encoded string
"username\0username\0password” that will look something like:
AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz
The server responds with a message indicating whether authentication was successful.
AUTH LOGIN
Client sends "AUTH LOGIN" command; server responds with "334 VXNlcm5hbWU6"
(Base64-encoded "Username:"); client responds with its Base64-encoded username;
server responds with "334 UGFzc3dvcmQ6"; client responds with its Base64-encoded
password.
At this point, the server should respond with a message indicating whether authentication
was successful.
This method is only slightly more complex than AUTH PLAIN.
AUTH CRAM-MD5
Client sends "AUTH CRAM-MD5"; server responds with "334 <challenge>" where
<challenge> is a unique Base64-encoded challenge string (for example,
"<[email protected]>").
The client generates a digest using the following MD5 hashing algorithm (where pass-
word is null-padded to a length of 64 bytes, ipad is 0x36 repeated 64 times and opad is
0x5C repeated 64 times):
digest = MD5((password XOR opad), MD5((password XOR
ipad), challenge))
The client responds with the string "<username> <response>" Base64-encoded; <user-
name> is in plaintext, and <response> is the 16-byte digest in hex form.
This method is the most secure, since someone sniffing the connection would be unable
to determine the cleartext password used to authenticate.
SMTP_DEBUG
This macro tells the SMTP code to log events to the STDIO window in Dynamic C. This
provides a convenient way of troubleshooting an e-mail problem.
SMTP_DOMAIN
This macro defines the text to be sent with the HELO client command. Many mail servers
ignore the information supplied with the HELO, but some e-mail servers require the fully
qualified name in this field (i.e., somemachine.somedomain.com). If you have problems
with e-mail being rejected by the server, turn on SMTP_DEBUG. If it is giving an error
message after the HELO line, talk to the administer of the machine for the appropriate
value to place in SMTP_DOMAIN. If you do not define this macro, it will default to
MY_IP_ADDRESS.
#define SMTP_DOMAIN "somemachine.somedomain.com"
SMTP_MAX_DATALEN
Defaults to 256. Maximum buffer size for server responses and short client requests.
SMTP_MAX_PASSWORDLEN
Defaults to 16. Maximum length of the password used in authentication.
SMTP_MAX_USERNAMELEN
Defaults to 64. Maximum length of the user name used in authentication.
SMTP_MAX_SERVERLEN
Defaults to MAX_STRING, which defaults to 50. Maximum length of mail server name.
SMTP_SERVER
This macro defines the mail server that will relay the controller’s mail. This server must
be configured to relay mail for your controller. You can either place a fully qualified do-
main name or an IP address in this field.
#define SMTP_SERVER "mail.mydomain.com"
or
#define SMTP_SERVER "10.10.6.19"
SMTP_TIMEOUT
This macro tells the SMTP code how long in seconds to try to send the e-mail before tim-
ing out. It defaults to 20 seconds.
#define SMTP_TIMEOUT 10
USE_SMTP_AUTH
Define this macro to enable SMTP authentication.
smtp_data_handler
DESCRIPTION
Sets a data handler for generating mail message content. This function should be called
after calling smtp_sendmail() etc. It overrides any message parameter set by the
smtp_sendmail() call, since the message is generated dynamically by the callback
function.
Note: you can use the same data handler as used for the FTP library (see the
ftp_data_handler() description). The flags values are numerically equivalent to
those of the same meaning for ftp_data_handler(). The SMTP data handler is
only used to generate data, not receive it.
The handler is a function that must be coded according to the following prototype:
int my_handler(char *data, int len, longword offset,
int flags, void *dhnd_data);
The data handler function must be called with the following parameters:
len The length of the above data buffer. This parameter is set to
SMTP_MAX_DATALEN (256) by default. You can override that
macro to allow larger "chunks".
offset The byte number relative to the first byte of the entire message
stream. This is useful for data handler functions that do not wish to
keep track of the current state of the data source.
dhnd_data A pointer that is passed to the data handler function. This may be
used to point to any further data required by the data handler such as
an open file descriptor.
RETURN VALUE
The return value from this function should be the actual number of bytes placed in the
data buffer, or -1 to abort. If 0 is returned, then this is considered to be the end of data.
You can write up to and including "len" bytes into the buffer, but at least one byte must
be written otherwise it is assumed that no more data is following.
For SMTPDH_ABORT, the return code is ignored.
SEE ALSO
smtp_sendmail, smtp_sendmailxmem, smtp_mailtick
EXAMPLE
The program Samples/tcpip/smtp/smtp_dh.c makes use of this function.
DESCRIPTION
Repetitively call this function until e-mail is completely sent.
RETURN VALUE
SMTP_SUCCESS - e-mail sent.
SMTP_PENDING - e-mail not sent yet call smtp_mailtick again.
SMTP_TIME - e-mail not sent within SMTP_TIMEOUT seconds.
SMTP_UNEXPECTED - received an invalid response from SMTP server.
SMTP_DNSERROR - cannot resolve server name
SMTP_ABORTED - transaction aborted (by data handler)
If using SMTP AUTH, the following values are also possible:
SMTP_AUTH_UNAVAILABLE - unable to attempt authentication|
SMTP_AUTH_FAILED - attempts to authenticate failed
LIBRARY
SMTP.LIB
SEE ALSO
smtp_sendmail, smtp_status
DESCRIPTION
Start an e-mail being sent. This function is intended to be used for short messages that are
entirely constructed prior to being sent.
If you have previously installed a data handler via smtp_data_handler(), then
you must call smtp_data_handler() with a NULL data handler, otherwise this
message will not get sent.
NOTE: The strings pointed to by the parameters must not be changed until the entire
process is completed. Also, if the first character of any line of the message is a period
(.), then this character will be deleted as part of normal mail processing. Thus, to actu-
ally send a line starting with '.', you must start the line with '..' i.e. double up an initial
period.
PARAMETERS
from String containing the e-mail address of the source. Maximum of 192
characters for a return address. If no return should be sent by receiv-
er, then pass an empty string ("").
subject String containing the subject of the message. This may be NULL in
which case no subject line will be sent. This string may also contain
embedded \r\n sequences so that additional mail header lines may be
inserted. The length of this string is unlimited.
message String containing the message. (This string must not contain the
byte sequence "\r\n.\r\n" (CRLF.CRLF), as this is used to mark the
end of the e-mail, and will be appended to the e-mail automatically.)
This message must be null terminated, and is only allowed to con-
tain 7-bit characters. You can pass NULL if a data handler is to be
used to generate the message.
RETURN VALUE
None.
SEE ALSO
smtp_mailtick, smtp_status, smtp_sendmailxmem
DESCRIPTION
Start an e-mail being sent. This is intended for moderately long, fixed messages that are
stored in extended memory (e.g., via #ximport'ed file).
See smtp_sendmail() for more details.
PARAMETERS
RETURN VALUE
None
LIBRARY
SMTP.LIB
SEE ALSO
smtp_mailtick, smtp_status, smtp_sendmail
DESCRIPTION
Sets the username and password to use for SMTP AUTH (Authentication). You must
#define USE_SMTP_AUTH in your program if you want to use SMTP AUTH on your
outbound connections. To disable SMTP authentication, set both username and
password to “” (empty strings).
PARAMETERS
username This is copied into the SMTP state structure. Note that some SMTP
servers require a full email address while others just want a user-
name.
RETURN VALUE
SMTP_OK: server name was set successfully
SMTP_USERNAMETOOLONG: the username was too long
SMTP_PASSWORDTOOLONG: the username was too long
SEE ALSO
smtp_sendmail, smtp_mailtick
DESCRIPTION
Sets the SMTP server. This value overrides SMTP_SERVER and the results of any pre-
vious call to smtp_setserver_ip().
PARAMETER
server Server name string. This is copied into the SMTP state structure.
This name is not resolved to an IP address until you start calling
smtp_mailtick().
RETURN VALUE
SMTP_OK: Server name was set successfully
SMTP_NAMETOOLONG: The server name was too long
SEE ALSO
smtp_sendmail, smtp_setserver_ip, smtp_mailtick
smtp_setserver_ip
DESCRIPTION
Sets the SMTP server. This value overrides the value set by smtp_setserver(), and
is used when the IP address of the mail server is known.
PARAMETER
RETURN VALUE
SMTP_OK: server IP was set successfully
SEE ALSO
smtp_sendmail, smtp_setserver, smtp_mailtick
DESCRIPTION
Return the status of the last e-mail processed.
RETURN VALUE
SMTP_SUCCESS - e-mail sent.
SMTP_PENDING - e-mail not sent yet call smtp_mailtick again.
SMTP_TIME - e-mail not sent within SMTP_TIMEOUT seconds.
SMTP_UNEXPECTED - received an invalid response from SMTP server.
LIBRARY
SMTP.LIB
Post Office Protocol version 3 (POP3) is probably the most common way of retrieving e-mail
from a remote server. Most e-mail programs, such as Eudora, MS-Outlook, and Netscape’s e-mail
client, use POP3. The protocol is a fairly simple text-based chat across a TCP socket, normally
using TCP port 110.
There are two ways of using POP3.LIB. The first method provides a raw dump of the incoming
e-mail. This includes all of the header information that is sent with the e-mail, which, while some-
times useful, may be more information than is needed. The second method provides a parsed ver-
sion of the e-mail, with the sender, recipient, subject line, and body text separated out.
In both methods, each line of e-mail has CRLF stripped from it and ‘\0’ appended to it.
9.1 Configuration
The POP3 client can be configured through the following macros:
POP_BUFFER_SIZE
This will set the buffer size for POP_PARSE_EXTRA in bytes. These are the buffers that
hold the sender, recipient and subject of the e-mail. POP_BUFFER_SIZE defaults to 64
bytes.
POP_DEBUG
This will turn on debug information. It will show the actual conversation between the de-
vice and the remote mail server, as well as other useful information.
POP_NODELETE
This will stop the POP3 library from removing messages from the remote server as they
are read. By default, the messages are deleted to save storage space on the remote mail
server.
POP_PARSE_EXTRA
This will enable the second mode, creating a parsed version of the e-mail as mentioned
above. The POP3 library parses the incoming mail more fully to provide the Sender, Re-
cipient, Subject, and Body fields as separate items to the call-back function.
pop3_init
DESCRIPTION
This function must be called before any other POP3 function is called. It will set the call-
back function where the incoming e-mail will be passed to. This probably should only be
called once.
PARAMETERS
RETURN VALUE
0: Success.
1: Failure.
LIBRARY
POP3.LIB
DESCRIPTION
This function will initiate receiving e-mail (a POP3 request to a remote e-mail server).
IMPORTANT NOTE - the buffers for username and password must NOT change
until pop3_tick() returns something besides POP_PENDING. These values are not
saved internally, and depend on the buffers not changing.
PARAMETERS
RETURN VALUE
0: Success.
1: Failure.
LIBRARY
POP3.LIB
int pop3_tick(void)
DESCRIPTION
A standard tick function, to run the daemon. Continue to call it as long as it returns
POP_PENDING.
RETURN VALUE
POP_PENDING: Transfer is not done; call pop3_tick again.
POP_SUCCESS: All e-mails were received successfully.
POP_ERROR: Unknown error occurred.
POP_TIME: Session timed-out. Try again, or use POP_TIMEOUT to increase the time-
out length.
LIBRARY
POP3.LIB
10.1.1 Setup
To use a serial port, the circular buffers must be initialized. For instance, if serial port A is used by
an application, then the following macros must be defined in the program:
#define AINBUFSIZE 31
#define AOUTBUFSIZE 31
The parameter passed to VSERIAL_PORTA is the unique gateway identifier mentioned earlier.
This value is chosen by the developer when entries are made to the array of type VSerialSpec
(also known as the spec table).
VSERIAL_DEBUG
Turns on debug messages.
VSERIAL_NUM_GATEWAYS
The number of telnet sessions must be defined and must match the number of entries in
the spec table.
vserial_close
DESCRIPTION
Closes the specified gateway. This will not only terminate any network activity, but will
also close the serial port.
PARAMETERS
RETURN VALUE
0: Success.
1: Failure.
LIBRARY
VSERIAL.LIB
vserial_init
DESCRIPTION
Initializes the daemon and parses the spec table.
RETURN VALUE
0: Success;
1: Failure.
LIBRARY
VSERIAL.LIB
DESCRIPTION
This function sets the keepalive timer to generate TCP keepalives after timeout pe-
riods of inactivity. This helps detect if the connection has gone bad.
Keepalives should be used at the application level, but if that is not possible, then
timeout should be set so as to not overload the network. The standard timeout is two
hours, and should be set sooner than that only for a Very Good Reason.
PARAMETERS
RETURN VALUE
0: Success.
1: Failure.
LIBRARY
VSERIAL.LIB
DESCRIPTION
Listens on the specified port for a telnet connection. The gateway process is started
when a connection request is received. On disconnect, re-listen happens automatically.
PARAMETERS
baud The parameter to send to the open() serial port command; it’s usu-
ally the baud rate.
flags Option flags for this gateway. Currently the only valid bit flags are
VSERIAL_COOKED to strip out telnet control codes, or 0 to leave
it a raw data link.
RETURN VALUE
0: Success.
1: Failure.
LIBRARY
VSERIAL.LIB
int vserial_open( int id, long baud, int port, long remote_host,
int flags, long retry );
DESCRIPTION
Opens a connection to a remote host and maintains it, starting the gateway process.
PARAMETERS
baud The parameter to send to the open() serial port command; it’s usu-
ally the baud rate.
flags Option flags for this gateway. Currently the only valid bit flags are
VSERIAL_COOKED to strip out telnet control codes, or 0 to leave
it a raw data link.
RETURN VALUE
0: Success.
1: Failure.
LIBRARY
VSERIAL.LIB
DESCRIPTION
Runs the telnet daemon - must be called periodically.
RETURN VALUE
0: Success;
1: Failure.
But call it periodically no matter the return value! An error message can be seen when
1 is returned if you define VSERIAL_DEBUG at the top of your program.
LIBRARY
VSERIAL.LIB
SERIAL_PORT_SPEED
The baud rate of the serial port. Defaults to 115,200 bps.
TELNET_COOKED
#define this to have telnet control codes stripped out of the data stream.
This is useful if you are actually telneting to the device from another box. It should not
be defined if you are using two devices as a transparent bridge over the Ethernet.
telnet_init
DESCRIPTION
Initializes the connection. This function must not be called by an application program
starting with Dynamic C 7.05.
PARAMETERS
which Is one of the following:
TELNET_LISTEN—Listens on a port for incoming connections.
TELNET_RECONNECT—Connects to a remote host, and recon-
nects if the connection dies.
TELNET_CONNECT—Connects to a remote host, and terminates if
the connection dies.
addy IP address of the remote host, or 0 if we are listening.
port Port to bind to if we are listening, or the port of the remote host to
connect to.
RETURN VALUE
0: Success.
1: Failure.
LIBRARY
VSERIAL.LIB
DESCRIPTION
Must be called periodically to run the daemon.
RETURN VALUE
0: Success (call it again);
1: Failure; TELNET_CONNECT died, or a fatal error occurred.
LIBRARY
VSERIAL.LIB
telnet_close
DESCRIPTION
Terminates any connections currently open, and shuts down the daemon.
LIBRARY
VSERIAL.LIB
The library, zconsole.lib, implements a serial-based console that we call Zconsole. It can be
used to:
• Configure a board.
• Upload and download web pages.
• Change web page variables without re-uploading the page.
• Send e-mail.
• Calls subsystem initialization for ARP, TCP, UDP and DNS (if applicable).
command
This field is a string like the following: “SET MAIL FROM.” That is, each word of the
command is separated by a space. The case of the command does not matter. Entering
this string is how the command is invoked.
cmdfunc
This field is a function pointer to the function that implements the command. The func-
tions that come with Zconsole are listed in Section 11.4.1.1 on page 345.
helptext
This field points to a text file. The text file contains help information for the associated
command. When HELP COMMAND is entered, this text file (the help information for
COMMAND) will be printed to Zconsole. The help text comes from #ximported text
files.
con_add_nameserver()
This function adds a name server to the list of name servers (unlike con_set_nameserver()
that clears the list of name servers and adds one name server). A command that use this function
takes one parameter: the IP address of the name server in dotted quad notation.
con_createv()
This function creates a variable that can be used with SSI commands in SHTML files. Certain SSI
commands can be replaced by the value of this variable, so that a web page can be dynamically
altered without re-uploading the entire page. Note, however, that the value of the variable is not
preserved across power cycles, although the variable entry is still preserved. That is, the value of
the variable may change after a power cycle. It can be changed again, though, with a putv com-
mand. It works in the following fashion (if the command is called “CREATEV”):
usage: "createv <varname> <vartype> <format> <value> [strlen]"
A web variable that can be referenced within web files is created.
<varname> is the name of the variable
<vartype> is the type of the variable (INT8, INT16, INT32, FLOAT32, or STRING)
<format> is the printf-style format specifier for outputting the variable (such as "%d")
<value> is the value to assign the variable.
[strlen] is only used if the variable is of type STRING. It is used to give the maximum
length of the string.
con_delete()
This function deletes a file from the file system. A command that uses this function takes one
parameter: the name of the file to delete.
con_echo()
This function turns on or off the echoing of characters on a particular I/O stream. That is, it does
not affect echoing globally, but only for the I/O stream on which it is issued. A command that uses
this function takes one parameter: ON | OFF.
con_getv()
This function displays the value of the given variable. The variable is displayed using the printf-
style format specifier given in the createv command. A command that uses this function takes
one parameter: the name of the variable.
con_help()
This function implements the help system for Zconsole. A command that uses this function takes
one parameter: the name of another command. Zconsole outputs the associated help text for the
requested command. The help text is the text file referenced in the third field of the Console-
Command structure.
con_list_files()
This function lists the files in the file system and their file sizes. A command that uses this func-
tion takes no parameters.
con_list_variables()
This function displays the names and types of all variables. A command that uses this function
takes no parameters.
con_loginname()
This function stores an identifier that will be remembered across power cycles (with battery-
backed RAM). The existence of the identifier will be used to prompt the user of a new console ses-
sion. Before console access to the controller is allowed, a valid identifier must be entered in
response to the prompt. A command that uses this function takes one parameter: an identifier that
will be used as the login name.
If no identifier is stored for the password, a <CR> must be sent in response to the prompt for the
old password.
con_logout()
This function exits the current console session and begins a new session by entering the initializa-
tion state of Zconsole. A command that uses this function takes no parameters.
con_mail()
This function sends e-mail to the server specified by con_mail_server(), with the return
address specified by set_mail_from(). A command that uses this function takes one parame-
ter: the destination e-mail address. If the command is named mail, the usage is:
"mail [email protected]"
The first line of the message will be used as the subject, and the other lines are the body. The body
is terminated with a ^D or ^Z (0x04 or 0x1A).
con_putv()
This function updates the value of a variable. A command that uses this function takes two param-
eters: the name of the variable, and the new value for the variable.
con_reset_files()
This function removes all web files.
con_reset_variables()
This function removes all web variables.
con_set_dhcp()
This function turns DHCP configuration for an interface "on" or "off." Currently this command
only works with the default interface. After DHCP has been turned on, ZConsole will undertake
reacquiring the lease should it be dropped. (For example, a lease might be dropped if the DHCP
server is unavailable for an extended period of time.)
con_set_gateway()
This function changes the gateway of the board. A command that uses this function takes one
parameter: the new gateway in dotted quad notation, e.g., 192.168.1.1.
con_set_icmp_config()
This function configures an interface to use directed ICMP echo request (ping) packets for config-
uration. A command that uses this function takes two parameters. The first is "on" or "off" to turn
this feature on or off. The second parameter is optional, and specifies the intended interface
(ETH0 or ETH1). Only non-PPPoE Ethernet may be used for ping configuration.
con_set_icmp_config_reset()
Normally, when an interface has been configured via a directed ping packet, further configuration
via a directed ping packet is disabled (until the next power cycle). This function allows the inter-
face to be configured via a ping packet again. A command that uses this function takes an optional
interface argument (ETH0 or ETH1).
con_set_ip()
This function changes the IP address of the board. A command that uses this function takes one
parameter: the new IP address in dotted quad notation, e.g., 192.168.1.112.
con_set_mail_from()
This function sets the return address for all e-mail messages. This address will be added to the out-
going e-mail and should be valid in case the e-mail needs to be returned. A command that uses this
function takes one parameter: the return address.
con_set_mail_server()
This functions identifies the SMTP server to use. A command that uses this function takes one
parameter: the IP address of the SMTP server.
con_set_nameserver()
This function changes the name server for the board. A command that uses this function takes one
parameter: the IP address of the new name server in dotted quad notation, e.g., 192.168.1.1.
con_set_netmask()
This function changes the netmask of the board. A command that uses this function takes one
parameter: the new netmask in dotted quad notation, e.g., 255.255.255.0.
con_set_tcpip_debug()
This function is intended to aid in development and debugging. A command that uses this function
takes one parameter: the numerical level of debugging messages. The higher the number, the more
verbose the TCP/IP debugging messages will be.
con_show()
This function displays the current configuration of the board (IP address, netmask, and gateway).
If the developer’s application has configuration options she would like to show other than the IP
address, netmask, and gateway, she will probably want to implement her own version of the show
command. The new show command can be modelled after con_show() in ZConsole.lib. A
command that uses this function takes no parameters.
con_show_multi()
Like the con_show() function, this function shows the current console configuration. This com-
mand will, however, show more network configuration than is available via con_show().
Interface-specific configuration information is separated out. A command that uses this function
takes an optional parameter (ETH0, ETH1, PPP0, PPP1, PPP2, etc.) to display the interface spe-
cific configuration for the specified interface. If the optional parameter is missing, the current con-
sole configuration for all valid interfaces is displayed.
The parameter passed to the function is a structure of type ConsoleState. Some of the fields in
this structure must be manipulated by your custom command function, other fields are used by
Zconsole.lib and must not be changed by the your program.
typedef struct {
int console_number;
ConsoleIO *conio;
int state;
int laststate;
char command[CON_CMD_SIZE];
char *cmdptr;
char buffer[CON_BUF_SIZE]; // Use for reading in data.
char *bufferend; // Use for reading in data.
ConsoleCommand *cmdspec;
int sawcr;
int sawesc;
int echo; // Check if echo is enabled, or change it.
int substate;
unsigned int error;
int numparams; // Number of parameters on command line.
int commandparams; // Number of commands issued on cmd line
char cmddata[CON_CMD_DATA_SIZE];
#ifndef CON_NO_FS_SUPPORT // File processing not needed with DC 7.30
FileNumber filenum; // Use for file processing.
File file; // Use for file processing.
#endif
int spec; // Use for working with Zserver entities
long timeout; // Use for extending the time out.
} ConsoleState;
#endif
To accomplish its tasks, the function should use state->substate for its state machine
(which is initialized to zero before dispatching the command handler), and state->command to
read out the command buffer (to get other parameters to the command, for instance). In case of
error, the function should set state->error to the appropriate value.
The buffer at state->cmddata is available for the command to preserve data across invoca-
tions of the command’s state machine. The size of the buffer is adjustable via the
CON_CMD_DATA_SIZE macro (set to 16 bytes by default). Generally this buffer area will be cast
into a data structure appropriate for the given command state machine.
IMPORTANT: The fields discussed in the previous paragraph and the fields that
have comments in the structure definition are the only ones that an application
program should change. The other fields must not be changed.
11.5.2.2 Telnet
Zconsole runs a telnet server. The port number is passed to the macro CONSOLE_IO_TELNET.
The user telnets to the controller that is running the console.
The slave port has 256 channels, separate port addresses that are independent of one another. A
handler function for each channel that is used must be provided. For details on how to do this,
please see the Dynamic C User’s Manual.
A stream-based handler, SPShandler(), to process Zconsole commands for the slave is pro-
vided in SP_STREAM.LIB. The handler is set up automatically by the console when the slave
port I/O method is included. The macro, CONSOLE_IO_SP, expands to the I/O functions defined
in SP_STREAM.LIB.
the application program must initialize the file system with a call to fs_init(). Starting with
Dynamic C 7.30 none of this is necessary because Zconsole saves configuration information to the
User block. See the Rabbit 2000 Microprocessor User’s Manual or the Rabbit 3000 Microproces-
sor User’s Manual for more information about the User block.
In general, these buffers can be smaller for slower baud rates, but must be larger for faster baud
rates.
console_init
DESCRIPTION
This function will initialize Zconsole data structures. It must be called before
console_tick() is called for the first time. This function also loads the configura-
tion information from the file system.
RETURN VALUE
0: Success;
1: No configuration information found.
<0: Indicates an error loading the configuration data;
-1 indicates an error reading the 1st set of information,
-2 the 2nd set, and so on.
LIBRARY
zconsole.lib
console_tick
DESCRIPTION
This function needs to be called periodically in an application program to allow Zconsole
time for processing.
LIBRARY
zconsole.lib
con_backup
DESCRIPTION
This function backs up the current configuration.
RETURN VALUE
0: Success
1: Failure
LIBRARY
zconsole.lib
SEE ALSO
con_backup_reserve, con_load_backup
con_backup_bytes
DESCRIPTION
Returns the number of bytes necessary for each backup configuration file. Note that
enough space for two of these files needs to be reserved. This function is most useful
when ZCONSOLE.LIB is being used with FS2.LIB.
RETURN VALUE
Number of bytes needed for a backup configuration file.
LIBRARY
zconsole.lib
SEE ALSO
con_backup_reserve
DESCRIPTION
Reserves space for the configuration information in the file system. For more information
on the file system see the Dynamic C User’s Manual.
LIBRARY
zconsole.lib
SEE ALSO
con_backup, con_load_backup, con_backup_bytes
con_chk_timeout
DESCRIPTION
Checks whether the given timeout value has passed.
RETURN VALUE
0: Timeout has not passed
!0: Timeout has passed
LIBRARY
zconsole.lib
SEE ALSO
con_set_timeout
DESCRIPTION
Loads the configuration from the file system.
RETURN VALUE
0: Success
1: No configuration information found
<0: Failure
-1: error reading 1st set of information
-2: error reading 2nd set of information, and so on
LIBRARY
zconsole.lib
SEE ALSO
con_backup, con_backup_reserve
con_reset_io
DESCRIPTION
Resets all I/O methods by calling close() and open() on each of them.
LIBRARY
zconsole.lib
DESCRIPTION
Sets the logical extent (LX) that will be used to store the backup configuration data. For more
information on the file system see the Dynamic C User’s Manual. This is only useful in conjunc-
tion with FS2.LIB. This should be called once before console_init(). Care should be
taken that enough space is available in this logical extent for the configuration files. See
con_backup_bytes() for more information.
PARAMETER
LIBRARY
zconsole.lib
SEE ALSO
con_set_files_lx, con_backup_bytes
con_set_files_lx
DESCRIPTION
Sets the logical extent (LX) that will be used to store files. For more information on the
file system see the Dynamic C User’s Manual. This is only useful in conjunction with
FS2.LIB. This should be called once before console_init().
PARAMETER
LIBRARY
zconsole.lib
SEE ALSO
con_set_backup_lx
DESCRIPTION
Sets a user-defined function that will be called when the console (for a particular I/O
channel) is idle. The user-defined function should take an argument of type
ConsoleState* .
LIBRARY
zconsole.lib
SEE ALSO
con_set_user_timeout
con_set_timeout
DESCRIPTION
Returns the value that MS_TIMER should have when the number of seconds given have
elapsed.
LIBRARY
zconsole.lib
SEE ALSO
con_chk_timeout
DESCRIPTION
Sets a user-defined function that will be called when a timeout event has occurred. The
user-defined function should take an argument of type ConsoleState*.
LIBRARY
zconsole.lib
SEE ALSO
con_set_user_idle
console_disable
DESCRIPTION
Disable processing for the designated console in the console_io[] array. This func-
tion, along with console_enable(), allows the sharing of the Zconsole port with
some other processing.
PARAMETER
LIBRARY
zconsole.lib
SEE ALSO
console_init, console_enable
DESCRIPTION
Enable processing for the designated console in the console_io[] array. This func-
tion, along with console_disable(), allows the sharing of the Zconsole port with
some other processing.
PARAMETER
LIBRARY
zconsole.lib
SEE ALSO
console_init, console_disable
http://hp.vector.co.jp/authors/VA002416/teraterm.html
data
This is a pointer to the data to be backed up.
len
This is how many bytes of data need to be backed up.
postload
This is a function pointer to a function that is called after configuration data is loaded, in case the
developer needs to do something with the newly loaded configuration data.
presave
This is a function pointer that is called just before the configuration data is saved so that the devel-
oper can fill in the data structure to be saved. The functions referenced by postload() and
presave() should have the following prototype:
void my_preload(void *dataptr);
The dataptr parameter is the address of the configuration data (the same as the data pointer in
the ConsoleBackup structure).
CONSOLE_BASIC_BACKUP
Causes backup of the echo state (on or off), baud rate and port number information.
CONSOLE_TCPIP_BACKUP
Causes backup of the IP addresses of the controller board and the IP address of its net-
mask, gateway and name server.
Note that only one of the CONSOLE_TCP_* structures should be used.
CONSOLE_TCP_MULTI_BACKUP
Using this structure causes ifconfig() to save and restore network configuration. In
addition to the information saved by CONSOLE_TCP_BACKUP, multiple name servers,
DHCP configuration, ICMP (Ping) configuration, and multiple interface configuration
are all saved by CONSOLE_TCP_MULTI_BACKUP.
Some built-in console functions are for use with CONSOLE_TCP_MULTI_BACKUP. In
general, except for backwards compatibility issues, CONSOLE_TCP_MULTI_BACKUP
should be used instead of CONSOLE_TCP_BACKUP.
Note that only one of the CONSOLE_TCP_* structures should be used.
CONSOLE_HTTP_BACKUP
Causes backup of the files and variables visible to the HTTP server.
CONSOLE_SMTP_BACKUP
Causes backup of the mail configuration.
CONSOLE_BACKUP_LOGIN
Causes backup of the ConsoleLogin structure which stores the login name and pass-
word strings.
CON_BACKUP_FILE1
The file number used for the first backup file. For FS1, this number must be in the range
128-143, so that fs_reserve_blocks() can be used to guarantee free space for the
backup files. Defaults to 128 for FS1. Defaults to 254 for FS2.
CON_BACKUP_FILE2
Same as above, except this is for the second backup file. Two files are used so that con-
figuration information is preserved even if the power cycles while configuration data is
being saved. For FS1, this number must be in the range 128-143. Defaults to 129 for FS1.
Defaults to 255 for FS2.
CON_BACKUP_USER_BLOCK
Defaults to not defined. If this is defined, then configuration information for the console
will be saved to the User block instead of to the flash file system. Note that the configu-
ration is only safe in the case of power failures with a version 3 or higher System ID
block.
CON_BUF_SIZE
Changes the size of the data buffer that is allocated for each I/O method. If the baud rate
or transfer speed is too great for the console to keep up, then increasing this value may
help avoid dropped characters. It is allocated in root data space. It defaults to 1024 bytes.
CON_CMD_SIZE
Changes the size of the command buffer that is allocated for each I/O method. This limits
the length of a command line. It is allocated in root data space. Defaults to 128 bytes.
CON_CMD_DATA_SIZE
Default is 16. Adjusts the size of the user data area within the state structure so that user
commands may preserve arbitrary information across calls. The user data area is allocat-
ed in root data space.
CON_DHCP_ACQUIRE_RETRY_TIMEOUT
Defaults to 120 seconds. If DHCP is enabled, then Zconsole will maintain the DHCP
lease. This macro specifies the number of seconds after which a DHCP lease has been
dropped that the board will attempt to reacquire the lease. Note that in the normal course
of operation, a lease will never be dropped. Generally, that will only happen if the DHCP
server is inoperable for an extended period of time (subject to the lengths of the leases
that the DHCP server issues).
CON_INIT_MESSAGE
Defines the message that is displayed on all Zconsole I/O methods upon startup. Defaults
to “Console Ready\r\n”.
CON_MAIL_BUF_SIZE
Maximum length of a mail message. Defaults to 1024.
CON_MAIL_FROM_SIZE
Maximum length of mail from address to NULL terminator. Default to 51.
CON_MAIL_SERV_SIZE
Maximum length of mail server name and NULL terminator. Defaults to 51.
CON_MAX_NAME
Default is 10: maximum number of characters for a login name. This value must be equal
to or less than CON_CMD_DATA_SIZE.
CON_MAX_PASSWORD
Default is 10: maximum number of characters for a login password.
CON_NO_FS_SUPPORT
This macro is defined by default only if no filesystem libraries have been used. Even if a
filesystem library has been used, this can still be explicitly defined by the user. When this
is defined, then the console will not save configuration information to the filesystem, and
no filesystem function calls will be included.
CON_SP_RDBUF_SIZE
Size of the slave port read buffer. Defaults to 255.
CON_SP_WRBUF_SIZE
Size of the slave port write buffer. Defaults to 255.
CON_TIMEOUT
Adjusts the number of seconds that the console will wait before cancelling the current
command. The timeout can be adjusted in user code in the following manner:
state->timeout = con_set_timeout(CON_TIMEOUT);
This is useful for custom user commands so that they can indicate when something
“meaningful” has happened on the console (such as some data being successfully trans-
ferred).
CON_VERSION_MESSAGE
This defines the version message to display when the HELP command is issued with no
parameters. It is not defined by default, so has no default value.
/*
* Size of the buffers for serial port C. If you want to use another serial port, you should
* change the buffer macros below appropriately (and change the console_io[] array below).
*/
#define CINBUFSIZE 1023
#define COUTBUFSIZE 255
/*
* Maximum number of connections to the web server. This indicates the number of sockets
* that the web server will use.
*/
#define HTTP_MAXSERVERS 2
/*
* Maximum number of sockets this program can use. The web server is taking two sockets:
* the mail client uses one socket, and the telnet interface uses the other socket.
*/
#define MAX_SOCKETS 4
/*
* All web server content is dynamic, so we do not need http_flashspec[].
*/
#define HTTP_NO_FLASHSPEC
/*
* The file system that the console uses should be located in flash.
*/
#define FS_FLASH
/*
* The function prototype for a custom command must be declared before the
* console_command[] array.
*/
int hello_world ( ConsoleState *state);
/*
* The number of console I/O streams that this program supports. Since we are supporting
* serial port C and telnet, there are two I/O streams.
*/
#define NUM_CONSOLES 2
/*
* If this macro is defined, then the version message will be shown with the help command,
* when the help command has no parameters.
*/
#define CON_HELP_VERSION
/*
* Defines the version message that will be displayed in the help command if
* CON_HELP_VERSION is defined.
*/
#define CON_VERSION_MESSAGE "TCP/IP Console Version 1.0\r\n"
/*
* Defines the message that is displayed on all I/O channels when the console starts.
*/
#define CON_INIT_MESSAGE CON_VERSION_MESSAGE
/*
* The ximport directives include the help texts for the console commands. Having the help text
* in xmem helps save root code space.
*/
#ximport "samples\zconsole\tcpipconsole_help\help.txt" help_txt
...
/* The rest of the #ximport statements may be seen in tcpipconsole.c. */
/* The console will be available to the I/O streams given in the following array. The I/O streams
* are defined through macros as documented in Section 11.5.2. The parameter for the first macro
* represents the initial baud rate for serial port C. The second macro is passed the port number
* for telnet. If you change the number of I/O streams, update NUM_CONSOLES above.*/
const ConsoleIO console_io[] = {
CONSOLE_IO_SERC(57600),
CONSOLE_IO_TELNET(23)
};
/* This array defines the commands that are available in the console. The first parameter for the
* ConsoleCommand structure is the command specification, i.e., how the console
* recognizes a command. The second parameter is the function to call when the command
* is recognized. The third parameter is the location of the #ximport’ed help file for the command.
* Note that the second parameter can be NULL, which is useful if help information is needed
* for something that is not a command (like for the "SET" command below--the help file for
* "SET" contains a list of all of the set commands). Also note the entry for the command "",
* which is used to set up the help text that is displayed when the help command is used by
* itself (that is, with no parameters).*/
const ConsoleCommand console_commands[] = {
{ "HELLO WORLD", hello_world, 0 },
{ "ECHO", con_echo, help_echo_txt },
{ "HELP", con_help, help_help_txt },
{ "", NULL, help_txt },
{ "SET", NULL, help_set_txt },
{ "SET PARAM", con_set_param, help_set_param_txt },
...
};
/* This array sets up the error messages that can be generated. CON_STANDARD_ERRORS is
* a macro that expands to the standard errors used by the built-in commands in zconsole.lib.
* Users can define their own errors here, as well.*/
const ConsoleError console_errors[] = {
CON_STANDARD_ERRORS
};
/* This array defines the information (such as configuration) that will be saved to the file system.
* Note that if, for example, the HTTP or SMTP related commands are included in the
* console_commands array above, then the backup information must be included in
* this array. The entries below are macros that expand to the appropriate entry for each set of
* functionality. Users can also add their own information to be backed up here by adding
* more ConsoleBackup structures.*/
const ConsoleBackup console_backup[] = {
CONSOLE_BASIC_BACKUP,
CONSOLE_TCP_BACKUP,
CONSOLE_HTTP_BACKUP,
CONSOLE_SMTP_BACKUP
};
The function for the custom command is defined here and the main program finishes up the pro-
gram. To see the complete sample, look in Samples\zconsole\tcpipconsole.c.