WebSite
WebSite API 1.1 SDK
General Information

Return to Overview
Rev 13-Apr-96

API Structure

The API consists of a C/C++ header file and an import library that exposes over 40 of the server's internal functions, including its fast form decoder. The header file describes a transaction context block (TCTX) that exposes the server's context information for each transaction. Some of the fields are protected against modification, others are available for modification by some of the extensions. The functions exposed by the server make it possible for you to gain an extraordinary degree of control over your processing, and provide tested, reliable services that are common to many HTTP tasks.

Calling Interface

The server calls all extensions with a simple, unified interface. An extension must have an action function, which is called with a single parameter, a pointer to the transaction context for the request. The function prototype for all extensions' action functions is:

    BOOL Action(TCTX *tp);

The action function's name may be anything for filters and registered generators. It is specified in the registry when the extension is installed. See the installation instructions for each extension type in Extensions. For dynamically loaded generators, the entry point name must be Process.

DLL Main Entry

All Win32 dynamic link libraries need a main entry. The main entry is called by the operating system for each process and thread that attaches to, and detaches from, the DLL. The main entry is not the action routine described above. It is called by the operating system, not by WebSite pro. If you use only Win32 native calls in your extension DLL, your main entry can have any name you like, however you must specify the name in the development environment (details vary between development environments).

WSAPI Version Binding

WSAPI has a version binding interface designed to prevent use of obsolete extensions. We strongly recommend that you use this facility. It is very simple; just call the bind_wsapi function in your DLL's main routine at PROCESS_ATTACH time. This routine performs run-time version locking between the extension DLL and the server. The 'h' file used by the hook contains a #define that carries the major and minor version numbers of the interface for which the 'h' file was written. Your DLL must call this function at process-attach time, with its major and minor versions as parameters. If this function returns TRUE, the interface is usable, else it returns false. If the DLL gets a FALSE back from this function, it must return FALSE from its DLLMain function, refusing the load. The server will report a load refusal to the logs and via a one-time MessageBox.

The call takes a true/false parameter, strict. The ground rules are:

strict = TRUE:
Major and minor versions must match
strict = FALSE:
fail if (1) major versions do not match, or (2) minor version of the DLL is greater than that of the server

Major version changes occur when the interface is changed so as to be incompatible with previous versions (for example, the TCTX structure changes). Minor version changes occur when bugs are fixed and/or new functionality is added in a way that is backward compatible. The DLL cannot load if its minor version is greater than that of the server because it may depend on such bug fixes or additional functionality in the server for its proper operation.

Example DLL Main

Here is a sample DLL main function for Microsoft Visual C++

BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpReserved)
{
    switch(fdwReason)
    {
        case DLL_PROCESS_ATTACH:
            return(bind_wsapi(MAJOR_VERSION, MINOR_VERSION, FALSE));

        case DLL_PROCESS_DETACH:            // No process-wise cleanup
        case DLL_THREAD_ATTACH:             // No thread-wise initialization
        case DLL_THREAD_DETACH:             // No thread-wise cleanup
            return(TRUE);
    }           
}

Using Runtime Libraries

If you use non-Win32 functions (for example, from a C runtime library) it may be necessary to do initialization and cleanup required by the library in the main function. Some libraries require this in order to be thread-safe. Of course, you must use a thread-safe runtime library in the first place. A common mistake is to use a single-threaded C runtime library. See the documentation on your runtime library for details.

Microsoft Visual C++ Runtime Library

The Microsoft Visual C++ runtime library comes in three flavors: a statically linked, single-threaded version; a statically-linked, multithreaded version; and a dynamically linked, multithreaded version. We strongly recommend using the statically-linked multithreaded library. The single-threaded library cannot be used at all. The DLL version of the multithreaded library has caused us some serious server stability problems, and we stopped using it. The statically linked, multithreaded version seems stable. Plus, you never know when some poorly designed installation program will replace your MSVCRT40.DLL with an older, less stable version. Using the statically-linked library will add to the size of your extensions and force multiple copies of the same code (the library) into memory at once. If you are brave, you can try using the DLL version, but we recommend against it.

Regardless of which version of the multithreaded library you use, you must initialize and clean up in your DLL's main function. Fortunately, Microsoft made this easy. In Visual C++ versions 2.0 and later, all you need to do is name your DLL's main entry DLLMain. If you do not need to do any of your own process or thread initialization or cleanup, eliminate the main function from your code entirely. The library contains its own stub DLLMain that will be linked in automatically. In either case specify the entry point to your DLL (watch upper/lower case!) as:

    _DllMainCRTStartup@12

This entry point causes the Microsoft-supplied initialization and cleanup modules to be included in your DLL and to be called as the main entry.

