start page | rating of books | rating of authors | reviews | copyrights

Apache The Definitive Guide, 3rd EditionApache: The Definitive GuideSearch this book

A.6. Functions

Now that we have covered the main structures used by modules, we can detail the functions available to use and manipulate those structures.

A.6.1. Pool Functions

ap_make_sub_poolcreate a subpool

pool *ap_make_sub_pool(pool *p)
Creates a subpool within a pool. The
subpool is destroyed automatically when the pool p is destroyed, but can also be destroyed earlier with destroy_pool or cleared with clear_pool. Returns the new pool.

ap_clear_poolclear a pool without destroying it

void ap_clear_pool(pool *p)
Clears a pool, destroying all its subpools with destroy_pool and running cleanups. This leaves the pool itself empty but intact, and therefore available for reuse.

ap_destroy_pooldestroy a pool and all its contents

void ap_destroy_pool(pool *p)
Destroys a pool, running cleanup methods for the contents and also destroying all subpools. The subpools are destroyed before the pool's cleanups are run.

ap_bytes_in_poolreport the size of a pool

long ap_bytes_in_pool(pool *p)
Returns the number of bytes currently allocated to a pool.

ap_bytes_in_free_blocksreport the total size of free blocks in the pool system

long ap_bytes_in_free_blocks(void)
Returns the number of bytes currently in free blocks for all pools.

ap_pallocallocate memory within a pool

void *ap_palloc(pool *p, int size)
Allocates memory of at least size bytes. The memory is destroyed when the pool is destroyed. Returns a pointer to the new block of memory.

ap_pcallocallocate and clear memory within a pool

void *ap_pcalloc(pool *p, int size)
Allocates memory of at least size bytes. The memory is initialized to zero. The memory is destroyed when the pool is destroyed. Returns a pointer to the new block of memory.

ap_pstrdupduplicate a string in a pool

char *ap_pstrdup(pool *p,const char *s)
Duplicates a string within a pool. The memory is destroyed when the pool is destroyed. If s is NULL, the return value is NULL; otherwise, it is a pointer to the new copy of the string.

ap_pstrndupduplicate a string in a pool with limited length

char *ap_pstrndup(pool *p, const char *s, int n)
Allocates n+1 bytes of memory and copies up to n characters from s, NULL- terminating the result. The memory is destroyed when the pool is destroyed. Returns a pointer to the new block of memory, or NULL if s is NULL

ap_pstrcatconcatenate and duplicate a list of strings

char *ap_pstrcat(pool *p, ...)
Concatenates the NULL-terminated list of strings together in a new block of memory. The memory is destroyed when the pool is destroyed. Returns a pointer to the new block of memory. For example:

pstrcat(p,"Hello,","world!",NULL);

returns a block of memory containing Hello, world!

A.6.2. Array Functions

ap_make_arrayallocate an array of arbitrary-size elements

array_header *ap_make_array(pool *p, int nelts, int elt_size)
Allocates memory to
contain nelts elements of size elt_size. The array can grow to contain as many elements as needed. The array is destroyed when the pool is destroyed. Returns a pointer to the new array.

ap_push_arrayadd a new element to an array

void *ap_push_array(array_header *arr)
Returns a pointer to the next element of the array arr, allocating more memory to accommodate it if necessary.

ap_array_catconcatenate two arrays

void ap_array_cat(array_header *dst, const array_header *src)
Appends the array src to the array dst. The dst array is allocated more memory if necessary to accommodate the extra elements. Although this operation only makes sense if the two arrays have the same element size, there is no check for this.

ap_copy_arraycreate a copy of an array

array_header *ap_copy_array(pool *p, const array_header *arr)
Creates a new copy of the array arr in the pool p. The new array is destroyed when the pool is destroyed. Returns a pointer to the new array.

ap_copy_array_hdrcreate a copy of an array with copy-on-write

array_header *ap_copy_array_hdr(pool *p, const array_header *arr)
Copies the array arr into the pool p without immediately copying the array's storage. If the array is extended with push_array, the original array is copied to the new array before the extension takes place. Returns a pointer to the new array.

There are at least two pitfalls with this function. First, if the array is not extended, its memory is destroyed when the original array is destroyed; second, any changes made to the original array may also affect the new array if they occur before the new array is extended.

ap_append_arraysconcatenate two arrays into a new array

array_header *ap_append_arrays(pool *p, const array_header *first, 
const array_header *second)
Creates a new array consisting of the elements of second appended to the elements of first. If second is empty, the new array shares memory with first until a new element is appended. (This is a consequence of using ap_copy_array_hdr( ) to create the new array; see the warning in that function.) Returns a pointer to the new array.

A.6.3. Table Functions

A table is an association between two strings known as the key and the value, accessible by the key.

ap_make_tablecreate a new table

table *ap_make_table(pool *p, int nelts)
Creates a new table with sufficient initial storage for nelts elements. Returns a pointer to the table.

ap_copy_tablecopy a table

table *ap_copy_table(pool *p, const table *t)
Returns a pointer to a copy of the table.

ap_table_eltsaccess the array that underlies a table

array_header *ap_table_elts(table *t)
Returns the array upon which the table is based.

ap_is_empty_tabletest whether a table is empty

int ap_is_empty_table(table *t)
Returns nonzero if the table is empty.

ap_table_setcreate or replace an entry in a table

void ap_table_set(table *t, const char *key, const char *value)
If key already has an associated value in t, it is replaced with a copy of value; otherwise, a new entry is created in the table. Note that the key and value are duplicated with ap_pstrdup( ).

ap_table_setncreate or replace an entry in a table without duplication

void ap_table_setn(table *t, const char *key, const char *value)
This is similar to ap_table_set( ), except that the key and value are not duplicated. This is normally used to copy a value from a pool to a subpool.

ap_table_mergemerge a new value into a table

void ap_table_merge(table *t, const char *key, const char *value)
If an entry already exists for key in the table, value is appended to the existing value, separated by a comma and a space. Otherwise, a new entry is created, as in table_set. Note that if multiple instances of key exist in the table, only the first is affected.

pool *p;			/* Assumed to be set elsewhere */
table *t;
char *v;

t=make_table(1);
table_set(t,"somekey","Hello");
table_merge(t,"somekey","world!");
v=table_get(t,"somekey");	/* v now contains "Hello, world!" */
ap_table_mergenmerge a new value into a table without duplication

void ap_table_mergen(table *t, const char *key, const char *value)
This is similar to ap_table_merge( ), except that if a new key/value pair is created, it is not duplicated. This is normally used to merge a value from a pool into a subpool.

ap_table_addadd a new key/value pair to a table

void ap_table_add(table *t, const char *key, const char *value)
Adds a new entry to the table, associating key with value. Note that a new entry is created regardless of whether the key already exists in the table. The key and value stored are duplicated using ap_pstrdup( ).

ap_table_addnadd a new key/value pair to a table without duplication

void ap_table_addn(table *t, const char *key, const char *value)
Adds a new entry to the table, associating key with value. Note that a new entry is created regardless of whether the key already exists in the table. The key and value stored are not duplicated, so care must be taken to ensure they are not changed. This function is normally used to copy a table element from a pool into a subpool.

ap_table_unsetremove an entry from a table

void ap_table_unset(table *t, const char *key)
Removes the entry in the table corresponding to key. It is not an error to remove an entry that does not exist.

ap_table_ getfind the value in a table corresponding to a key

const char *ap_table_ get(const table *t, const char *key)
Returns the value corresponding to key in the table t. Note that you may not modify the returned value.

ap_table_doapply a function to each element of a table

void ap_table_do(int (*comp) (void *, const char *, const char *), void *rec, 
const table *t,...)
If the NULL-terminated vararg list is empty, traverses the whole table and runs the function comp(rec,key,value) on each key/value pair. If the vararg list is nonempty, traverses the matching keys (strcasecmp( ) is used to determine a match) and runs the same function. Each traversal is terminated if the function comp returns the value 0.

In either case it may happen that the comp( ) function is called multiple times for the same key. The table may again contain various entries of the same key; if the vararg list is nonempty, the traversal is repeated for any vararg item, even if they are equal.

ap_overlay_tablesconcatenate two tables to give a new table

table *ap_overlay_tables(pool *p, const table *overlay, const table *base)
Creates a new table consisting of the two tables overlay and base concatenated — overlay first. No attempt is made to merge or override existing keys in either table, but since overlay comes first, any retrieval done with table_get on the new table gets the entry from overlay if it exists. Returns a pointer to the new table.

ap_clear_tableclear a table without deleting it