Function Return Value

Some extensions interpret the BOOL return value from the action routine. See the descriptions for each extension for details.

Handling Errors

WebSite Pro's architecture depends on Win32 structured exception handling for its operation. Used properly, structured exception handling is one of the most powerful services provided by Win32, allowing you to greatly simplify your error handling code. To use this feature, you must use a development language that supports structured exception handling. In Microsoft Visual C++, support is provided by the __try/__finally and __try/__except blocks. A detailed explanation of these language features is beyond the scope of this document. It is imperative that you have a thorough understanding of structured exception handling and the support your language provides for this service.

WebSite's FaultGuard Technology

WebSite Pro has a feature, called FaultGuard, that protects the server from faults in WSAPI extensions using structured exception handling. All calls to extension DLLs are guarded by __try/__except blocks. Any exception within a WSAPI DLL will be caught by the FaultGuard code. With the exception described below, FaultGuard will report the exception, then disable the DLL. The only way to re-enable the DLL is to restart the server. By doing this, the server protects itself against exceptions in WSAPI extensions. Thus, an access violation (for example) in a WSAPI DLL will not cause the server to fail. The extension will never be called again, however.

The ABORT exception

There may be times you want the server to simply stop processing the current HTTP request. To do this, use the ABORT macro in wsapi.h. This translates to a Win32 RaiseException call with an exception code of 0xE100000F. If the FaultGuard catches an exception with this code, it will not disable the WSAPI DLL, it simply passes the exception up the line. WebSite Pro itself uses exception 0xE100000F to abort a transaction in progress. Its request-level exception handler (not the FaultGuard one, its parent) does some in-thread cleanup, then the request thread simply exits. Nothing is sent to the client, the socket is simply closed in a way that sends a TCP RST packet to the client (indicating the abort).

The die() Function

Calling the die() function is an easy way to bail out in case of a problem or to finish up by sending an HTTP response other than 200 OK. It does not return, but ultimately raises an exception with exception code 0xE100000F (the ABORT exception described above). Prior to this, however, it sends a properly formed HTTP response to the client. It supports most of the HTTP/1.0 status codes (and reason phrases), so you can use it for generating redirection responses, forcing the username/password dialog to appear at the browser and generate various HTTP error responses. See the documentation for die() for more information.

The FATAL exception

Use the FATAL macro when you believe that your extension has encountered an error from which you cannot safely recover. This macro generates an exception with a code of 0xe1000001. The FaultGuard exception catcher will respond by disabling your DLL, preventing it from being called until the server is restarted. This exception (as with any exception but 0xE100000f described above) is dismissed by the FaultGuard exception catcher; therefore, it will not cause the server itself to fail.

Preventing Leaks

WebSite Pro must be able to run unattended for long periods of time without failing. Your application will most likely become mission critical. Therefore, it is essential that you prevent leakage of things like memory blocks and object handles. Leaks will eventually cause the server (with your DLL as part of it) to exhaust its virtual memory and fail. Before that happens, your paging file(s) (swap file, a misnomer) will grow to a large size, possibly causing the paging drive(s) to run out of space. The C++ language makes it relatively easy to prevent memory leaks if you use its features for run-time allocation of objects that get freed automatically when the object goes out of scope. This feature cannot, however, be used to prevent Win32 object handle leakage.

WSAPI's structured exception handling can be used to simplify your DLL's architecture and make leakage prevention much easier than using layers of if statements and functions that return success/failure results. Any time you need to allocate memory, open files, create synchronization events, and so on, enclose the allocations in the __try section of a __try/__finally block. Right at the beginning, initialize handles with the value INVALID_HANDLE_VALUE and memory pointers with NULL. These sentinels can be used later, in the __finally section to safely clean up no matter where in your logic an error or exception (for example, access violation) occurs, as long as it occurs within the context of the __try section, including any procedure called from within the __try section. Simply test the sentinel, and if it is not the initial value (for example, INVALID_HANDLE_VALUE or NULL), it is safe to close or free the item. The examples provided with WebSite Professional use this technique.

Synchronization Techniques

Because WebSite Pro is fully multithreaded, your extension DLL may be called from many threads at a time. If you are not used to programming in this kind of environment, you can experience endless heartbreaks as you discover the race conditions and resource conflicts that can arise. This section describes some of the basic techniques that you can use with your DLL to make it reliable in a multithreaded environment. It is beyond the scope of this document to give a tutorial on multithreaded programming, however, so it is suggested that you study the plentiful Microsoft and third party documentation that exists on this subject.

Win32 Synchronization Objects

The Win32 API provides three types of synchronization objects: critical sections, mutexes, and semaphores. Use critical sections wherever possible, they are the most efficient and simplest to use. If you need to synchronize access to a shared object (such as a read/write file or data in a shared memory region), you can use named mutexes. Semaphores are rarely needed, but they can be useful if you have a need to maintain a count associated with the lock.

Try to minimize the work you do while holding a synchronization object. If practical (often times it is not), make a copy of a shared variable, then immediately release the lock. In any case, release the lock as soon as possible, since you are locking the other threads out of the resource (putting them to sleep) while you hold the lock.

Guarding Synchronization Objects

Whenever you use a synchronization object, always guard it in a __try/__finally block! This guarantees that the lock will be released if an exception occurs. Suppose you enter a critical section, then your code generates an access violation. The structured exception handling service takes control and performs the global unwind, eventually ending up in an exception filter. If the global unwind doesn't call LeaveCriticalSection() the critical section is locked forever. No other threads can use the shared resource forever thereafter. The same goes for mutexes and semaphores. Obviously a serious problem.

Start a __try/__finally block immediately before locking a shared resource. Then perform the computations that depend on your ownership of the resource. You are free to call functions to any depth (though you should try to minimize computation while the resource is locked). Exceptions in called functions will boil up during the global unwind. Once you no longer need exclusive access to the shared resource, end the __try section and begin the __finally section. Release the lock in the __finally section (and do any other cleanup you may want there as well (see Preventing Leaks above ). If an exception occurs in the __try section (including within functions called), the structured exception handling will perform the global unwind, and the code in the __finally section will get executed, releasing the lock (and doing the cleanup).

Global and Static Variables

Global variables must be used with caution. Globals can be useful for controlling overall behavior, as configuration items, and for other things that don't change from request to request. If you use them for request-specific information, you run the risk that a request running on one thread can change the value at any time with respect to the requests running in other threads. If you must use globals for request-specific information, use Win32 critical sections to guard each access. Be aware that this serializes access to these variables and may affect the performance of your DLL.

Static variables can drive you nuts, unless you allocate them using thread-local storage. A typical error involves allocating a static string buffer in a function, then returning a pointer to that buffer. In a multithreaded environment, different threads will overwrite the contents of the static buffer and your function will appear to return random data.

Shared Files

Both the Win32 API and the Microsoft C runtime library have file I/O that is thread safe. Therefore, it is not necessary to serialize writes to a shared file. However, if you attempt to open a file for write each time your extension is called, and you do not allow shared write, the file open may fail ("already open for write") if you have multiple threads running at the same time. Consider opening the file once, in the process attach call of your DLL and using the open file handle or pointer. Flush the buffers from time to time using FlushFileBuffers() (Win32) or fflush() (C runtime).

Be aware that you cannot predict when a particular request will write to the shared file. Just because a particular request arrives before another does not mean that it will write to the file in that order. You may need to timestamp entries and sort them later. You can use the TCTX dwStartTicks field as a relative time stamp, for example.

Thread-Local Storage

Some development languages support thread-local storage. This feature normally cannot be used with DLLs that are loaded at run time via the LoadLibrary() function. WSAPI loads all extensions this way, so you cannot use the high level thread-local storage provided in the language. For example, in Visual C++, you cannot use the __declspec(thread) modifier on variable declarations to give them the thread-local attribute.

As described in the Win32 SDK documentation, you can use the low-level thread-local storage functions (for example, TlsAlloc()) to allocate a single pointer per thread, at DLL_THREAD_ATTACH time.

The WSAPI Form Decoder

WSAPI exposes WebSite Pro's internal HTML form decoder via the functions open_form_decoder(), decode_next_field(), and close_form_decoder. The decoder supports the two types of form-data encoding currently in use (application/x-www-form-urlencoded and multipart/form-data). The latter encoding is used with forms that support the new form-based file uploading feature of some browsers.

The internal form decoder is optimized for in-memory scanning and processing and is, therefore, very fast. In addition, it isolates you from the differences in form encoding and the complexity of the multipart/form-data encoding. The example given in the open_form_decoder() description, plus the formdecode generator sample supplied with WebSite Pro show how easy it is to use the WSAPI decoder.

The WSAPI Image Mapper

WSAPI exposes WebSite Pro's built-in image mapper via the do_imagemap() function. To use it you simply pass the full pathname of an NCSA-format image map file and a coordinate string from either a URL query string (ISMAP/GET) or from an <INPUT TYPE=IMAGE> tag within a form. Either format of coordinates are understood by WebSite Pro's decoder. The function will return with the local URL of the target, or issue a redirect if the target resolves to a remote URL. The mapper supports NCSA format image map files.


[email protected]