API_EXPORT(void) ap_clear_table(table *t)
Clears the table. None of the elements are destroyed (since the pool mechanism doesn't permit it, anyway), but they become unavailable.

A.6.4. Cleanup Functions

An important part of the pool is the cleanup functions that are run when the pool is destroyed. These functions deal with those cleanup functions.

ap_register_cleanupregister a cleanup function

void ap_register_cleanup(pool *p, void *data, void (*plain_cleanup)(void *), 
void (*child_cleanup)(void *))
Registers a pair of functions to be called when the pool is destroyed. Pools can be destroyed for two reasons: first, because the server has finished with that pool, in which case it destroys it and calls the plain_cleanup function, or second, because the server has forked and is preparing to exec some other program, in which case the child_cleanup function is called. In either case, data is passed as the only argument to the cleanup function. If either of these cleanups is not required, use ap_null_cleanup.

ap_kill_cleanupremove a cleanup function

void ap_kill_cleanup(pool *p, void *data, void (*plain_cleanup)(void *))
Removes the previously registered cleanup function from the pool. The cleanup function is identified by the plain_cleanup function and the data pointer previously registered with register_cleanup. Note that the data pointer must point to the same memory as was used in register_cleanup.

ap_cleanup_for_execclear all pools in preparation for an exec

void ap_cleanup_for_exec(void)
Figure

Destroys all pools using the child_cleanup methods. Needless to say, this should only be done after forking and before running a (nonserver) child. Calling this in a running server certainly stops it from working! Note that on Win32 this actually does nothing on the slightly dubious grounds that we aren't forked. Unfortunately, there isn't really much alternative.

ap_note_cleanups_for_fdregister a cleanup for a file descriptor

void ap_note_cleanups_for_fd(pool *p, int fd)
Registers a cleanup function that will close the file descriptor when the pool is destroyed. Normally one of the file-opening functions does this for you, but it is occasionally necessary to do it "by hand." Note that sockets have their own cleanup functions.

ap_kill_cleanups_for_fdremove the cleanup for a file descriptor

void ap_kill_cleanups_for_fd(pool *p, int fd)
Kills cleanups for a file descriptor registered using popenf( ), pfopen( ), pfdopen( ), or note_cleanups_for_fd( ). Normally this is taken care of when the file is closed, but occasionally it is necessary to call it directly.

ap_note_cleanups_for_socketregister a cleanup for a socket

void ap_note_cleanups_for_socket(pool *p, int fd)
Registers a cleanup function that will close the socket when the pool is destroyed. This is distinct from ap_note_cleanups_for_fd( ) because sockets and file descriptors are not equivalent on Win32.

ap_kill_cleanups_for_socketremove the cleanup for a socket

void ap_kill_cleanups_for_socket(pool *p, int sock)
Removes the cleanup function for the socket sock. This is normally done for you when the socket is closed by ap_pclosesocket( ), but it may occasionally be necessary to call it directly.

ap_note_cleanups_for_fileregister a cleanup for a FILE

void ap_note_cleanups_for_file(pool *p, FILE *f)
Registers a cleanup function to close the stream when the pool is destroyed. Strangely, there isn't an ap_kill_cleanups_for_file( ).

ap_run_cleanuprun a cleanup function, blocking alarms

void ap_run_cleanup(pool *p, void *data, void (*cleanup)(void *))
Runs a cleanup function, passing data to it, with alarms blocked. It isn't usually necessary to call this, since cleanups are run automatically, but it can be used for any custom cleanup code. The cleanup function is removed from p.

A.6.5. File and Socket Functions

These functions are used to open and close files and sockets with automatic cleanup registration and killing.

ap_popenfopen a file with automatic cleanup

int ap_popenf(pool *p, const char *name, int flg, int mode)
The equivalent to the standard C-function open( ), except that it ensures that the file is closed when the pool is destroyed. Returns the file descriptor for the opened file or -1 on error.

ap_pclosefclose a file opened with popenf

int ap_pclosef(pool *p, int fd)
Closes a file previously opened with ap_popenf( ). The return value is whatever close( ) returns. The file's cleanup function is destroyed.

ap_pfopenopen a stream with automatic cleanup

FILE *ap_pfopen(pool *p, const char *name, const char *mode)
Equivalent to fopen( ), except that it ensures that the stream is closed when the pool is destroyed. Returns a pointer to the new stream or NULL on error.

ap_pfdopenopen a stream from a file descriptor with automatic cleanup

FILE *ap_pfdopen(pool *p, int fd, const char *mode)
Equivalent to fdopen( ), except that it ensures the stream is closed when the pool is destroyed. Returns a pointer to the new stream or NULL on error.

ap_pfcloseclose a stream opened with pfopen( ) or pfdopen( )

int ap_pfclose(pool *p, FILE *fd)
Closes the stream with fclose( ), removing its cleanup function from the pool. Returns whatever fclose( ) returns.

ap_psocketopen a socket with automatic cleanup

int ap_psocket(pool *p, int domain, int type, int protocol)
Opens a socket, using socket( ), registering a cleanup function to close the socket when the pool is destroyed.

ap_pclosesocketclose a socket created with ap_psocket( )

int ap_pclosesocket(pool *a, int sock)
Closes the socket, using closesocket( ), removing the cleanup function from the pool. Returns whatever closesocket( ) returns.

A.6.6. Regular Expression Functions

Note that only the functions that allocate memory are wrapped by Apache API functions.

ap_pregcompcompile a regular expression with automatic cleanup

regex_t *ap_pregcomp(pool *p, const char *pattern, int cflags)
Equivalent to regcomp( ), except that memory used is automatically freed when the pool is destroyed and that the regex_t * argument to regcomp( ) is created in the pool and returned, rather than being passed as a parameter.

ap_pregsubsubstitute for regular-expression submatches

char *ap_pregsub(pool *p, const char *input, const char *source, size_t nmatch,
regmatch_t pmatch[])
Substitutes for $0-$9 in input, using source as the source of the substitutions and pmatch to determine from where to substitute. nmatch, pmatch, and source should be the same as passed to regexec( ). Returns the substituted version of input in memory allocated from p.

ap_pregfreefree a regular expression compiled with ap_pregcomp( )

void ap_pregfree(pool *p, regex_t * reg)
Frees the regular expression with regfree( ), removing its cleanup function from the pool.

ap_os_is_path_absolutedetermine whether a path is absolute

int ap_os_is_path_absolute(const char *file)
Returns 1 if file is an absolute path, 0 otherwise.

A.6.7. Process and CGI Functions

ap_note_subprocessregister a subprocess for killing on pool destruction

void ap_note_subprocess(pool *p, int pid, enum kill_conditions how)
Registers a subprocess to be killed on pool
destruction. Exactly how it is killed depends on how :

kill_never
Don't kill the process or wait for it. This is normally used internally.

kill_after_timeout
Send the process a SIGTERM, wait three seconds, send a SIGKILL, and wait for the process to die.

kill_always
Send the process a SIGKILL and wait for the process to die.

just_wait
Don't send the process any kind of kill.

kill_only_once
Send a SIGTERM, then wait.

Note that all three-second delays are carried out at once, rather than one after the other.

ap_spawn_childspawn a child process

int ap_spawn_child(pool *p, void(*func)(void *,child_info *), void *data, enum kill_
conditions kill_how, FILE **pipe_in, FILE **pipe_out, FILE **pipe_err)
This function should not be used, as it is known to expose bugs in Microsoft's libraries on Win32. You should use ap_bspawn_child( ) instead. This function was called spawn_child_err in previous versions of Apache.

ap_bspawn_childspawn a child process

int ap_bspawn_child(pool *p, int (*func) (void *, child_info *), void *data, enum 
kill_conditions kill_how, BUFF **pipe_in, BUFF **pipe_out, BUFF **pipe_err)
Figure

Spawns a child process with pipes optionally connected to its standard input, output, and error. This function takes care of the details of forking (if the platform supports it) and setting up the pipes. func is called with data and a child_info structure as its arguments in the child process. The child_info structure carries information needed to spawn the child under Win32; it is normally passed straight on to ap_call_exec( ). If func( ) wants cleanup to occur, it calls cleanup_for_exec. func( ) will normally execute the child process with ap_call_exec( ). If any of pipe_in, pipe_out, or pipe_err are NULL, those pipes aren't created; otherwise, they are filled in with pointers to BUFF s that are connected to the subprocesses' standard input, output, and error, respectively. Note that on Win32, the pipes use Win32 native handles rather than C-file handles. This function only returns in the parent. Returns the PID of the child process or -1 on error. This function was called spawn_child_err_buff in previous versions of Apache.

ap_call_execexec, spawn, or call setuid wrapper

int ap_call_exec(request_rec *r, child_info *pinfo, char *argv0, char **env, 
int shellcmd)
Calls exec( ) (or an appropriate spawning function on nonforking platforms) or the setuid wrapper, depending on whether setuid wrappers are enabled. argv0 is the name of the program to run; env is a NULL-terminated array of strings to be used as the environment of the exec ed program. If shellcmd is nonzero, the command is run via a shell. If r->args is set and does not contain an equal sign, it is passed as a command-line argument. pinfo should be the structure passed by ap_bspawn_child( ). This function should not return on forking platforms. On nonforking platforms it returns the PID of the new process.

ap_can_execcheck whether a path can be executed

int ap_can_exec(const struct stat *finfo)
Given a struct stat (from stat( ), etc.), returns nonzero if the file described by finfo can be executed.

ap_add_cgi_varsset environment variables for CGIs

void ap_add_cgi_vars(request_rec *r)
Adds the environment variables required by the CGI specification (apart from those added by ap_add_common_vars( )). Call this before actually exec( ) ing a CGI. ap_add_common_vars( ) should also be called.

ap_add_common_varsset environment variables for subprograms

void ap_add_common_vars(request_rec *r)
Adds the environment variables common to all subprograms run as a result of a request. Usually, ap_add_cgi_vars( ) should be called as well. The only exception we are aware of is ISAPI programs.

ap_scan_script_header_errscan the headers output by a CGI

int ap_scan_script_header_err(request_rec *r, FILE *f, char *buffer)
Read the headers arriving from a CGI on f, checking them for correctness. Most headers are simply stored in r->headers_out, which means they'll ultimately be sent to the client, but a few are dealt with specially:

Status
If this is set, it is used as the HTTP response code.

Location
If this is set, the result is a redirect to the URL specified.

If buffer is provided (it can be NULL), then — should the script send an illegal header — it will be left in buffer, which must be at least MAX_STRING_LEN bytes long. The return value is HTTP_OK, the status set by the script, or SERVER_ERROR if an error occurred.

ap_scan_script_header_err_buffscan the headers output by a CGI

int ap_scan_script_header_err_buff(request_rec *r, BUFF *fb, char *buffer)
This is similar to ap_scan_script_header_err( ), except that the CGI is connected with a BUFF * instead of a FILE *.

ap_scan_script_headerscan the headers output by a CGI

int ap_scan_script_header(request_rec *r, FILE *f)
This is similar to ap_scan_script_header_err( ), except that no error buffer is passed.

A.6.8. MD5 Functions

ap_md5calculate the MD5 hash of a string

char *ap_md5(pool *p, unsigned char *string)
Calculates
the MD5 hash of string, returning the ASCII hex representation of the hash (which is 33 bytes, including terminating NUL), allocated in the pool p.

ap_md5contextTo64convert an MD5 context to base-64 encoding

char *ap_md5contextTo64(pool *a, AP_MD5_CTX * context)
Take the MD5 hash in context (which must not have had ap_MD5Final run) and make a base-64 representation of it in the pool a.

ap_md5digestmake a base-64 MD5 digest of an open file

char *ap_md5digest(pool *p, FILE *infile)
Reads the file infile from its current position to the end, returning a base-64 MD5 digest allocated in the pool p. The file is rewound to the beginning after calculating the digest.

ap_MD5Initinitialize an MD5 digest

void ap_MD5Init(AP_MD5_CTX *context)
Initializes context in preparation for an MD5 digest.

ap_MD5Finalfinalize an MD5 digest

void ap_MD5Final(unsigned char digest[16], AP_MD5_CTX *context)
Finishes the MD5 operation, writing the digest to digest and zeroing context.

ap_MD5Updateadd a block to an MD5 digest

void ap_MD5Update(AP_MD5_CTX * context, const unsigned char *input, unsigned int 
inputLen)
Processes inputLen bytes of input, adding
them to the digest being calculated in context.

A.6.9. Synchronization and Thread Functions

These functions hide operating system-dependent functions. On platforms that do not use threads for Apache, these functions exist but do not do anything; they simulate success if called.

Note that of these functions, only the mutex functions are actually implemented. The rest are documented for completeness (and in case they get implemented).

A.6.9.1. Mutex functions

ap_create_mutexcreate a mutual exclusion object

mutex *ap_create_mutex(char *name)
Creates a mutex object with the name name. Returns NULL if the operation fails.

ap_open_mutexopen a mutual exclusion object

mutex *ap_open_mutex(char *name)
Opens an existing mutex with the name name. Returns NULL if the operation fails.

ap_acquire_mutexlock an open mutex object

int ap_acquire_mutex(mutex *mutex_id)
Locks the open mutex mutex_id. Blocks until the lock is available. Returns MULTI_OK or MULTI_ERR.

ap_release_mutexrelease a locked mutex

int ap_release_mutex(mutex *mutex_id)
Unlocks the open mutex mutex_id. Blocks until the lock is available. Returns MULTI_OK or MULTI_ERR.

ap_destroy_mutexdestroy an open mutex

void ap_destroy_mutex(mutex *mutex_id);
Destroys the mutex mutex_id.

A.6.9.2. Semaphore functions

create_semaphorecreate a semaphore

semaphore *create_semaphore(int initial)
Creates a semaphore with an initial value of initial.

acquire_semaphoreacquire a semaphore

int acquire_semaphore(semaphore *semaphore_id)
Acquires the semaphore semaphore_id. Blocks until it is available. Returns MULTI_OK or MULTI_ERR.

release_semaphorerelease a semaphore

int release_semaphore(semaphore *semaphore_id)
Releases the semaphore semaphore_id. Returns MULTI_OK or MULTI_ERR.

destroy_semaphoredestroy an open semaphore

void destroy_semaphore(semaphore *semaphore_id)
Destroys the semaphore semaphore_id.

A.6.9.3. Event functions

create_eventcreate an event

event *create_event(int manual, int initial, char *name)
Creates an event named name with an initial state of initial. If manual is true, the event must be reset manually. If not, setting the event immediately resets it. Returns NULL on failure.

open_eventopen an existing event

event *open_event(char *name)
Opens an existing event named name. Returns NULL on failure.

acquire_eventwait for an event to be signaled

int acquire_event(event *event_id)
Waits for the event event_id to be signaled. Returns MULTI_OK or MULTI_ERR.

set_eventsignal an event

int set_event(event *event_id)
Signals the event event_id. Returns MULTI_OK or MULTI_ERR.

reset_eventclear an event

int reset_event(event *event_id)
Clears the event event_id. Returns MULTI_OK or MULTI_ERR.

destroy_eventdestroy an open event

void destroy_event(event *event_id)
Destroys the event event_id .

A.6.9.4. Thread functions

create_threadcreate a thread

thread *create_thread(void (thread_fn) (void *thread_arg), void *thread_arg)
Creates a thread, calling thread_fn with the argument thread_arg in the newly created thread. Returns NULL on failure.

kill_threadkill a thread

int kill_thread(thread *thread_id)
Kills the thread thread_id. Since this may leave a thread's resources in an unknown state, it should only be used with caution.

await_threadwait for a thread to complete

int await_thread(thread *thread_id, int sec_to_wait)
Waits for the thread thread_id to complete or for sec_to_wait seconds to pass, whichever comes first. Returns MULTI_OK, MULTI_TIMEOUT, or MULTI_ERR.

exit_threadexit the current thread

void exit_thread(int status)
Exits the current thread, returning status as the thread's status.

A.6.10. Time and Date Functions

ap_ get_timereturn a human-readable version of the current time

char *ap_ get_time(void)
Uses
ctime to format the current time and removes the trailing newline. Returns a pointer to a string containing the time.

ap_ht_timereturn a pool-allocated string describing a time

char *ap_ht_time(pool *p, time_t t, const char *fmt, int gmt)
Formats the time using strftime and returns a pool-allocated copy of it. If gmt is nonzero, the time is formatted as GMT; otherwise, it is formatted as local time. Returns a pointer to the string containing the time.

ap_ gm_timestr_822format a time according to RFC 822

char *ap_ gm_timestr_822(pool *p, time_t t)
Formats the time as specified by RFC 822 (Standard for the Format of ARPA Internet Text Messages).
[83] The time is always formatted as GMT. Returns a pointer to the string containing the time.

[83]Or, in other words, mail. Since HTTP has elements borrowed from MIME and MIME is for mail, you can see the connection.

ap_ get_ gmtoffget the time and calculate the local time zone offset from GMT

struct tm *ap_ get_ gmtoff(long *tz)
Returns the current local time, and tz is filled in with the offset of the local time zone from GMT, in seconds.

ap_tm2secconvert a struct tm to standard Unix time

time_t ap_tm2sec(const struct tm *t)
Returns the time in t as the time in seconds since 1 Jan 1970 00:00 GMT. t is assumed to be in GMT.

ap_parseHTTPdateconvert an HTTP date to Unix time

time_t ap_parseHTTPdate(const char *date)
Parses a date in one of three formats, returning the time in seconds since 1 Jan 1970 00:00 GMT. The three formats are as follows:

  • Sun, 06 Nov 1994 08:49:37 GMT (RFC 822, updated by RFC 1123)

  • Sunday, 06-Nov-94 08:49:37 GMT (RFC 850, made obsolete by RFC 1036)

  • Sun Nov 6 08:49:37 1994 (ANSI C asctime( ) format)

Note that since HTTP requires dates to be in GMT, this routine ignores the time-zone field.

A.6.11. String Functions

ap_strcmp_matchwildcard match two strings

int ap_strcmp_match(const char *str, const char *exp)
Matches
str to exp, except that * and ? can be used in exp to mean "any number of characters" and "any character," respectively. You should probably use the newer and more powerful regular expressions for new code. Returns 1 for success, 0 for failure, and -1 for abort.

ap_strcasecmp_matchcase-blind wildcard match two strings

int ap_strcasecmp_match(const char *str, const char *exp)
Similar to strcmp_match, except matching is case blind.

ap_is_matchexpdoes a string contain wildcards?

int ap_is_matchexp(const char *exp)
Returns 1 if exp contains * or ?; 0 otherwise.

ap_ getwordextract one word from a list of words

char *ap_ getword(pool *p, const char **line, char stop)
char *ap_ getword_nc(pool *p, char **line, char stop)
Looks for the first occurrence of stop in *line and copies everything before it to a new buffer, which it returns. If *line contains no stop s, the whole of *line is copied. *line is updated to point after the occurrence of stop, skipping multiple instances of stop if present. ap_ getword_nc( ) is a version of ap_ getword( ) that takes a nonconstant pointer. This is because some C compilers complain if a char ** is passed to a function expecting a const char **.

ap_ getword_whiteextract one word from a list of words

char *ap_ getword_white(pool *p, const char **line)
char *ap_ getword_white_nc(pool *p, char **line)
Works like ap_ getword( ), except the words are separated by whitespace (as determined by isspace).

ap_ getword_nullsextract one word from a list of words

char *ap_ getword_nulls(pool *p, const char **line, char stop)
char *ap_ getword_nulls_nc(pool *p, char **line, char stop)
Works like ap_ getword( ), except that multiple occurrences of stop are not skipped, so null entries are correctly processed.

ap_ getword_confextract one word from a list of words

char *ap_ getword_conf(pool *p, const char **line)
char *ap_ getword_conf_nc(pool *p, char **line)
Works like ap_ getword( ), except that words can be separated by whitespace and can use quotes and backslashes to escape characters. The quotes and backslashes are stripped.

ap_ get_tokenextract a token from a string

char *ap_ get_token(pool *p, const char **line, int accept_white)
Extracts a token from *line, skipping leading whitespace. The token is delimited by a comma or a semicolon. If accept_white is zero, it can also be delimited by whitespace. The token can also include delimiters if they are enclosed in double quotes, which are stripped in the result. Returns a pointer to the extracted token, which has been allocated in the pool p.

ap_find_tokenlook for a token in a line (usually an HTTP header)

int ap_find_token(pool *p, const char *line, const char *tok)
Looks for tok in line. Returns nonzero if found. The token must exactly match (case blind) and is delimited by control characters (determined by iscntrl), tabs, spaces, or one of these characters:

( )<>@,;\\/[]?={}

This corresponds to the definition of a token in RFC 2068.

ap_find_last_tokencheck if the last token is a particular string

int ap_find_last_token(pool *p, const char *line, const char *tok)
Checks whether the end of line matches tok and whether tok is preceded by a space or a comma. Returns 1 if so, 0 otherwise.

ap_escape_shell_cmdescape dangerous characters in a shell command

char *ap_escape_shell_cmd(pool *p, const char *s)
Prefixes dangerous characters in s with a backslash, returning the new version. The current set of dangerous characters is as follows:

&;''\"|*?~<>^( )[]{}$\\\n

Under OS/2, & is converted to a space.[84]

[84]Don't think that using this function makes shell scripts safe: it doesn't. See Chapter 11.

ap_uudecodeuudecode a block of characters

char *ap_uudecode(pool *p, const char *coded)
Returns a decoded version of coded allocated in p.

ap_escape_htmlescape some HTML

char *ap_escape_html(pool *p, const char *s)
Escapes HTML so that the characters <, >, and & are displayed correctly. Returns a pointer to the escaped HTML.

ap_checkmaskcheck whether a string matches a mask

int ap_checkmask(const char *data, const char *mask)
Checks whether data conforms to the mask in mask. mask is composed of the following characters:

@
An uppercase letter

$
A lowercase letter

&
A hexadecimal digit

#
A decimal digit

~
A decimal digit or a space

*
Any number of any character

Anything else
Itself

data is arbitrarily limited to 256 characters. It returns 1 for a match, 0 if not. For example, the following code checks for RFC 1123 date format:

if(ap_checkmask(date, "## @$$ #### ##:##:## *"))
    ...
ap_str_tolowerconvert a string to lowercase

void ap_str_tolower(char *str)
Converts str to lowercase, in place.

ap_psprintfformat a string

char *ap_psprintf(pool *p, const char *fmt, ...)
Much the same as the standard function sprintf( ) except that no buffer is supplied; instead, the new string is allocated in p. This makes this function completely immune from buffer overflow. Also see ap_vformatter( ).

ap_pvsprintfformat a string

char *ap_pvsprintf(pool *p, const char *fmt, va_list ap)
Similar to ap_psprintf( ), except that varargs are used.

ap_indfind the first index of a character in a string

int ap_ind(const char *s, char c)
Returns the offset of the first occurrence of c in s, or -1 if c is not in s.

ap_rindfind the last index of a character in a string

int ap_rind(const char *s, char c)
Returns the offset of the last occurrence of c in s, or -1 if c is not in s.

A.6.12. Path, Filename, and URL Manipulation Functions

ap_ getparentsremove "." and ".." segments from a path

void ap_ getparents(char *name)
Removes ".." and "." segments
from a path, as specified in RFC 1808 (Relative Uniform Resource Locators). This is important not only for security but also to allow correct matching of URLs. Note that Apache should never be presented with a path containing such things, but it should behave correctly when it is.

ap_no2slashremove "//" from a path

void ap_no2slash(char *name)
Removes double slashes from a path. This is important for correct matching of URLs.

ap_make_dirstrmake a copy of a path with a trailing slash, if needed

char *ap_make_dirstr(pool *p, const char *path, int n)
Makes a copy of path guaranteed to end with a slash. It will truncate the path at the n th slash. Returns a pointer to the copy, which was allocated in the pool p.

ap_make_dirstr_parentmake the path of the parent directory

char * ap_make_dirstr_parent(pool *p, const char *s)
Make a new string in p with the path of s's parent directory with a trailing slash.

ap_make_dirstr_prefixcopy part of a path

char *ap_make_dirstr_prefix(char *d, const char *s, int n)
Copy the first n path elements from s to d or the whole of s if there are less than n path elements. Note that a leading slash counts as a path element.

ap_count_dirscount the number of slashes in a path

int ap_count_dirs(const char *path)
Returns the number of slashes in a path.

ap_chdir_filechange to the directory containing file

void ap_chdir_file(const char *file)
Performs a chdir( ) to the directory containing file. This is done by finding the last slash in the file and changing to the directory preceding it. If there are no slashes in the file, it attempts a chdir to the whole of file. It does not check that the directory is valid, nor that the chdir succeeds.

ap_unescape_urlremove escape sequences from a URL

int ap_unescape_url(char *url)
Converts escape sequences (%xx) in a URL back to the original character. The conversion is done in place. Returns 0 if successful, BAD_REQUEST if a bad escape sequence is found, and NOT_FOUND if %2f (which converts to "/" ) or %00 is found.

ap_construct_servermake the server part of a URL

char *ap_construct_server(pool *p, const char *hostname, int port, request_rec *r)
Makes the server part of a URL by appending :<port> to hostname if port is not the default port for the scheme used to make the request.

ap_construct_urlmake an HTTP URL

char *ap_construct_url(pool *p, const char *uri, const request_rec *r)
Makes a URL by prefixing the scheme used by r to the server name and port extracted from r and by appending uri. Returns a pointer to the URL.

ap_escape_path_segmentescape a path segment as per RFC 1808

char *ap_escape_path_segment(pool *p, const char *segment)
Returns an escaped version of segment, as per RFC 1808.

ap_os_escape_pathescape a path as per RFC 1808

char *ap_os_escape_path(pool *p, const char *path, int partial)
Returns an escaped version of path, per RFC 1808. If partial is nonzero, the path is assumed to be a trailing partial path (so that a "./" is not used to hide a ":").

ap_is_directorychecks whether a path refers to a directory

int ap_is_directory(const char *path)
Returns nonzero if path is a directory.

ap_make_full_pathcombines two paths into one

char *ap_make_full_path(pool *p, const char *path1, const char *path2)
Appends path2 to path1, ensuring that there is only one slash between them. Returns a pointer to the new path.

ap_is_urlchecks whether a string is in fact a URL

int ap_is_url(const char *url)
Returns nonzero if url is a URL. A URL is defined, for this purpose, to be "<any string of numbers, letters, +, -, or . (dot)>:<anything>."

ap_fnmatchmatch a filename

int ap_fnmatch(const char *pattern, const char *string, int flags)
Matches string against pattern, returning 0 for a match and FNM_NOMATCH otherwise. pattern consists of the following:

?
Match a single character.

*
Match any number of characters.

[...]
Represents a closure, as in regular expressions. A leading caret (^) inverts the closure.

\
If FNM_NOESCAPE is not set, removes any special meaning from next character.

flags is a combination of the following:

FNM_NOESCAPE
Treat a "\" as a normal character.

FNM_PATHNAME
*, ?, and [...] don't match "/.".

FNM_PERIOD
*, ?, and [...] don't match leading dots. "Leading" means either at the beginning of the string or after a "/" if FNM_PATHNAME is set.

ap_is_fnmatchcheck whether a string is a pattern

int ap_is_fnmatch(const char *pattern)
Returns 1 if pattern contains ?, *, or [...]; 0 otherwise.

ap_server_root_relativemake a path relative to the server root

char *ap_server_root_relative(pool *p, char *file)
If file is not an absolute path, append it to the server root, in the pool p. If it is absolute, simply return it (not a copy).

ap_os_canonical_filenameconvert a filename to its canonical form

char *ap_os_canonical_filename(pool *pPool, const char *szFile)
Figure

Returns a canonical form of a filename. This is needed because some operating systems will accept more than one string for the same file. Win32, for example, is case blind, ignores trailing dots and spaces, and so on.[85] This function is generally used before checking a filename against a pattern or other similar operations.

[85]In fact, exactly what Windows does with filenames is very poorly documented and is a seemingly endless source of security holes.

A.6.13. User and Group Functions

ap_uname2idconvert a username to a user ID (UID)

uid_t ap_uname2id(const char *name)
Figure

If name starts with a "#," returns the number following it; otherwise, looks it up using getpwnam( ) and returns the UID. Under Win32, this function always returns 1.

ap_ gname2idconvert a group name to a group ID (GID)

gid_t ap_ gname2id(const char *name)
Figure

If name starts with a "#," returns the number following it; otherwise, looks it up using getgrnam( ) and returns the GID. Under Win32, this function always returns 1.

A.6.14. TCP/IP and I/O Functions

ap_ get_virthost_addrconvert a hostname or port to an address

unsigned long ap_ get_virthost_addr(const char *hostname, short *ports)
Converts a hostname
of the form name[:port] to an IP address in network order, which it returns. *ports is filled in with the port number if it is not NULL. If name is missing or "*", INADDR_ANY is returned. If port is missing or "*", *ports is set to 0.

If the host has multiple IP addresses, an error message is printed, and exit( ) is called.

ap_ get_local_hostget the FQDN for the local host

char *ap_ get_local_host(pool *p)
Returns a pointer to the fully qualified domain name for the local host. If it fails, an error message is printed, and exit( ) is called.

ap_ get_remote_hostget client hostname or IP address

const char *ap_ get_remote_host(conn_rec *conn, void *dir_config, int type)
Returns the hostname or IP address (as a string) of the client. dir_config is the per_dir_config member of the current request or NULL. type is one of the following:

REMOTE_HOST
Returns the hostname or NULL (if it either couldn't be found or hostname lookups are disabled with the HostnameLookups directive).

REMOTE_NAME
Returns the hostname or, if it can't be found, returns the IP address.

REMOTE_NOLOOKUP
Similar to REMOTE_NAME, except that a DNS lookup is not performed. (Note that the name can still be returned if a previous call did do a DNS lookup.)

REMOTE_DOUBLE_REV
Does a double-reverse lookup (that is, look up the hostname from the IP address, then look up the IP address from the name). If the double reverse works and the IP addresses match, return the name; otherwise, return a NULL.

ap_send_fdcopy an open file to the client

long ap_send_fd(FILE *f, request_rec *r)
Copies the stream f to the client. Returns the number of bytes sent.

ap_send_fd_lengthcopy a number of bytes from an open file to the client

long ap_send_fd_length(FILE *f, request_rec *r, long length)
Copies no more than length bytes from f to the client. If length is less than 0, copies the whole file. Returns the number of bytes sent.

ap_send_fbcopy an open stream to a client

long ap_send_fb(BUFF *fb, request_rec *r)
Similar to ap_send_fd( ) except that it sends a BUFF * instead of a FILE *.

ap_send_fb_lengthcopy a number of bytes from an open stream to a client

long ap_send_fb_length(BUFF *fb, request_rec *r, long length)
Similar to ap_send_fd_length( ), except that it sends a BUFF * instead of a FILE *.

ap_send_mmapsend data from an in-memory buffer

size_t ap_send_mmap(void *mm, request_rec *r, size_t offset, size_t length)
Copies length bytes from mm+offset to the client. The data is copied MMAP_SEGMENT_SIZE bytes at a time, with the timeout reset in between each one. Although this can be used for any memory buffer, it is really intended for use with memory mapped files (which may give performance advantages over other means of sending files on some platforms).

ap_rwritewrite a buffer to the client

int ap_rwrite(const void *buf, int nbyte, request_rec *r)
Writes nbyte bytes from buf to the client. Returns the number of bytes written or -1 on an error.

ap_rputcsend a character to the client

int ap_rputc(int c, request_rec *r)
Sends the character c to the client. Returns c or EOF if the connection has been closed.

ap_rputssend a string to the client

int ap_rputs(const char *s, request_rec *r)
Sends the string s to the client. Returns the number of bytes sent or -1 if there is an error.

ap_rvputssend a list of strings to the client

int ap_rvputs(request_rec *r, ...)
Sends the NULL-terminated list of strings to the client. Returns the number of bytes sent or -1 if there is an error.

ap_rprintfsend a formatted string to the client

int ap_rprintf(request_rec *r, const char *fmt,...)
Formats the extra arguments according to fmt (as they would be formatted by printf( )) and sends the resulting string to the client. Returns the number of bytes sent or -1 if there is an error.

ap_rflushflush client output

int ap_rflush(request_rec *r)
Causes any buffered data to be sent to the client. Returns 0 on success or -1 on an error.

ap_setup_client_blockprepare to receive data from the client

int ap_setup_client_block(request_rec *r, int read_policy)
Prepares to receive (or not receive, depending on read_policy) data from the client, typically because the client made a PUT or POST request. Checks that all is well to do the receive. Returns OK if all is well or a status code if not. Note that this routine still returns OK if the request does not include data from the client. This should be called before ap_should_client_block( ).

read_policy is one of the following:

REQUEST_NO_BODY
Return HTTP_REQUEST_ENTITY_TOO_LARGE if the request has any body.

REQUEST_CHUNKED_ERROR
If the Transfer-Encoding is chunked, return HTTP_BAD_REQUEST if there is a Content-Length header or HTTP_LENGTH_REQUIRED if not.[86]

[86]This may seem perverse, but the idea is that by asking for a Content-Length, we are implicitly requesting that there is no Transfer-Encoding (at least, not a chunked one). Getting both is an error.

REQUEST_CHUNKED_DECHUNK
Handle chunked encoding in ap_ get_client_block( ), returning just the data.

REQUEST_CHUNKED_PASS
Handle chunked encoding in ap_ get_client_block( ), returning the data and the chunk headers.

ap_should_client_blockready to receive data from the client

int ap_should_client_block(request_rec *r)
Checks whether the client will send data and invites it to continue, if necessary (by sending a 100 Continue response if the client is HTTP 1.1 or higher). Returns 1 if the client should send data; 0 if not. ap_setup_client_block( ) should be called before this function, and this function should be called before ap_ get_client_block( ). This function should only be called once. It should also not be called until we are ready to receive data from the client.

ap_ get_client_blockread a block of data from the client

long ap_ get_client_block(request_rec *r, char *buffer, int bufsiz)
Reads up to bufsiz characters into buffer from the client. Returns the number of bytes read, 0 if there is no more data, or -1 if an error occurs. ap_setup_client_block( ) and ap_should_client_block( ) should be called before this. Note that the buffer should be at least big enough to hold a chunk-size header line (because it may be used to store one temporarily). Since a chunk-size header line is simply a number in hex, 50 bytes should be plenty.

ap_send_http_headersend the response headers to the client

void ap_send_http_header(request_rec *r)
Sends the headers (mostly from r->headers_out) to the client. It is essential to call this in a request handler before sending the content.

ap_send_sizesend a size approximately

void ap_send_size(size_t size, request_rec *r)
Sends size to the client, rounding it to the nearest thousand, million, or whatever. If size is -1, prints a minus
sign only.

A.6.15. Request-Handling Functions

ap_sub_req_lookup_urilook up a URI as if it were a request

request_rec *ap_sub_req_lookup_uri(const char *new_uri, const request_rec *r)
Feeds new_uri into
the system to produce a new request_rec, which has been processed to just before the point at which the request handler would be called. If the URI is relative, it is resolved relative to the URI of r. Returns the new request_rec. The status member of the new request_rec contains any error code.

ap_sub_req_lookup_filelook up a file as if it were a request

request_rec *ap_sub_req_lookup_file(const char *new_file, const request_rec *r)
Similar to ap_sub_req_lookup_uri( ) except that it looks up a file, so it therefore doesn't call the name translators or match against <Location> sections.

ap_run_sub_reqrun a subrequest

int ap_run_sub_req(request_rec *r)
Runs a subrequest prepared with ap_sub_req_lookup_file( ) or ap_sub_req_lookup_uri( ). Returns the status code of the request handler.

ap_destroy_sub_reqdestroy a subrequest

void ap_destroy_sub_req(request_rec *r)
Destroys a subrequest created with ap_sub_req_lookup_file( ) or ap_sub_req_lookup_uri( ) and releases the memory associated with it. Needless to say, you should copy anything you want from a subrequest before destroying it.

ap_internal_redirectinternally redirect a request

void ap_internal_redirect(const char *uri, request_rec *r)
Internally redirects a request to uri. The request is processed immediately, rather than returning a redirect to the client.

ap_internal_redirect_handlerinternally redirect a request, preserving handler

void ap_internal_redirect_handler(const char *uri, request_rec *r)
Similar to ap_internal_redirect( ), but uses the handler specified by r.

A.6.16. Timeout and Alarm Functions

ap_hard_timeoutset a hard timeout on a request

void ap_hard_timeout(char *name, request_rec *r)
Sets an alarm to go off
when the server's configured timeout expires. When the alarm goes off, the current request is aborted by doing a longjmp( ) back to the top level and destroying all pools for the request r. The string name is logged to the error log.

ap_keepalive_timeoutset the keepalive timeout on a request

void ap_keepalive_timeout(char *name, request_rec *r)
Works like ap_hard_timeout( ) except that if the request is kept alive, the keepalive timeout is used instead of the server timeout. This should normally be used only when awaiting a request from the client, and thus it is used only in http_protocol.c but is included here for completeness.

ap_soft_timeoutset a soft timeout on a request

void ap_soft_timeout(char *name, request_rec *r)
Similar to ap_hard_timeout( ), except that the request that is destroyed is not set. The parameter r is not used (it is there for historical reasons).

ap_reset_timeoutresets a hard or soft timeout to its original time

void ap_reset_timeout(request_rec *r)
Resets the hard or soft timeout to what it originally was. The effect is as if you had called ap_hard_timeout( ) or ap_soft_timeout( ) again.

ap_kill_timeoutclears a timeout

void ap_kill_timeout(request_rec *r)
Clears the current timeout on the request r.

ap_block_alarms( )temporarily prevents a timeout from occurring

void ap_block_alarms(void)
Temporarily blocks any pending timeouts. Protects critical sections of code that would leak resources (or would go wrong in some other way) if a timeout occurred during their execution. Calls to this function can be nested, but each call must be matched by a call to ap_unblock_alarms( ).

ap_unblock_alarms( )unblock a blocked alarm

void ap_unblock_alarms(void)
Remove a block placed by ap_block_alarms( ).

ap_check_alarmcheck alarm (Win32 only)

int ap_check_alarm(void)
Figure

Since Win32 has no alarm( ) function, it is necessary to check alarms "by hand." This function does that, calling the alarm function set with one of the timeout functions. Returns -1 if the alarm has gone off, the number of seconds left before the alarm does go off, or 0 if no alarm is set.

A.6.17. Configuration Functions

ap_pcfg_openfileopen a file as a configuration

configfile_t *ap_pcfg_openfile(pool *p, const char *name)
Opens
name as a file (using fopen( )), returning NULL if the open fails or a pointer to a configuration if the open succeeds.

ap_pcfg_open_customcreate a custom configuration

configfile_t *ap_pcfg_open_custom(pool *p, const char *descr, void *param,
int(*getch)(void *param), void *(*getstr) (void *buf, size_t bufsiz, void *param),
int(*close_func)(void *param))
Creates a custom configuration. The function getch( ) should read a character from the configuration, returning it or EOF if the configuration is finished. The function getstr( ) (if supplied — it can be NULL, in which case getch( ) will be used instead) should read a whole line into buf, terminating with NUL. It should return buf or NULL if the configuration is finished. close_func( ) (if supplied — it can be NULL) should close the configuration, returning 0 or more on success. All the functions are passed param when called.

ap_cfg_ getcread a character from a configuration

int ap_cfg_ getc(configfile_t *cfp)
Reads a single character from cfp. If the character is LF, the line number is incremented. Returns the character or EOF if the configuration has completed.

ap_cfg_ getlineread a line from a configuration, stripping whitespace

int ap_cfg_ getline(char *s, int n, configfile_t *cfp)
Reads a line (up to n characters) from cfp into s, stripping leading and trailing whitespace and converting internal whitespace to single spaces. Continuation lines (indicated by a backslash immediately before the newline) are concatenated. Returns 0 normally; 1 if EOF has been reached.

ap_cfg_closefileclose a configuration

int ap_cfg_closefile(configfile_t *cfp)
Close the configuration cfp. Return is less than zero on error.

ap_check_cmd_contextcheck if configuration cmd allowed in current context

const char *ap_check_cmd_context(cmd_parms *cmd, unsigned forbidden)
Checks whether cmd is permitted in the current configuration context, according to the value of forbidden. Returns NULL if it is or an appropriate error message if not. forbidden must be a combination of the following:

NOT_IN_VIRTUALHOST
Command cannot appear in a <VirtualHost> section.

NOT_IN_LIMIT
Command cannot occur in a <Limit> section.

NOT_IN_DIRECTORY
Command cannot occur in a <Directory> section.

NOT_IN_LOCATION
Command cannot occur in a <Location> section.

NOT_IN_FILES
Command cannot occur in a <Files> section.

NOT_IN_DIR_LOC_FILE
Shorthand for NOT_IN_DIRECTORY|NOT_IN_LOCATION|NOT_IN_FILES.

GLOBAL_ONLY
Shorthand for NOT_IN_VIRTUALHOST|NOT_IN_LIMIT|NOT_IN_DIR_LOC_FILE.

ap_set_file_slotset a file slot in a configuration structure

const char *ap_set_file_slot(cmd_parms *cmd, char *struct_ptr, char *arg)
Designed to be used in a command_rec to set a string for a file. It expects to be used with a TAKE1 command. If the file is not absolute, it is made relative to the server root. Obviously, the corresponding structure member should be a char *.

ap_set_flag_slotset a flag slot in a configuration structure.

const char * ap_set_flag_slot(cmd_parms *cmd, char *struct_ptr, int arg)
Designed to be used in a command_rec to set a flag. It expects to be used with a FLAG command. The corresponding structure member should be an int, and it will be set to 0 or 1.

ap_set_string_slotset a string slot in a configuration structure

const char *ap_set_string_slot(cmd_parms *cmd, char *struct_ptr, char *arg)
Designed to be used in a command_rec to set a string. It expects to be used with a TAKE1 command. Obviously, the corresponding structure member should be a char *.

ap_set_string_slot_lowerset a lowercase string slot in a configuration structure

const char *ap_set_string_slot_lower(cmd_parms *cmd, char *struct_ptr, char *arg)
Similar to ap_set_string_slot( ), except the string is made lowercase.

A.6.18. Configuration Information Functions

Modules may need to know how some things have been configured. These functions give access to that information.

ap_allow_optionsreturn options set with the Options directive

int ap_allow_options (request_rec *r)
Returns the option set for the request r. This is a bitmap composed of the bitwise OR of the following:

OPT_NONE
No options set.

OPT_INDEXES
The Indexes option.

OPT_INCLUDES
The Includes option.

OPT_SYM_LINKS
The FollowSymLinks option.

OPT_EXECCGI
The ExecCGI option.

OPT_INCNOEXEC
The IncludesNOEXEC option.

OPT_SYM_OWNER
The FollowSymLinksIfOwnerMatch option.

OPT_MULTI
The MultiViews option.

ap_allow_overridesreturn overrides set with the AllowOverride option

int ap_allow_overrides (request_rec *r)
Returns the overrides permitted for the request r. These are the bitwise OR of the following:

OR_NONE
No overrides are permitted.

OR_LIMIT
The Limit override.

OR_OPTIONS
The Options override.

OR_FILEINFO
The FileInfo override.

OR_AUTHCFG
The AuthConfig override.

OR_INDEXES
The Indexes override.

ap_auth_typereturn the authentication type for this request

const char *ap_auth_type (request_rec *r)
Returns the authentication type (as set by the AuthType directive) for the request r. Currently this should only be Basic, Digest, or NULL.

ap_auth_namereturn the authentication domain name

const char *ap_auth_name (request_rec *r)
Returns the authentication domain name (as set by the AuthName directive) for the request r.

ap_requiresreturn the require array

const array_header *ap_requires (request_rec *r)
Returns the array of require_line s that correspond to the require directive for the request r. require_line is defined as follows:

typedef struct {
    int method_mask;
    char *requirement;
} require_line;

method_mask is the bitwise OR of:

1 << M_GET
1 << M_PUT
1 << M_POST
1 << M_DELETE
1 << M_CONNECT
1 << M_OPTIONS
1 << M_TRACE
1 << M_INVALID

as set by a Limit directive.

ap_satisfiesreturn the satisfy setting

int ap_satisfies (request_rec *r)
Returns the setting of satisfy for the request r. This is one of the following:

SATISFY_ALL
Must satisfy all authentication requirements (satisfy all).

SATISFY_ANY
Can satisfy any one of the authentication requirements (satisfy any).

A.6.19. Server Information Functions

ap_ get_server_builtget the date and time Apache was built

const char *ap_ get_server_built(void)
Returns a string containing the
date and time the server was built. Since this uses the C preprocessor _ _DATE_ _ and _ _TIME_ _ variables, the format is somewhat system dependent. If the preprocessor doesn't support _ _DATE_ _ or _ _TIME_ _, the string is set to "unknown."

ap_ get_server_versionget the Apache version string

const char *ap_ get_server_version( )
Returns a string containing Apache's version (plus any module version strings that have been added).

ap_add_version_componentadd a module version string

void ap_add_version_component(const char *component)
Adds a string to the server-version string. This function only has an effect during startup, after which the version string is locked. Version strings should take the form module name / version number, e.g., MyModule/1.3. Most modules do not add a version string.

A.6.20. Logging Functions

ap_error_log2stderrmap stderr to an error log

void ap_error_log2stderr (server_rec *s)
Makes stderr the error
log for the server s. Useful when running a subprocess.

ap_log_errorlog an error

void ap_log_error (const char *file, int line, int level, const server_rec *s, 
const char *fmt, ...)
Logs an error (if level is higher than the level set with the LogLevel directive). file and line are only logged if level is APLOG_DEBUG. file and line are normally set by calling ap_log_error( ) like so:

ap_log_error(APLOG_MARK, APLOG_ERR, server_conf,"some error");

APLOG_MARK is a #define that uses _ _FILE_ _ and _ _LINE_ _ to generate the filename and line number of the call.

level is a combination of one of the following:

APLOG_EMERG
Unusable system.

APLOG_ALERT
Action to be taken immediately.

APLOG_CRIT
Critical conditions.

APLOG_ERR
Error conditions.

APLOG_WARNING
Warnings.

APLOG_NOTICE
Normal but significant condition.

APLOG_INFO
Informational.

APLOG_DEBUG
Debugging messages.

These can be optionally OR ed with the following:

APLOG_NOERRNO
Do not log errno.

APLOG_WIN32ERROR
Figure

On Win32, use GetLastError( ) instead of errno.

ap_log_reasonlog an access failure

void ap_log_reason (const char *reason, const char *file, request_rec *r)
Logs a message of the form "access to file failed for remotehost, reason: reason." The remote host is extracted from r. The message is logged with ap_log_error( ) at level APLOG_ERR.

A.6.21. Piped Log Functions

Apache provides functions to manage reliable piped logs. These are logs that are piped to another program. Apache restarts the program if it dies. This functionality is disabled if NO_RELIABLE_PIPED_LOGS is defined. The functions still exist and work, but the "reliability" is disabled.

ap_open_piped_logopen a piped log program

piped_log *ap_open_piped_log (pool *p, const char *program)
The program program is launched with appropriate pipes. program may include arguments.

ap_close_piped_logclose a piped log

void ap_close_piped_log (piped_log *pl)
Closes pl. Doesn't kill the spawned child.

ap_piped_log_write_fdget the file descriptor of a log pipe

int ap_piped_log_write_fd(piped_log *pl)
Returns the file descriptor of an open piped log.

A.6.22. Buffering Functions

Apache provides its own I/O buffering interface. This allows chunked transfers to be done transparently and hides differences between files and sockets under Win32.

ap_bcreatecreate a buffered stream

BUFF *ap_bcreate(pool *p, int flags)
Creates a new buffered stream in p. The stream is not associated with any file or socket at this point. flags are a combination of one of the following:

B_RD
Reading is buffered.

B_WR
Writing is buffered.

B_RDWR
Reading and writing are buffered.

B_SOCKET (optional)
The stream will be buffering a socket. Note that this flag also enables ASCII/EBCDIC translation on platforms that use EBCDIC (see ap_bsetflag( )).

ap_bpushfdset the file descriptors for a stream

void ap_bpushfd(BUFF *fb, int fd_in, int fd_out)
Sets the read file descriptor to fd_in and the write file descriptor to fd_out. Use -1 for file descriptors you don't want to set. Note that these descriptors must be readable with read( ) and writable with write( ).

ap_bpushhset a Win32 handle for a stream

void ap_bpushh(BUFF *fb, HANDLE hFH)
Figure

Sets a Win32 file handle for both input and output. The handle will be written with WriteFile( ) and read with ReadFile( ). Note that this function should not be used for a socket, even though a socket is a Win32 handle. ap_bpushfd( ) should be used for sockets.

ap_bsetoptset an option

int ap_bsetopt(BUFF *fb, int optname, const void *optval)
Sets the
option optname to the value pointed at by optval. There is currently only one option, which is the count of bytes sent to the stream,[87] set with BO_BYTECT. In this case, optval should point to a long. This function is used for logging and statistics and is not normally called by modules. Its main use, when it is called, is to zero the count after sending headers to a client. Returns 0 on success or -1 on failure.

[87]Not really an option, in our view, but we didn't name the function.

ap_bgetoptget the value of an option

int ap_bgetopt(BUFF *fb, int optname, void *optval)
Gets the
value of the option optname in the location pointed at by optval. The only supported option is BO_BYTECT (see ap_bsetopt( )).

ap_bsetflagset or clear a flag

int ap_bsetflag(BUFF *fb, int flag, int value)
If value is 0, clear
flag; otherwise, set it. flag is one of the following:

B_EOUT
Prevent further I/O.

B_CHUNK
Use chunked writing.

B_SAFEREAD
Force an ap_bflush( ) if a read would block.

B_ASCII2EBCDIC
Convert ASCII to EBCDIC when reading. Only available on systems that support EBCDIC.

B_EBCDIC2ASCII
Convert EBCDIC to ASCII when writing. Only available on systems that support EBCDIC.

ap_bgetflagget a flag's setting

int ap_bgetflag(BUFF *fb, int flag)
Returns 0 if flag is not set; nonzero otherwise. See ap_bsetflag( ) for a list of flags.

ap_bonerrorregister an error function

void ap_bonerror(BUFF *fb, void (*error) (BUFF *, int, void *),void *data)
When an error occurs on fb, error( ) is called with fb, the direction (B_RD or B_WR), and data.

ap_bnonblockset a stream to nonblocking mode

int ap_bnonblock(BUFF *fb, int direction)
direction is one of B_RD or B_WR. Sets the corresponding file descriptor to be nonblocking. Returns whatever fcntl( ) returns.

ap_bfilenoget a file descriptor from a stream

int ap_bfileno(BUFF *fb, int direction)
direction is one of B_RD or B_WR. Returns the corresponding file descriptor.

ap_breadread from a stream

int ap_bread(BUFF *fb, void *buf, int nbyte)
Reads up to nbyte bytes into buf. Returns the number of bytes read, 0 on end of file (EOF), or -1 for an error. Only reads the data currently available.

ap_bgetcget a character from a stream

int ap_bgetc(BUFF *fb)
Reads a single character from fb. Returns the character on success and returns EOF on error or end of file. If the EOF is the result of an end of file, errno will be zero.

ap_bgetsread a line from a stream

int ap_bgets(char *buff, int n, BUFF *fb)
Reads up to n-1 bytes into buff until an LF is seen or the end of file is reached. If LF is preceded by CR, the CR is deleted. The buffer is then terminated with a NUL (leaving the LF as the character before the NUL). Returns the number of bytes stored in the buffer, excluding the terminating NUL.

ap_blookcpeek at the next character in a stream

int ap_blookc(char *buff, BUFF *fb)
Places the next character in the stream in *buff, without removing it from the stream. Returns 1 on success, 0 on EOF, and -1 on error.

ap_bskiplfdiscard until an LF is read

int ap_bskiplf(BUFF *fb)
Discards input until an LF is read. Returns 1 on success, 0 on EOF, and -1 on an error. The stream must be read-buffered (i.e., in B_RD or B_RDWR mode).

ap_bwritewrite to a stream

int ap_bwrite(BUFF *fb, const void *buf, int nbyte)
Writes nbyte bytes from buf to fb. Returns the number of bytes written. This can only be less than nbyte if an error occurred. Takes care of chunked encoding if the B_CHUNK flag is set.

ap_bputcwrite a single character to a stream

int ap_bputc(char c, BUFF *fb)
Writes c to fb, returning 0 on success or -1 on an error.

ap_bputswrite a NUL-terminated string to a stream

int ap_bputs(const char *buf, BUFF *fb)
Writes the contents of buf up to, but not including, the first NUL. Returns the number of bytes written or -1 on an error.

ap_bvputswrite several NUL-terminated strings to a stream

int ap_bvputs(BUFF *fb,...)
Writes the contents of a list of buffers in the same manner as ap_bputs( ). The list of buffers is terminated with a NULL. Returns the total number of bytes written or -1 on an error. For example:

if(ap_bvputs(fb,buf1,buf2,buf3,NULL) < 0)
	...
ap_bprintfwrite formatted output to a stream

int ap_bprintf(BUFF *fb, const char *fmt, ...)
Write formatted output, as defined by fmt, to fb. Returns the number of bytes sent to the stream.

ap_vbprintfwrite formatted output to a stream

int ap_vbprintf(BUFF *fb, const char *fmt, va_list ap)
Similar to ap_bprintf( ), except it uses a va_list instead of "...".

ap_bflushflush output buffers

int ap_bflush(BUFF *fb)
Flush fb's output buffers. Returns 0 on success and -1 on error. Note that the file must be write-buffered (i.e., in B_WR or B_RDWR mode).

ap_bcloseclose a stream

int ap_bclose(BUFF *fb)
Flushes the output buffer and closes
the underlying file descriptors/handle/socket. Returns 0 on success and -1 on error.

A.6.23. URI Functions

Some of these functions use the uri_components structure:

typedef struct {
    char *scheme;     /* scheme ("http"/"ftp"/...) */
    char *hostinfo;   /* combined [user[:password]@]host[:port] */
    char *user;       /* username, as in http://user:passwd@host:port/ */
    char *password;   /* password, as in http://user:passwd@host:port/ */
    char *hostname;   /* hostname from URI (or from Host: header) */
    char *port_str;   /* port string (integer representation is in "port") */
    char *path;       /* The request path (or "/" if only scheme://host was 
                      /* given) */
    char *query;      /* Everything after a '?' in the path, if present */
    char *fragment;   /* Trailing "#fragment" string, if present */
    struct hostent *hostent;
    unsigned short port;	
                      /* The port number, numeric, valid only if
                      /* port_str != NULL */

    unsigned is_initialized:1;
    unsigned dns_looked_up:1;
    unsigned dns_resolved:1;
} uri_components;
ap_parse_uri_componentsdissect a full URI

int ap_parse_uri_components(pool *p, const char *uri, uri_components *uptr)
Dissects the URI uri into its components, which are placed in uptr. Each component is allocated in p. Any missing components are set to NULL. uptr->is_initialized is set to 1.

ap_parse_hostinfo_componentsdissect host:port

int ap_parse_hostinfo_components(pool *p, const char *hostinfo, uri_components 
*uptr)
Occasionally, it is necessary to parse host:port — for example, when handling a CONNECT request. This function does that, setting uptr->hostname, uptr->port_str, and uptr->port (if the port component is present). All other elements are set to NULL.

ap_unparse_uri_componentsconvert back to a URI

char *ap_unparse_uri_components(pool *p, const uri_components *uptr, unsigned flags)
Takes a filled-in uri_components, uptr, and makes a string containing the corresponding URI. The string is allocated in p. flags is a combination of none or more of the following:

UNP_OMITSITEPART
Leave out scheme://user:password@site:port.

UNP_OMITUSER
Leave out the user.

UNP_OMITPASSWORD
Leave out the password.

UNP_OMITUSERINFO
Shorthand for UNP_OMITUSER|UNP_OMITPASSWORD.

UNP_REVEALPASSWORD
Show the password (instead of replacing it with XXX).

ap_pgethostbynameresolve a hostname

struct hostent *ap_pgethostbyname(pool *p, const char *hostname)
Essentially does the same as the standard function gethostbyname( ), except that the result is allocated in p instead of being temporary.

ap_pduphostentduplicate a hostent structure

struct hostent *ap_pduphostent(pool *p, const struct hostent *hp)
Duplicates hp (and everything it points at) in the pool p.

A.6.24. Miscellaneous Functions

ap_child_terminatecause the current process to terminate

void ap_child_terminate(request_rec *r)
Makes this instance
of Apache terminate after the current request has completed. If the connection is a keepalive connection, keepalive is canceled.

ap_default_portreturn the default port for a request

unsigned short ap_default_port(request_rec *r)
Returns the default port number for the type of request handled by r. In standard Apache this is always an HTTP request, so the return is always 80; but in Apache-SSL, for example, it depends on whether HTTP or HTTPS is in use.

ap_is_default_portcheck whether a port is the default port

int ap_is_default_port(int port, request_rec *r)
Returns 1 if port is the default port for r or 0 if not.

ap_default_port_for_schemereturn the default port for a scheme

unsigned short ap_default_port_for_scheme(const char *scheme_str)
Returns the default port for the scheme scheme.

ap_http_methodreturn the scheme for a request

const char *ap_http_method(request_rec *r)
Returns the default scheme for the type of request handled by r. In standard Apache this is always an HTTP request, so the return is always http; but in Apache-SSL, for example, it depends on whether HTTP or HTTPS is in use.

ap_default_typereturns default content type

const char *ap_default_type(request_rec *r)
Returns the default content type for the request r. This is either set by the DefaultType directive or is text/plain.

ap_ get_basic_auth_pwget the password supplied for basic authentication

int ap_ get_basic_auth_pw(request_rec *r, const char **pw)
If a password has been set for basic authentication (by the client), its address is put in *pw. Otherwise, an appropriate error is returned:

DECLINED
If the request does not require basic authentication

SERVER_ERROR
If no authentication domain name has been set (with AuthName)

AUTH_REQUIRED
If authentication is required but has not been sent by the client

OK
If the password has been put in *pw

ap_ get_module_configget module-specific configuration information

void *ap_ get_module_config(void *conf_vector, module *m)
Gets the module-specific configuration set up by the module during startup. conf_vector is usually either the per_dir_config from a request_rec or module_config from a server_rec. See
Chapter 21 for more information.

ap_ get_remote_lognameget the login name of the client's user

const char *ap_ get_remote_logname(request_rec *r)
Returns the login name of the client's user if it can be found and if the facility has been enabled with the IdentityCheck directive. Returns NULL otherwise.

ap_ get_server_nameget the name of the current server

const char *ap_ get_server_name(const request_rec *r)
Gets the name of the server that is handling r. If the UseCanonicalName directive is on, then it returns the name configured in the configuration file. If UseCanonicalName is off, it returns the hostname used in the request — if there was one, or the configured name if not.

ap_ get_server_portget the port of the current server

unsigned ap_ get_server_port(const request_rec *r)
If UseCanonicalName is on, then returns the port configured for the server that is handling r. If UseCanonicalName is off, returns the port of the connection if the request included a hostname; otherwise the configured port.
[88]

[88]Though what practical difference this makes is somewhat mysterious to us.

ap_is_initial_reqis this the main request_rec?

int ap_is_initial_req(request_rec *r)
Returns 1 if r is the main request_rec (as opposed to a subrequest or internal redirect) and 0 otherwise.

ap_matches_request_vhostdoes a host match a request's virtual host?

int ap_matches_request_vhost(request_rec *r, const char *host, unsigned port)
Returns 1 if host:port matches the virtual host that is handling r; 0 otherwise.

ap_os_dso_loadload a dynamic shared object (DSO)

void *ap_os_dso_load(const char *path)
Loads the dynamic shared object (that is, DLL, shared library, etc.) specified by path. This has a different underlying implementation according to platform. The return value is a handle that can be used by other DSO functions. Returns NULL if path cannot be loaded.

ap_os_dso_unloadunload a dynamic shared object

void ap_os_dso_unload(void *handle)
Unloads the dynamic shared object described by handle.

ap_os_dso_symreturn the address of a symbol

void *ap_os_dso_sym(void *handle, const char *symname)
Returns the address of symname in the dynamic shared object referred to by handle. If the platform mangles symbols in some way (for example, by prepending an underscore), this function does the same mangling before lookup. Returns NULL if symname cannot be found or an error occurs.

ap_os_dso_errorget a string describing a DSO error

const char *ap_os_dso_error(void)
If an error occurs with a DSO function, this function returns a string describing the error. If no error has occurred, returns NULL.

ap_popendirdo an opendir( ) with cleanup

DIR *ap_popendir(pool *p, const char *name)
Essentially the same as the standard function opendir( ), except that it registers a cleanup function that will do a closedir( ). A DIR created with this function should be closed with ap_pclosedir( ) (or left for the cleanup to close). Apart from that, the standard functions should be used.

ap_pclosedirclose a DIR opened with ap_popendir( )

void ap_pclosedir(pool *p, DIR * d)
Does a closedir( ) and cancels the cleanup registered by ap_popendir( ). This function should only be called on a DIR created with ap_popendir( ).

ap_psignaturecreate the server "signature"

const char *ap_psignature(const char *prefix, request_rec *r)
Creates a "signature" for the server handling r. This can be nothing, the server name and port, or the server name and port hot-linked to the administrator's email address, depending on the setting of the ServerSignature directive. Unless ServerSignature is off, the returned string has prefix prepended.

ap_vformattergeneral-purpose formatter

int ap_vformatter(int (*flush_func)(ap_vformatter_buff *), 
ap_vformatter_buff *vbuff, const char *fmt, va_list ap)
Because Apache has several requirements for formatting functions (e.g., ap_bprintf( ), ap_psprintf( )) and it is actually not possible to implement them safely using standard functions, Apache has its own printf( )-style routines. This function is the interface to them. It takes a buffer-flushing function as an argument and an ap_vformatter_buff structure, which looks like this:

typedef struct {
    char *curpos;
    char *endpos;
} ap_vformatter_buff;

It also takes the usual format string, fmt, and varargs list, ap. ap_vformatter( ) fills the buffer (at vbuff->curpos) until vbuff->curpos == vbuff->endpos; then flush_func( ) is called with vbuff as the argument. flush_func( ) should empty the buffer and reset the values in vbuff to allow the formatting to proceed. flush_func( ) is not called when formatting is complete (unless it happens to fill the buffer). It is the responsibility of the function that calls ap_vformatter( ) to finish things off.

Since flush_func( ) almost always needs more information than that found in vbuff, the following ghastly hack is frequently employed. First, a structure with an ap_vformatter_buff as its first element is defined:[89]

[89]Of course, if you don't mind the hack being even more ghastly, it doesn't have to be first.

struct extra_data {
    ap_vformatter_buff vbuff;
    int some_extra_data;
    ...
};

Next, the printf( )-style routine calls ap_vformatter with an instance of this structure:

    struct extra_data mine;
    ...
    mine.some_extra_data=123;
    ap_vformatter(my_flush,&mine.vbuff,fmt,ap);
    ...

Finally, my_flush( ) does this:

API_EXPORT(int) my_flush(ap_vformatter_buff *vbuff)
{
    struct extra_data *pmine=(struct extra_data *)vbuff;
    assert(pmine->some_extra_data == 123);
    ...

As you can probably guess, we don't entirely approve of this technique, but it works.

ap_vformatter( ) does all the usual formatting, except that %p has been changed to %pp, %pA formats a struct in_addr * as a.b.c.d , and %pI formats a struct sockaddr_in * as a.b.c.d:port. The reason for these strange-looking formats is to take advantage of gcc 's format-string checking, which will make sure a %p corresponds to a pointer.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.