Index: CHANGES
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/CHANGES,v
retrieving revision 1.1.1.1
diff -u -u -r1.1.1.1 CHANGES
--- CHANGES	29 Jul 2003 20:19:10 -0000	1.1.1.1
+++ CHANGES	13 Apr 2006 20:54:33 -0000
@@ -1,3 +1,869 @@
+Changes with IHS 6.1
+
+  *) Add module tracking support for the log-transaction hook.  This
+     works in conjunction with mod_status and diagnostic modules to
+     indicate when a module has hung or crashed in the log-transaction
+     hook.
+     (IBM)
+
+  *) htdbm: Fix crash processing -d option in 64-bit mode on HP-UX.
+     [Jeff Trawick]
+     (Backport from Apache 2.3-dev for 359373)
+
+  *) apr-util SDBM support: Fix mishandling of record deletion on
+     some 64-bit platforms.
+     (IBM, for 359373)
+
+  *) Default handler: Don't return output filter apr_status_t values.
+     PR 31759.  [Jeff Trawick, Ruediger Pluem, Joe Orton]
+     (Backport from Apache 2.0.56-dev for PK22485)
+
+  *) Fix handling of a premature EOF with the FILE bucket; a new bucket
+     is not inserted for each attempt to read past EOF.  PR 34708.
+     [Jeff Trawick, Joe Orton]
+     (Backport from apr-util 0.9.7 for PK22485)
+
+Changes with IHS 6.0.2.9
+
+  *) mod_ext_filter: Prevent deadlock of child process due to pipe
+     inheritance.
+     (IBM, for PK20184)
+
+  *) Ensure that the proper status line is written to the client, fixing
+     incorrect status lines caused by filters which modify r->status without
+     resetting r->status_line, such as the built-in byterange filter.
+     [Jeff Trawick]
+     (Backport from Apache 2.2.1-dev for PK20050)
+
+  *) Apache.exe -V/apachectl -V now displays ids of vulnerabilities
+     which have been fixed in the installed level of IBM HTTP Server.
+     (IBM)
+
+  *) mod_speling: Stop crashing with certain non-file requests.  [Jeff Trawick]
+     (Backport from Apache 2.0.56-dev for PK17802; affects WebSphere
+     requests)
+
+Changes with IHS 6.0.2.7
+
+  *) mod_include: Fix bug which could truncate variable expansions
+     of N*64 characters by one byte.  PR 32985.  [Joe Orton]
+     (Backport from Apache 2.0.53 for PK15553)
+
+  *) Fix mod_include's expression parser to recognize strings correctly
+     even if they start with an escaped token.  [Andr Malo]
+     (Backport from Apache 2.0.49 for PK15553)
+
+  *) Backport major overhaul of mod_include's filter parser from 2.1.
+     The new parser code is expected to be more robust and should
+     catch all of the edge cases that were not handled by the previous one.
+     The 2.1 external API changes were hidden by a wrapper which is
+     expected to keep the API backwards compatible.  [Andr Malo]
+     (Backport from Apache 2.0.49 for PK15553)
+  
+  *) complain via error_log when mod_include's INCLUDES filter is
+     enabled, but the relevant Options flag allowing the filter to run
+     for the specific resource wasn't set, so that the filter won't
+     silently get skipped. next remove itself, so the warning will be
+     logged only once [Stas Bekman, Jeff Trawick, Bill Rowe]
+     (Backport from Apache 2.0.49 for PK15553)
+
+  *) mod_include no longer allows an ETag header on 304 responses.
+     PR 19355. [Geoffrey Young , Andr Malo]
+     (Backport from Apache 2.0.49 for PK15553)
+
+  *) SECURITY: CVE-2005-3352 (cve.mitre.org)
+     mod_imap: Escape untrusted referer header before outputting in HTML
+     to avoid potential cross-site scripting.  Change also made to
+     ap_escape_html so we escape quotes.  Reported by JPCERT.
+     [Mark Cox]
+     (Backport from Apache 2.0.56-dev)
+
+  *) Do not remove the Content-Length header for a proxied HEAD
+     request.  This allows Windows Update to work through an IHS proxy.
+     (Backport from Apache 2.3 PR 18757 for APAR PK13858) 
+
+  *) Avoid accessing potentially-invalid storage in
+     apr_tokenize_to_argv(), resolving a warning from Purify
+     which had no known customer impact.
+     (Backport from APR 0.9.8-dev; not mentioned in APR CHANGES)
+
+  *) Clear port field before calling getnameinfo(), resolving
+     a warning from Purify which had no known customer impact.
+     (Backport from APR 0.9.8-dev; not mentioned in APR CHANGES)
+
+Changes with cumulative e-fix PK13230 for 2.0.42 and 2.0.47
+
+  *) Change apr_proc_create() to avoid passing NULL to execve(), 
+     resolving a problem running with Purify which had no known
+     customer impact.
+     (Backport from APR 0.9.8-dev; not mentioned in APR CHANGES)
+
+Changes with IHS 6.0.2.3
+
+  *) Avoid accessing memory prior to start of buffer in mod_mime_magic,
+     resolving a warning from Purify which had no known customer
+     impact.
+     (Backport from Apache 2.1-dev)
+
+  *) SECURITY: CVE-2005-2970 (cve.mitre.org)
+     worker MPM: Fix a memory leak which can occur after an aborted
+     connection in some limited circumstances.  [Greg Ames]
+     (Backport from Apache 2.0.55 for APAR PK13066)
+
+  *) SECURITY: CAN-2005-2491 (cve.mitre.org): 
+     Fix integer overflows in PCRE in quantifier parsing which could
+     be triggered by a local user through use of a carefully-crafted 
+     regex in an .htaccess file.  [Philip Hazel]
+     (Backport from Apache 2.0.55 for APAR PK11929)
+
+  *) SECURITY: CAN-2005-2728 (cve.mitre.org)
+     Fix cases where the byterange filter would buffer responses
+     into memory.  PR 29962.  [Joe Orton]
+     (Backport from Apache 2.0.55 for APAR PK11929)
+     
+  *) misc/unix/errorcodes.c (native_strerror): Gracefully handle
+    strerror() returning NULL on Solaris.
+    [Joe Orton]
+    (Backport from Apache 2.0.52)
+
+Changes with IHS 6.0.2.1
+Changes with cumulative e-fix PK07831 for 2.0.42 and 2.0.47
+
+  *) SECURITY: CAN-2005-2088
+     proxy HTTP: If a response contains both Transfer-Encoding and a
+     Content-Length, remove the Content-Length and don't reuse the
+     connection, stopping some HTTP Request smuggling attacks.
+     core: If a request contains both Transfer-Encoding and a Content-Length,
+     remove the Content-Length, stopping some HTTP Request smuggling attacks.
+     (Similar to Apache 2.0.55)
+
+  *) SECURITY: CAN-2005-2088 (cve.mitre.org)
+     core: If a request contains both Transfer-Encoding and Content-Length
+     headers, remove the Content-Length, mitigating some HTTP Request
+     Splitting/Spoofing attacks.  [Paul Querna, Joe Orton]
+     (Backport from Apache 2.0.55)
+
+  *) mod_cgid: Fix buffer overflow processing ScriptSock directive.
+     [Steve Kemp <steve steve.org.uk>]
+     (Backport from Apache 2.1.6)
+
+  *) Pass environment variables through to piped loggers and start
+     them via the shell, resolving regressions since 1.3.  PR 28815
+     [Ken Coar, Jeff Trawick]
+     (Unix-only backport from Apache 2.1.1)
+
+  *) Add command type APR_SHELLCMD_ENV for creating a process
+     which is started by the shell and which inherits the parent's
+     environment variables.  [Jeff Trawick]
+     (Backport from Apache 2.0.50)
+
+  *) Support APR_SO_SNDBUF and APR_SO_RCVBUF on Windows.  PR 32177.
+     [Sim <sgobbi datamanagement.it>, Jeff Trawick]
+     (Backport from Apache 2.0.55 for PMR 05913,005,000)
+
+  *) Restore support for SHA1 passwords in apr_validate_password.
+     PR 17343.  [Joe Orton]
+     (Backport from Apache 2.0.50)
+
+  *) Add mod_status hook to allow modules to add to the mod_status
+     report.  [Joe Orton]
+     (Backport from Apache 2.0.49)
+
+  *) mod_mime_magic: Handle CRLF-format magic files so that it works with
+     the default installation on Windows.  [Jeff Trawick]
+     (Backport from Apache 2.1.5)
+
+  *) mod_proxy: Handle client-aborted connections correctly.  PR 32443.
+     [Janne Hietamki, Joe Orton]
+     (Backport from Apache 2.0.53)
+
+  *) Start keeping track of time-taken-to-process-request again for
+     mod_status if ExtendedStatus is enabled. [Jim Jagielski]
+     (Backport from Apache 2.0.53)
+
+  *) worker MPM: Change log level of apr_proc_mutex_unlock error message
+     from emergency to debug if it occurs during a restart, where it is
+     harmless.
+     (Backport from Apache 2.0.55, where it was unmentioned in CHANGES,
+     for PMR 03649,999,624)
+
+  *) Remember an authenticated user during internal redirects if the
+     redirection target is not access protected and pass it
+     to scripts using the REDIRECT_REMOTE_USER environment variable.
+     PR 10678, 11602.  [Andr Malo]
+     (Backport from Apache 2.0.48, for PMR 43476,999,760)
+
+  *) EBCDIC: Handle chunked input from client or, with proxy, origin
+     server.  [Jeff Trawick]
+     (Backport from Apache 2.0.55)
+
+  *) Support the suppress-error-charset setting, as with Apache 1.3.x.
+     PR 31274.  [Jeff Trawick]
+     (Backport from Apache 2.0.55, for APAR PK05957)
+
+  *) Prevent hangs of child processes when writing to piped loggers at
+     the time of graceful restart.  PR 26467.  [Jeff Trawick]
+     (Backport from Apache 2.0.55, for APAR PK05830)
+
+  *) worker mpm: don't take down the whole server for a transient
+     thread creation failure. PR 34514 [Greg Ames]
+     (backport from Apache 2.0.55 for PK03603)
+
+Changes with IHS 6.0.2
+
+  *) Fix storage corruption problem with mod_userdir+suexec processing.
+     PR 34588.
+     (Backport from Apache 2.1.5; omitted from Apache CHANGES)
+
+  *) Fix memory leak in the cache handling of mod_rewrite. PR 27862.
+     [chunyan sheng , Andr Malo]
+     (Backport from Apache 2.0.51)
+
+  *) mod_status showmodule support: Print "_" for module field if
+     unknown.  Print module name when overall state is READ.
+     (IBM)
+
+  *) Fix problem with default service name on Windows with 6.0.1.
+     Now reverted back to 6.0 for life of 6.0.x release, so that 
+     "apache.exe -k start" can still work after applying updates.
+     (IBM)
+     
+  *) Log an error message on Windows if a Listen directive is not 
+     qualified with either an IPv4 or an IPv6 address.  (IHS 6.0.2
+     and above only)
+     (IBM)
+
+  *) mod_rewrite: use buffered I/O to improve performance with large
+     RewriteMap txt: files.  [Greg Ames]
+     (Backport from Apache 2.0.55 for PK04429)
+  
+  *) dbmmanage: Select the database format which is accepted by IBM
+     HTTP Server (SDBM).
+     (IBM)
+
+  *) Set RH ("request handler") variable to indicate which module handled 
+     or failed the request.  Example value: "(mod_cgid.c/500/handler)".  
+     Log this in access log with %{RH}e.  Implemented for common failure
+     points.  Requires ExtendedStatus On.
+     (IBM)
+
+  *) Fix a servlet timeout when a POST response page contains SSI tags.
+     [Greg Ames] (Backport from Apache 2.1)
+
+  *) AIX: Change default setting of LDR_CNTRL in envvars file to reserve
+     6 segments of heap instead of 8.  This avoids envvars changes for
+     users with third-party modules or crypto drivers which need more
+     shared memory.
+     (IBM)
+
+  *) Fix Windows CompContext buff size miscalculation
+     [Allan Edwards] (Backport from Apache 2.1.4)
+
+  *) Enabled IPv6 builds on Windows for IHS 6.0.2 and above
+     (IBM)
+
+  *) Add ReceiveBufferSize directive to control the TCP receive buffer.
+     [Eric Covener <covener gmail.com>]
+     (Backport from Apache 2.0.56-dev)
+
+Changes with cumulative e-fix PK01070 for 2.0.42 and 2.0.47
+
+  *) mod_fastcgi: Add compatibility with modules which bypass normal file
+     handling, such as the WebSphere plug-in.
+     (IBM)
+
+  *) Rename zlib symbols exported by mod_deflate.so to avoid collisions
+     when 3rd-party modules use zlib.
+     (IBM)
+
+  *) Track the active module for selected hooks when ExtendedStatus is set
+     to On.  This can be displayed with mod_status by adding the showmodule
+     query arg (e.g., "http://www.example.com/server-status/?showmodule").
+     This support will also be exploited by features of the ihsdiag
+     package.
+     (IBM)
+
+  *) Rewrite macros APR_OPTIONAL_HOOK and APR_REGISTER_OPTIONAL_FN to avoid 
+     calling a function through a function pointer of incompatible type, 
+     which is not conformant C99 code (by section 6.3.2.3 para 8) and 
+     triggers a warning from gcc 3.4 (default compiler RHEL4). 
+     (Backport from Apache 2.0.49)
+
+Changes with IHS 6.0.1
+
+  *) SECURITY [CAN-2003-0020]: Escape arbitrary data before writing
+     into the errorlog.  [Andr Malo]
+     (Backport from Apache 2.0.49)
+  
+  *) Win32: Do not fail service install if another service is running
+     on the IHS listening port.
+     (Backport from Apache 2.1)
+
+Changes with IHS 6.0.0.2
+
+  *) Remove 2Gb log file size restriction on some 32-bit platforms.
+     PR 13511.  [Joe Orton]
+     (Backport from Apache 2.0.50)
+
+  *) Add APR_LARGEFILE flag to allow opening files with the
+     O_LARGEFILE flag; not recommended for general use, see
+     include/apr_file_io.h.  [Joe Orton]
+     (Backport from Apache 2.0.50)
+
+  *) Remove compiled-in upper limit on LimitRequestFieldSize.
+     [Bill Stoddard]
+     (Backport from Apache 2.0.53)
+
+  *) mod_cache: CacheDisable will only disable the URLs it was meant to
+     disable, not all caching. PR 31128.
+     [Edward Rudd <eddie omegaware.com>, Paul Querna]
+     (Backport from Apache 2.0.53)
+
+  *) mod_cache: Try to correctly follow RFC 2616 13.3 on validating stale
+     cache responses.  [Justin Erenkrantz]
+     (Backport from Apache 2.0.53)
+
+  *) proxy HTTP: Rework the handling of request bodies to handle
+     chunked input and input filters which modify content length, and
+     avoid spooling arbitrary-sized request bodies in memory.
+     PR 15859.  [Jeff Trawick]
+     (Backport from Apache 2.0.55, for PQ98957)
+
+  *) Add apr_temp_dir_get() for getting the most suitable temp directory
+     [Mike Pilato <cmpilato@collab.net>, Thom May]
+     (Backport from Apache 2.0.52)
+
+  *) Fix memory leak in handling of request bodies during reverse
+     proxy operations.  PR 24991. [Larry Toppi <larry.toppi citrix.com>]
+     (Backport from Apache 2.0.49)
+
+  *) mod_log_config: Fix %b log format to write really "-" when 0 bytes
+     were sent (e.g. with 304 or 204 response codes).  [Astrid Keler]
+     (Backport from Apache 2.0.48)
+
+  *) mod_proxy: Respect errors reported by pre_connection hooks.
+     [Jeff Trawick]
+     (Backport from Apache 2.0.53 for defect 247084; HTTP path only)
+
+  *) mod_cgid: Catch configuration problem where two web server instances
+     share same ServerRoot but admin forgot to use ScriptSock.
+     [Jeff Trawick]
+     (Backport from Apache 2.1.2)
+
+  *) worker MPM: Fix a problem which could cause httpd processes to
+     remain active after shutdown.  [Jeff Trawick]
+     (Backport from Apache 2.0.54 for PQ97712)
+
+  *) modules/filters/mod_deflate.c (deflate_out_filter): Check explicitly
+     for a 304 or 204 response rather than a brigade which begins with EOS,
+     to correctly handle such responses when generated by a CGI script.
+     Don't alter the headers for this case either. [Joe Orton]
+     (Backport from Apache 2.1-dev)
+
+  *) Sync deflate_out_filter function of mod_deflate with Apache 2.1-dev 
+     revision 1.58 to pick up fixes to handle empty bucket brigades being 
+     passed in. 
+     (Backport from Apache 2.1-dev)
+
+Changes with cumulative e-fix PQ94389 for 2.0.42 and 2.0.47
+
+  *) Add fatal exception hook for use by diagnostic modules.  The hook
+     is only available if the --enable-exception-hook configure parm 
+     is used and the EnableExceptionHook directive has been set to 
+     "on".  [Jeff Trawick]
+     (Backport from Apache 2.0.49)
+
+  *) SECURITY: CAN-2004-0942 (cve.mitre.org)
+     Fix for memory consumption DoS in handling of MIME folded request
+     headers.  [Joe Orton]
+     (Backport from Apache 2.0.53 for PQ97125)
+
+  *) Log the client IP address when an error occurs disabling nagle on a
+     connection, but log at a severity of debug since this error
+     generally means that the connection was dropped before data was
+     sent.  Log the client IP address when reporting errors in the core
+     output filter.  [Jeff Trawick]
+     (Backport from Apache 2.1.1)
+
+Changes with IHS 6.0
+
+  *) Fix Expires handling in mod_cache.  [Justin Erenkrantz]
+     (Backport from Apache 2.0.53)
+
+  *) Alter mod_expires to run at a different filter priority to allow
+     proper Expires storage by mod_cache.  [Justin Erenkrantz]
+     (Backport from Apache 2.0.53)
+
+  *) Unix MPMs: Shut down the server more quickly when child processes are
+     slow to exit.  [Joe Orton, Jeff Trawick]
+     (Backport from Apache 2.0.54)
+
+  *) mod_rewrite: Handle per-location rules when r->filename is unset.
+     Previously this would segfault or simply not match as expected,
+     depending on the platform.  [Jeff Trawick]
+     (Backport from Apache 2.0.53)
+
+  *) mod_mem_cache: Fixed race condition causing segfault because of memory being
+     freed twice, or reused after being freed. 
+     [J. Clar, W. Stoddard, G. Ames]
+     (Backport from 2.0.52; cumulative e-fix PQ94086 had an alternate fix for 
+     this problem)
+
+  *) SECURITY: CAN-2004-0809 (cve.mitre.org)
+     mod_dav_fs: Fix a segfault in the handling of an indirect lock
+     refresh.  PR 31183.  [Joe Orton]
+     (Backport from Apache 2.0.51 for PQ94389)
+
+Changes with cumulative e-fix PQ94086 for 2.0.42 and 2.0.47
+
+  *) SECURITY: CAN-2004-0786 (cve.mitre.org)
+     Fix an input validation issue in apr-util which could be
+     triggered by malformed IPv6 literal addresses.  [Joe Orton]
+     (Backport from Apache 2.0.51)
+
+  *) SECURITY: CAN-2004-0747 (cve.mitre.org)
+     Fix buffer overflow in expansion of environment variables in
+     configuration file parsing.  [Andr Malo]
+     (Backport from Apache 2.0.51)
+
+  *) Fix off-by-one error in ap_rgetline_core() NUL-termination.
+     (Backport from Apache 2.0.51; unmentioned in Apache CHANGES)
+
+  *) Fix regression from 1.3:
+     There's a new optional flag for the Header directive
+     ('always'), which keeps the former ErrorHeader functionality.
+     PR: 28657 
+
+     Allow conditional RequestHeader directives.
+     PR: 27951
+     Basically submitted by: vincent gryzor.com (Vincent Deffontaines)
+     (Backport mod_headers rev 1.42.2.7 from Apache 2.0.50 and 
+     1.42.2.6 from Apache 2.0.51)
+
+  *) mod_deflate: Fix memory consumption (which was proportional to the
+     response size).  PR 29318.  [Joe Orton]
+     (Backport from Apache 2.0.50)
+
+  *) mod_autoindex: Don't truncate the directory listing if a stat()
+     call fails (for instance on a >2Gb file).  PR 17357.
+     [Joe Orton]
+     (Backport from Apache 2.0.51)
+
+  *) Prevent CGI script output which includes a Content-Range header
+     from being passed through the byterange filter.  [Joe Orton]
+     (Backport from Apache 2.0.51)
+
+  *) mod_headers no longer crashes if an empty header value should
+     be added.  [Andr Malo]
+     (Backport from Apache 2.0.50)
+
+  *) mod_log_config: Fix corruption of buffered logs with threaded
+     MPMs.  PR 25520.  [Jeff Trawick]
+     (Backport from Apache 2.0.49)
+
+  *) mod_disk_cache: Implement binary format for on-disk header files.
+     [Brian Akins <bakins web.turner.com>, Justin Erenkrantz]
+     (Backport from Apache 2.0.51)
+
+  *) mod_disk_cache: Optimize network performance of disk cache subsystem by
+     allowing zero-copy (sendfile) writes and other miscellaneous fixes.
+     [Justin Erenkrantz]
+     (Backport from Apache 2.0.51)
+
+  *) mod_cache, mod_disk_cache, mod_mem_cache: Refactor cache modules, and
+     switch to the provider API instead of hooks.  [Justin Erenkrantz]
+     (Backport from Apache 2.0.51)
+
+  *) Change ihs_insert_error_filter hook to insert_error_filter to
+     sync up with Apache 2.0.49 and minimize IHS differences. 
+     [Greg Ames] 
+     
+  *) Fix the handling of URIs containing %2F when AllowEncodedSlashes
+     is enabled.  Previously, such urls would still be rejected with
+     404.  [Jeff Trawick, Bill Stoddard]
+     (Backport from Apache 2.0.52)
+
+  *) Win32: Port Jeff Trawick's change to add two new proc attributes 
+     to improve diagnostics for apr_proc_create() failures.
+     [Bill Stoddard] (Backport from Apache 2.1-dev)
+
+  *) Win32: apache -k start|restart|install|config can leave stranded
+     piped logger processes (eg, rotatelogs.exe) due to improper
+     server shutdown on these code paths.
+     [Bill Stoddard] (Backport from Apache 2.0.51)
+
+  *) WinNT MPM: Fix a broken log message at termination.  PR 28063.
+     [Eider Oliveira <eider bol.com.br>]
+     (Backport from Apache 2.0.51)
+
+  *) The default Windows service name used by Apache.exe now matches
+     the service name used by the installer, so the -n SERVICENAME
+     option is not necessary when starting the service from the
+     command line.  [IBM]
+
+  *) Move dynacache.dll to the bin directory.  [Allan Edwards]
+
+  *) PQ92124: HTTP POSTs fail or hang when Afpa is enabled
+     Updated afpa.sys [Allan Edwards]
+
+  *) fix runtime crash by adding OVERLAPPED to afpa's copy of apr_socket_t
+     also move iol to end of structure [Allan Edwards]
+
+  *) mod_status: Report total CPU time accurately when using a threaded
+     MPM.  PR 23795.  [Jeff Trawick]
+     (Backport from Apache 2.0.49)
+
+  *) Win32: Fix bug in apr_socket_sendfile that interferred with
+     LSPs. PR 23982 [Jan Bilek, Bill Stoddard]
+     (Backport from APR 0.9.5-dev)
+
+Changes with cumulative e-fix PQ90698 for 2.0.42 and 2.0.47
+
+  *) SECURITY: CAN-2004-0493 (cve.mitre.org)
+     Close a denial of service vulnerability identified by Georgi
+     Guninski which could lead to memory exhaustion with certain
+     input data.  [Jeff Trawick]
+     (Backport from Apache 2.0.50)
+
+  *) Add -l option to rotatelogs to let it use local time rather than
+     UTC.  PR 24417.  [Ken Coar, Uli Zappe <uli ritual.org>]
+     (Backport from Apache 2.0.52)
+
+  *) Pass environment variables through to piped loggers, resolving
+     a regression since 1.3.  [Ken Coar, Jeff Trawick]
+     (Backport from Apache 2.1.1)
+
+  *) <VirtualHost myhost> now applies to all IP addresses for myhost
+     instead of just the first one reported by the resolver.  This
+     corrects a regression since 1.3.  [Jeff Trawick]
+     (Backport from Apache 2.0.50)
+
+  *) Fix mod_deflate to handle zero length responses (e.g. 304s) 
+     [Allan Edwards] 
+     (Backport from Apache 2.1-dev)
+
+  *) network_io/unix/sockaddr.c (apr_getnameinfo): Use apr_uint32_t to
+     fix build on platforms without uint32_t; use struct sockaddr_in rather
+     than struct apr_sockaddr_t. [Joe Orton](Back port from APR_0_9_BRANCH)
+
+  *) PQ89510 on Win32: PDF files may not properly render with acrobat 
+     reader when served over an SSL connection. This is only a problem
+     with Apache/IBM HTTP Server on Windows. 
+
+  *) Fix handling of IPv6 numeric strings in mod_proxy.  [Jeff Trawick]
+     (Back port from Apache 2.0.50)
+
+  *) Don't assume getnameinfo() can handle IPv4-mapped IPv6 addresses
+     on any platforms.
+     [Jeff Trawick, Joe Orton, Colm MacCarthaigh <colm stdlib.net>]
+     (Back port from Apache 2.0.50)
+
+Changes with IHS 2.0.47.1
+
+  *) mod_expires: Initialize ExpiresDefault to NULL instead of "" to
+     avoid reporting an Internal Server error if it is used without
+     having been set in the httpd.conf file. PR: 23748, 24459
+     [Andre Malo, Liam Quinn  <liam htmlhelp.com>]
+     (Back port from Apache 2.0.49)
+
+  *) Prevent Win32 pool corruption at startup 
+     [Allan Edwards] (Back port from Apache 2.0.51)
+
+  *) Ensure that lines in the request which are too long are 
+     properly terminated before logging.
+     [Tsurutani Naoki <turutani scphys.kyoto-u.ac.jp>]
+     (Backport from Apache 2.0.50)
+     (CMVC defect 198608)
+
+Changes with cumulative e-fix PQ85834 for 2.0.42 and 2.0.47
+
+  *) core_output_filter: Fix bug that could result in sending
+     garbage over the network when module handlers construct
+     bucket brigades containing multiple file buckets all referencing
+     the same open file descriptor. [Bojan Smojver]
+     (Back port from Apache 2.0.50)
+ 
+  *) Fix memory corruption problem with ap_custom_response() function.
+     The core per-dir config would later point to request pool data
+     that would be reused for different purposes on different requests.
+     [Jeff Trawick, based on an old 1.3 patch submitted by Will Lowe]
+     (Back port from Apache 2.0.50)
+
+  *) mod_dav: Fix a problem that could cause crashes when manipulating
+     locks on some platforms.  [Jeff Trawick]
+     (Back port from Apache 2.0.50)
+
+  *) Fix crash when Apache was started with no Listen directives.
+     [Michael Corcoran <mcorcoran warpsolutions.com>]
+     (Back port from Apache 2.0.50)
+
+  *) mod_cgid: Fix storage corruption caused by use of incorrect pool.
+     [Jeff Trawick]
+     (Back port from Apache 2.0.49)
+
+  *) Threaded MPMs for Unix and Win32: Add support for ThreadStackSize 
+     directive (previously NetWare-only) to override default thread 
+     stack size for threads which handle client connections.  Required 
+     for some third-party modules on platforms with small default 
+     thread stack size.  [Jeff Trawick]
+     (Back port from Apache 2.1.1)
+
+  *) Add apr_threadattr_stacksize_set() for overriding the default
+     stack size for threads created by apr_thread_create().
+     [Jeff Trawick]
+     (Back port from Apache 2.1.1)
+
+  *) Fix a misleading message from the some of the threaded MPMs when
+     MaxClients has to be lowered due to the setting of ServerLimit.
+     [Jeff Trawick]
+     (Back port from Apache 2.0.48)
+
+  *) Win32: Tweak worker thread accounting routines to eliminate
+     server hang when number of Listen directives in httpd.conf
+     is greater than or equal to the setting of ThreadsPerChild.
+     [Bill Stoddard] (Back port from Apache 2.0.50)
+
+  *) proxy_http fix: mod_proxy hangs when both KeepAlive and
+     ProxyErrorOverride are enabled, and a non-200 response without a
+     body is generated by the backend server. (e.g.: a client makes a
+     request containing the "If-Modified-Since" and "If-None-Match"
+     headers, to which the backend server respond with status 304.)
+     [Graham Wiseman <gwiseman fscinternet.com>, Richard Reiner]
+     (Back port from Apache 2.0.49)
+
+  *) Keep focus of ITERATE and ITERATE2 on the current module when
+     the module chooses to return DECLINE_CMD for the directive.
+     PR 22299.  [Geoffrey Young <geoff apache.org>]
+     (Back port from Apache 2.0.49)
+
+  *) mod_rewrite: Catch an edge case, where strange subsequent RewriteRules
+     could lead to a 400 (Bad Request) response.  [Andr Malo]
+     (Back port from Apache 2.0.49)
+
+  *) ap_mpm.h: Fix include guard of ap_mpm.h to reference mpm
+     instead of mmn. [Andr Malo]
+     (Back port from Apache 2.0.49)
+
+  *) mod_setenvif: Fix the regex optimizer, which under circumstances
+     treated the supplied regex as literal string. PR 24219.
+     [Andr Malo]
+     (Back port from Apache 2.0.49)
+
+  *) Remove compile-time length limit on request strings. Length is
+     now enforced solely with the LimitRequestLine config directive.
+     [Paul J. Reder]
+     (Back port from Apache 2.0.49)
+
+  *) apr_socket_data_set(): allow the same key to be used for 
+     multiple sockets in the same pool. [Jeff Trawick]
+     (Back port from Apache 2.0.48)
+
+  *) SECURITY: CAN-2004-0174 (cve.mitre.org)
+     Fix starvation issue on listening sockets where a short-lived
+     connection on a rarely-accessed listening socket will cause a
+     child to hold the accept mutex and block out new connections until
+     another connection arrives on that rarely-accessed listening socket.
+     With Apache 2.x there is no performance concern about enabling the
+     logic for platforms which don't need it, so it is enabled everywhere
+     except for Win32.  [Jeff Trawick]
+     (Back port from Apache 2.0.49)
+
+  *) Build array of allowed methods with proper dimensions, fixing
+     possible memory corruption.  [Jeff Trawick]
+     (Back port from Apache 2.0.49)
+
+  *) SECURITY: CAN-2003-0542 (cve.mitre.org)
+     Fix buffer overflows in mod_alias and mod_rewrite which occurred if
+     one configured a regular expression with more than 9 captures.
+     [Andr Malo] (Back port from Apache 2.0.48)
+
+  *) MPMs: The bucket brigades subsystem now honors the MaxMemFree setting.
+     [Cliff Woolley, Jean-Jacques Clar]
+     (Back port from Apache 2.0.48)
+
+  *) worker MPM: Write a message to the error log at startup if the
+     server is not configured for core dumps to be taken (ulimit -c 
+     is 0 or the server starts as root and the CoreDumpDirectory 
+     directive is not set).  [IBM]
+
+  *) Fixed cache-removal order in mod_mem_cache.
+     [Jean-Jacques Clar, Cliff Woolley]
+     (Back port from Apache 2.0.49)
+
+  *) Fix segfault in mod_mem_cache cache_insert() due to cache size
+     becoming negative.  PR: 21285, 21287
+     [Bill Stoddard, Massimo Torquati, Jean-Jacques Clar]
+     (Back port from Apache 2.0.49)
+
+  *) Modified the cache code to be header-location agnostic. Also
+     fixed a number of other cache code bugs related to PR 15852.
+     Includes a patch submitted by Sushma Rai <rsushma novell.com>.
+     This fixes mod_mem_cache but not mod_disk_cache yet so I'm not
+     closing the PR since that is what they are using. [Paul J. Reder]
+     (Back port from Apache 2.0.49)
+
+  *) cache_util: Fix ap_check_cache_freshness to check max_age, smax_age, and
+     expires as directed in RFC 2616. [Thomas Castelle <tcastelle generali.fr>]
+     (Back port from 2.0.48)
+
+  *) mod_cache: Fix the cache code so that responses can be cached
+     if they have an Expires header but no Etag or Last-Modified
+     headers. PR 23130. [<bjorn exoweb.net>]
+     (Back port from 2.0.48)
+
+  *) Win32 MPM: Implement MaxMemFree to enable setting an upper
+     limit on the amount of storage used by the bucket brigades
+     in each server thread. [Bill Stoddard]
+     (Back port from Apache 2.0.49)
+
+  *) Win32: Fix for find_ready_listener() bug and improved AcceptEx
+     error handling [Bill Stoddard]
+     (Back port from Apache 2.1-dev)
+  
+  *) Unix MPMs: Stop dropping connections when the file descriptor
+     is at least FD_SETSIZE.  [Jeff Trawick]
+     (Back port from Apache 2.0.50)
+
+  *) Win32: Add Win32DisableAcceptEx directive. This Windows
+     NT/2000/CP directive is useful to work around bugs in some 
+     third party layered service providers like virus scanners, 
+     VPN and firewall products, that do not properly handle 
+     WinSock 2 APIs.  Use this directive if your server is issuing
+     AcceptEx failed messages.
+     [Allan Edwards, Bill Rowe, Bill Stoddard, Jeff Trawick]
+     (Back port from Apache 2.0.49)
+
+  *) worker MPM: fix stack overlay bug that could cause the parent
+     process to crash.  [Jeff Trawick]
+     (Back port from Apache 2.0.49)
+
+  *) apr_socket_connect(): allow app to make subsequent call on
+     non-blocking socket.  [Jeff Trawick]
+     (Back port from Apache 2.0.49)
+
+  *) Add a hook (insert_error_filter) to allow filters to re-insert
+     themselves during processing of error responses. Enable mod_expires
+     to use the new hook to include Expires headers in valid error
+     responses. This addresses an RFC violation. It fixes PRs 19794,
+     24884, and 25123. [Paul J. Reder]
+     (Back port from Apache 2.0.49)
+
+  *) Provide an error string for APR_EBADPATH to avoid issues like this
+     in the web server error log:
+     (20025)Error string not specified yet: access to /images/xx***.gif failed
+     (Back port from Apache 2.0.49, unmentioned in APR CHANGES)
+
+  *) Fix a long delay with CGI requests and keepalive connections on
+     AIX.
+     (Back port from Apache 2.0.49 for PQ80604)
+
+  *) Tag the request and subrequest pools as a debugging aid.
+     (Back port from Apache 2.0.49, unmentioned in Apache CHANGES)
+
+  *) fix the config parser to support <Foo>..</Foo> containers (no
+     arguments in the opening tag) supported by httpd 1.3. Without
+     this change mod_perl 2.0's <Perl> sections are broken.
+     ["Philippe M. Chiasson" <gozer@cpan.org>]
+     (Back port from Apache 2.0.48)
+
+  *) Set the scoreboard state to indicate logging prior to running 
+     logging hooks so that server-status will show 'L' for hung loggers
+     instead of 'W'.  [Jeff Trawick]
+     (Back port from Apache 2.0.49)
+
+  *) mod_include: fix segfault which occured if the filename was not
+     set, for example, when processing some error conditions.
+     PR 23836.  [Brian Akins <bakins@web.turner.com>, Andr Malo]
+     (Back port from Apache 2.0.48)
+
+  *) Fix an IHS install problem that broke apxs -p on AIX.
+
+Changes with IHS 2.0.47
+
+  *) SECURITY [CAN-2003-0789]: mod_cgid: fix a double socket close problem 
+     while processing CGI-initiated redirects which could cause corruption 
+     for other requests being processed at the same time.  [IBM]
+     (Alternate fix in Apache 2.0.48)
+
+  *) mod_cgid: fix a hash table corruption problem which could
+     result in the wrong script being cleaned up at the end of a
+     request.  [Jeff Trawick]
+     (Back port from Apache 2.0.48)
+
+  *) Fix a bug, where mod_deflate sometimes unconditionally compressed the
+     content if the Accept-Encoding header contained only other tokens than
+     "gzip" (such as "deflate"). PR 21523.  [Joe Orton, Andr Malo]
+     (Back port from Apache 2.0.48)
+
+  *) Fix mod_deflate so that it does not call deflate() without checking
+     first whether it has something to deflate. (Currently this causes
+     deflate to generate a fatal error according to the zlib spec.)
+     PR 22259. [Stas Bekman]
+     (Back port from Apache 2.0.48)
+
+  *) mod_deflate: Don't attempt to hold all of the response until we're
+     done.  [Justin Erenkrantz]
+     (Back port from Apache 2.0.48)
+
+  *) Lower the severity of the "listener thread didn't exit" message 
+     to debug, as it is of interest only to developers.  PR 9011
+     [Jeff Trawick]
+     (Back port from Apache 2.0.48)
+
+  *) Fix apr_pool_create_ex to use the correct pool mutex.
+     (Back port from Apache 2.0.48; not mentioned in apr CHANGES)
+
+  *) ab: Work over non-loopback on Unix again. PR 21495. [Jeff Trawick]
+     (Back port from Apache 2.0.48 and Apache 2.1-dev)
+
+  *) mod_include: Fix a trio of bugs that would cause various unusual
+     sequences of parsed bytes to omit portions of the output stream.
+     PR 21095. [Ron Park <ronald.park@cnet.com>, Andr Malo, Cliff Woolley]
+     (Back port from Apache 2.0.48)
+
+  *) apr_socket_data_set(): allow the same key to be used for
+     multiple sockets in the same pool.  [Jeff Trawick]
+     (Back port from Apache 2.0.48)
+
+  *) Don't respect the Server header field as set by modules and CGIs.
+     As with 1.3, for proxy requests any such field is from the origin 
+     server; otherwise it will have our server info as controlled by
+     the ServerTokens directive.  [Jeff Trawick]
+     (Back port from Apache 2.0.48)
+
+  *) mod_cgid: Restart the cgid daemon if it crashes.  PR 19849
+     [Glenn Nielsen <glenn@apache.org>]
+     (Back port from Apache 2.0.49)
+
+Changes with IHS 2.0.42.2
+
+  *) Add IHS-specific debugging support for fatal signals.
+
+  *) Win32: Remove iconv from project files and Makefile.win. 
+     Set APU_HAVE_APR_ICONV in apr-util/include/apu.hw to 0.
+
+  *) Win32: Remove mod_auth_ldap and util_ldap from project files
+     and Makefile.win.
+
+  *) Win32: Remove mod_charset_lite from project files and
+     Makefile.win.
+
+  *) Rearrange some code in vhost.c to work around a gcc bug on 
+     s/390.
+
+  *) Enable all APR socket network calls to be hooked via an io layer
+     (IOL) in support of IHS-unique features.  This patch does not
+     break binary compatibility with APR.
+
+  *) Add extra information to LICENSE file in base source directory.
+
+  *) Modify the server version string to identify the release as
+     IBM_HTTP_Server from IBM instead of Apache from ASF.
+
+  *) Integrate an APR debugging patch which captures data received
+     by the client.  The data is not written anywhere but it is
+     easily accessible in a coredump.
+
 Changes with Apache 2.0.47
 
   *) SECURITY [CAN-2003-0192]: Fixed a bug whereby certain sequences
Index: LICENSE
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/LICENSE,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- LICENSE	29 Jul 2003 20:19:10 -0000	1.1.1.1
+++ LICENSE	15 Aug 2003 16:56:27 -0000	1.3
@@ -1,3 +1,39 @@
+====================================================================
+
+THIRD PARTY LICENSE TERMS AND CONDITIONS, NOTICES AND INFORMATION
+
+The license agreement for this product refers you to this file for details
+concerning terms and conditions applicable to third party software code included in
+this product, and for certain notices and other information IBM must provide to you
+under its license to certain software code. The relevant terms and conditions,
+notices and other information are provided or referenced below.  Please note that
+any non-English version of the licenses below is unofficial and is provided to you
+for your convenience only.  The English version of the licenses below, provided as
+part of the English version of this file, is the official version.
+
+All third party components, including third party components included or embedded in
+the Program, are provided to you by IBM on an "AS-IS" basis, and  IBM does not
+represent or warrant that these third party components do  not violate any
+intellectual property or other rights of a third party.   IBM will not
+indemnify you or be liable for any  incidental, indirect, special, exemplary,
+punitive or consequential damages resulting from third-party claims alleging patent
+or copyright infringement by any third party components; including but not limited
+to costs, damages, attorney's fees, costs of court, settlement fees, judgments, lost
+profits and related damages.
+
+=================================================================
+
+IBM HTTP SERVER AND THE APACHE HTTP SERVER: The IBM HTTP Server component of the
+Program includes Apache HTTP Server software developed by The Apache Software Foundation
+(http://www.apache.org/). The Program also is accompanied by source code for the
+Apache HTTP Server. Except as noted in the "APACHE HTTP SERVER SUBCOMPONENTS"
+section below, the portions of the IBM HTTP Server which are based on software
+developed by The Apache Group and the source code for the Apache HTTP Server are
+Copyright (c) 2000 The Apache Software Foundation. All rights reserved.  Except as
+noted in the "APACHE HTTP SERVER SUBCOMPONENTS" section below, your use of the
+source code for the Apache HTTP Server accompanying the Program is subject 
+the terms and conditions of the following license from The Apache Group:
+
 /* ====================================================================
  * The Apache Software License, Version 1.1
  *
@@ -59,10 +95,12 @@
 
 APACHE HTTP SERVER SUBCOMPONENTS: 
 
-The Apache HTTP Server includes a number of subcomponents with
-separate copyright notices and license terms. Your use of the source
-code for the these subcomponents is subject to the terms and
-conditions of the following licenses. 
+APACHE HTTP SERVER SUBCOMPONENTS: The Apache HTTP Server, both in source code form
+and in the binary code IBM HTTP Server, includes a number of subcomponents with
+separate copyright notices and license terms. Your use of the source code for the
+these subcomponents is subject to the terms and conditions of the following
+licenses. IBM did not modify these components after obtaining them as part of the
+Apache HTTP Server.
 
 For the mod_mime_magic component:
 
@@ -531,3 +569,36 @@
 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
 ====================================================================
+
+For the zlib component used by modules/filters/mod_deflate:
+
+ (C) 1995-2002 Jean-loup Gailly and Mark Adler
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+If you use the zlib library in a product, we would appreciate *not*
+receiving lengthy legal documents to sign. The sources are provided
+for free but without warranty of any kind.  The library has been
+entirely written by Jean-loup Gailly and Mark Adler; it does not
+include third-party code.
+
+If you redistribute modified sources, we would appreciate that you include
+in the file ChangeLog history information documenting your changes.
+
Index: Makefile.in
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/Makefile.in,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- Makefile.in	29 Jul 2003 20:19:10 -0000	1.1.1.1
+++ Makefile.in	6 Jun 2005 12:22:00 -0000	1.2
@@ -173,6 +173,7 @@
 	@cp -p $(srcdir)/modules/dav/main/mod_dav.h $(DESTDIR)$(includedir)
 	@cp -p $(srcdir)/modules/filters/mod_include.h $(DESTDIR)$(includedir)
 	@cp -p $(srcdir)/modules/generators/mod_cgi.h $(DESTDIR)$(includedir)
+	@cp -p $(srcdir)/modules/generators/mod_status.h $(DESTDIR)$(includedir)
 	@cp -p $(srcdir)/modules/loggers/mod_log_config.h $(DESTDIR)$(includedir)
 	@cp -p $(srcdir)/modules/http/mod_core.h $(DESTDIR)$(includedir)
 	@cp -p $(srcdir)/modules/proxy/mod_proxy.h $(DESTDIR)$(includedir)
Index: README
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/README,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
Index: configure.in
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/configure.in,v
retrieving revision 1.1.1.1
retrieving revision 1.10
diff -u -u -r1.1.1.1 -r1.10
--- configure.in	29 Jul 2003 20:19:11 -0000	1.1.1.1
+++ configure.in	10 Jan 2006 18:01:58 -0000	1.10
@@ -135,7 +135,7 @@
   APR_ADDTO(INCLUDES, [-I\$(srcdir) -I\$(top_builddir)/server/mpm/\$(MPM_SUBDIR_NAME) -I\$(top_builddir)/include])
 fi
 
-APR_ADDTO(INCLUDES, [-I\$(top_srcdir)/os/\$(OS_DIR) -I\$(top_srcdir)/server/mpm/\$(MPM_SUBDIR_NAME) -I\$(top_srcdir)/modules/http -I\$(top_srcdir)/modules/filters -I\$(top_srcdir)/modules/proxy -I\$(top_srcdir)/include])
+APR_ADDTO(INCLUDES, [-I\$(top_srcdir)/os/\$(OS_DIR) -I\$(top_srcdir)/server/mpm/\$(MPM_SUBDIR_NAME) -I\$(top_srcdir)/modules/http -I\$(top_srcdir)/modules/filters -I\$(top_srcdir)/modules/proxy -I\$(top_srcdir)/include -I\$(top_srcdir)/modules/generators])
 
 echo $ac_n "${nl}Applying OS-specific hints for httpd ...${nl}"
 
@@ -236,6 +236,8 @@
       ;;
 esac
 
+APR_SETVAR(AP_NONBLOCK_WHEN_MULTI_LISTEN, [1])
+
 dnl
 dnl Process command line arguments. This is done early in the process so the
 dnl user can get feedback quickly in case of an error.
@@ -318,7 +320,7 @@
     *aix*)
         # for 32-bit builds, increase MAXDATA to allow lots of threads
         if test x$OBJECT_MODE != x64; then
-            OS_SPECIFIC_VARS="LDR_CNTRL=\"MAXDATA=0x80000000\" ; export LDR_CNTRL ;"
+            OS_SPECIFIC_VARS="LDR_CNTRL=\"MAXDATA=0x60000000\" ; export LDR_CNTRL ;"
         fi
         OS_SPECIFIC_VARS="$OS_SPECIFIC_VARS AIXTHREAD_SCOPE=S ; export AIXTHREAD_SCOPE"
         OS_SPECIFIC_VARS="$OS_SPECIFIC_VARS ; AIXTHREAD_MUTEX_DEBUG=OFF ; export AIXTHREAD_MUTEX_DEBUG"
@@ -329,7 +331,8 @@
         OS_SPECIFIC_VARS="$OS_SPECIFIC_VARS ; MALLOCMULTIHEAP=considersize,heaps:8 ; export MALLOCMULTIHEAP"
         ;;
     *os390*)
-        OS_SPECIFIC_VARS="export _CEE_RUNOPTS=\"STACK(,,ANY)\" ; export _EDC_ADD_ERRNO2=1"
+        OS_SPECIFIC_VARS="LIBPATH=$exp_libexecdir:\$LIBPATH ; export LIBPATH"       
+	OS_SPECIFIC_VARS="$OS_SPECIFIC_VARS ; export _CEE_RUNOPTS=\"STACK(,,ANY)\" ; export _EDC_ADD_ERRNO2=1 ; export _BPX_SHAREAS=NO ; export GSK_SSL_HW_DETECT_MESSAGE=1 "
         ;;
     *)
         OS_SPECIFIC_VARS=""
@@ -368,6 +371,12 @@
     nonssl_listen_stmt_2="Listen [[::]]:@@Port@@"
 fi
 
+AC_ARG_ENABLE(exception-hook,APACHE_HELP_STRING(--enable-exception-hook,Enable fatal exception hook),
+[
+    AC_DEFINE(AP_ENABLE_EXCEPTION_HOOK, 1,
+              [Allow modules to run hook after a fatal exception])
+])dnl
+
 AC_ARG_ENABLE(maintainer-mode,APACHE_HELP_STRING(--enable-maintainer-mode,Turn on debugging and compile time warnings),
 [
   APR_ADDTO(CPPFLAGS, -DAP_DEBUG)
@@ -481,6 +490,11 @@
 if test "$SINGLE_LISTEN_UNSERIALIZED_ACCEPT" = "1"; then
     AC_DEFINE(SINGLE_LISTEN_UNSERIALIZED_ACCEPT, 1, 
               [This platform doesn't suffer from the thundering herd problem])
+fi
+
+if test "$AP_NONBLOCK_WHEN_MULTI_LISTEN" = "1"; then
+    AC_DEFINE(AP_NONBLOCK_WHEN_MULTI_LISTEN, 1, 
+              [Listening sockets are non-blocking when there are more than 1])
 fi
 
 AC_DEFINE_UNQUOTED(AP_SIG_GRACEFUL, SIG$AP_SIG_GRACEFUL, [Signal used to gracefully restart])
Index: docs/manual/mod/core.html.en
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/docs/manual/mod/core.html.en,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- docs/manual/mod/core.html.en	29 Jul 2003 20:19:14 -0000	1.1.1.1
+++ docs/manual/mod/core.html.en	10 Mar 2006 15:49:11 -0000	1.4
@@ -955,6 +955,14 @@
     error rather than masking it.  More information is available in
     Microsoft Knowledgebase article <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;Q294807">Q294807</a>.</p>
 
+    <p>Although most error messages can be overriden, there are certain
+    circumstances where the internal messages are used regardless of the
+    setting of <code class="directive"><a href="#errordocument">ErrorDocument</a></code>.  In
+    particular, if a malformed request is detected, normal request processing
+    will be immediately halted and the internal error message returned.
+    This is necessary to guard against security problems caused by
+    bad requests.</p>
+
     <p>Prior to version 2.0, messages were indicated by prefixing
     them with a single unmatched double quote character.</p>
 
@@ -1698,21 +1706,18 @@
 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Core</td></tr>
 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>core</td></tr>
 </table>
-    <p>This directive specifies the number of <var>bytes</var> from 0
-    to the value of the compile-time constant
-    <code>DEFAULT_LIMIT_REQUEST_FIELDSIZE</code> (8190 as
-    distributed) that will be allowed in an HTTP request
-    header.</p>
+    <p>This directive specifies the number of <var>bytes</var>
+    that will be allowed in an HTTP request header.</p>
 
     <p>The <code class="directive">LimitRequestFieldSize</code> directive
-    allows the server administrator to reduce the limit on the allowed
-    size of an HTTP request header field below the normal input buffer
-    size compiled with the server. A server needs this value to be
-    large enough to hold any one header field from a normal client
-    request. The size of a normal request header field will vary
-    greatly among different client implementations, often depending
-    upon the extent to which a user has configured their browser to
-    support detailed content negotiation.</p>
+    allows the server administrator to reduce or increase the limit
+    on the allowed size of an HTTP request header field. A server
+    needs this value to be large enough to hold any one header field
+    from a normal client request. The size of a normal request header
+    field will vary greatly among different client implementations,
+    often depending upon the extent to which a user has configured
+    their browser to support detailed content negotiation. SPNEGO
+    authentication headers can be up to 12392 bytes.</p>
 
     <p>This directive gives the server administrator greater
     control over abnormal client request behavior, which may be
@@ -1727,6 +1732,15 @@
     <div class="note">Under normal conditions, the value should not be changed from
     the default.</div>
 
+    <div class="note">Apache 2.0.53 or higher is required for increasing the
+    limit above the compiled-in value of DEFAULT_LIMIT_REQUEST_FIELDSIZE
+    (8190 as distributed).
+    </div>
+
+    <div class="note">IBM HTTP Server 6.0.0.2 or higher, or cumulative fix PK01070
+    or later for IBM HTTP Server 2.0, provides the capability of 
+    increasing the limit.
+    </div>
 
 </div>
 <div class="top"><a href="#page-header"><img alt="top" src="../images/up.gif" /></a></div>
@@ -2235,6 +2249,12 @@
     <code>-</code> are removed from the options currently in
     force. </p>
 
+    <div class="warning"><h3>Warning</h3>
+    <p>Mixing <code class="directive">Options</code> with a <code>+</code> or
+    <code>-</code> with those without is not valid syntax, and is likely
+    to cause unexpected results.</p>
+    </div>
+
     <p>For example, without any <code>+</code> and <code>-</code> symbols:</p>
 
     <div class="example"><p><code>
@@ -3141,4 +3161,4 @@
 </div><div id="footer">
 <p class="apache">Maintained by the <a href="http://httpd.apache.org/docs-project/">Apache HTTP Server Documentation Project</a></p>
 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="../faq/">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p></div>
-</body></html>
\ No newline at end of file
+</body></html>
Index: docs/manual/mod/core.xml
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/docs/manual/mod/core.xml,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- docs/manual/mod/core.xml	29 Jul 2003 20:19:14 -0000	1.1.1.1
+++ docs/manual/mod/core.xml	10 Mar 2006 15:49:11 -0000	1.4
@@ -894,6 +894,14 @@
     href="http://support.microsoft.com/default.aspx?scid=kb;en-us;Q294807"
     >Q294807</a>.</p>
 
+    <p>Although most error messages can be overriden, there are certain
+    circumstances where the internal messages are used regardless of the
+    setting of <directive>ErrorDocument</directive>.  In
+    particular, if a malformed request is detected, normal request processing
+    will be immediately halted and the internal error message returned.
+    This is necessary to guard against security problems caused by
+    bad requests.</p>
+
     <p>Prior to version 2.0, messages were indicated by prefixing
     them with a single unmatched double quote character.</p>
 </usage>
@@ -1648,21 +1656,18 @@
 <contextlist><context>server config</context></contextlist>
 
 <usage>
-    <p>This directive specifies the number of <var>bytes</var> from 0
-    to the value of the compile-time constant
-    <code>DEFAULT_LIMIT_REQUEST_FIELDSIZE</code> (8190 as
-    distributed) that will be allowed in an HTTP request
-    header.</p>
+    <p>This directive specifies the number of <var>bytes</var>
+    that will be allowed in an HTTP request header.</p>
 
     <p>The <directive>LimitRequestFieldSize</directive> directive
-    allows the server administrator to reduce the limit on the allowed
-    size of an HTTP request header field below the normal input buffer
-    size compiled with the server. A server needs this value to be
-    large enough to hold any one header field from a normal client
-    request. The size of a normal request header field will vary
-    greatly among different client implementations, often depending
-    upon the extent to which a user has configured their browser to
-    support detailed content negotiation.</p>
+    allows the server administrator to reduce or increase the limit
+    on the allowed size of an HTTP request header field. A server
+    needs this value to be large enough to hold any one header field
+    from a normal client request. The size of a normal request header
+    field will vary greatly among different client implementations,
+    often depending upon the extent to which a user has configured
+    their browser to support detailed content negotiation. SPNEGO
+    authentication headers can be up to 12392 bytes.</p>
 
     <p>This directive gives the server administrator greater
     control over abnormal client request behavior, which may be
@@ -1677,6 +1682,15 @@
     <note>Under normal conditions, the value should not be changed from
     the default.</note>
 
+    <note>Apache 2.0.53 or higher is required for increasing the
+    limit above the compiled-in value of DEFAULT_LIMIT_REQUEST_FIELDSIZE
+    (8190 as distributed).
+    </note>
+
+    <note>IBM HTTP Server 6.0.0.2 or higher, or cumulative fix PK01070
+    or later for IBM HTTP Server 2.0, provides the capability of 
+    increasing the limit.
+    </note>
 </usage>
 </directivesynopsis>
 
@@ -2195,6 +2209,12 @@
     options currently in force, and any options preceded by a
     <code>-</code> are removed from the options currently in
     force. </p>
+
+    <note type="warning"><title>Warning</title>
+    <p>Mixing <directive>Options</directive> with a <code>+</code> or
+    <code>-</code> with those without is not valid syntax, and is likely
+    to cause unexpected results.</p>
+    </note>
 
     <p>For example, without any <code>+</code> and <code>-</code> symbols:</p>
 
Index: docs/manual/mod/mod_headers.html.en
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/docs/manual/mod/mod_headers.html.en,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- docs/manual/mod/mod_headers.html.en	29 Jul 2003 20:19:16 -0000	1.1.1.1
+++ docs/manual/mod/mod_headers.html.en	7 Sep 2004 21:06:46 -0000	1.2
@@ -152,17 +152,28 @@
 <div class="directive-section"><h2><a name="Header" id="Header">Header</a> <a name="header" id="header">Directive</a></h2>
 <table class="directive">
 <tr><th><a href="directive-dict.html#Description">Description:</a></th><td>Configure HTTP response headers</td></tr>
-<tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>Header set|append|add|unset|echo  <var>header</var>
-[<var>value</var> [env=[!]<var>variable</var>]]</code></td></tr>
+<tr><th><a href="directive-dict.html#Syntax">Syntax:</a></th><td><code>Header [<var>condition</var>] set|append|add|unset|echo
+<var>header</var> [<var>value</var>] [env=[!]<var>variable</var>]</code></td></tr>
 <tr><th><a href="directive-dict.html#Context">Context:</a></th><td>server config, virtual host, directory, .htaccess</td></tr>
 <tr><th><a href="directive-dict.html#Override">Override:</a></th><td>FileInfo</td></tr>
 <tr><th><a href="directive-dict.html#Status">Status:</a></th><td>Extension</td></tr>
 <tr><th><a href="directive-dict.html#Module">Module:</a></th><td>mod_headers</td></tr>
+<tr><th><a href="directive-dict.html#Compatibility">Compatibility:</a></th><td><var>Condition</var> is available in version 2.0.51 and
+later</td></tr>
 </table>
     <p>This directive can replace, merge or remove HTTP response
     headers. The header is modified just after the content handler
     and output filters are run, allowing outgoing headers to be
-    modified. The action it performs is determined by the first
+    modified.</p>
+
+    <p>The optional <var>condition</var> can be either <code>onsuccess</code>
+    or <code>always</code>. It determines, which internal header table should be
+    operated on. <code>onsuccess</code> stands for <code>2<var>xx</var></code>
+    status codes and <code>always</code> for all status codes (including
+    <code>2<var>xx</var></code>). Especially if you want to unset headers
+    set by certain modules, you should try out, which table is affected.</p>
+
+    <p>The action it performs is determined by the second
     argument. This can be one of the following values:</p>
 
     <dl>
@@ -207,6 +218,7 @@
     are supported in <var>value</var>:</p>
 
     <table class="bordered">
+    
     <tr><td><code>%t</code></td>
         <td>The time the request was received in Universal Coordinated Time
         since the epoch (Jan. 1, 1970) measured in microseconds. The value
@@ -296,6 +308,6 @@
 <div class="bottomlang">
 <p><span>Available Languages: </span><a href="../en/mod/mod_headers.html" title="English">&nbsp;en&nbsp;</a></p>
 </div><div id="footer">
-<p class="apache">Maintained by the <a href="http://httpd.apache.org/docs-project/">Apache HTTP Server Documentation Project</a></p>
+<p class="apache">Copyright 1999-2004 The Apache Software Foundation.<br />Licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.</p>
 <p class="menu"><a href="../mod/">Modules</a> | <a href="../mod/directives.html">Directives</a> | <a href="../faq/">FAQ</a> | <a href="../glossary.html">Glossary</a> | <a href="../sitemap.html">Sitemap</a></p></div>
 </body></html>
Index: docs/manual/mod/mod_headers.xml
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/docs/manual/mod/mod_headers.xml,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- docs/manual/mod/mod_headers.xml	29 Jul 2003 20:19:16 -0000	1.1.1.1
+++ docs/manual/mod/mod_headers.xml	7 Sep 2004 21:06:46 -0000	1.2
@@ -1,6 +1,24 @@
 <?xml version="1.0"?>
 <!DOCTYPE modulesynopsis SYSTEM "../style/modulesynopsis.dtd">
 <?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>
+<!-- $Revision: 1.2 $ -->
+
+<!--
+ Copyright 2002-2004 The Apache Software Foundation
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+     http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
 <modulesynopsis metafile="mod_headers.xml.meta">
 
 <name>mod_headers</name>
@@ -176,17 +194,28 @@
 <directivesynopsis>
 <name>Header</name>
 <description>Configure HTTP response headers</description>
-<syntax>Header set|append|add|unset|echo  <var>header</var>
-[<var>value</var> [env=[!]<var>variable</var>]]</syntax>
+<syntax>Header [<var>condition</var>] set|append|add|unset|echo
+<var>header</var> [<var>value</var>] [env=[!]<var>variable</var>]</syntax>
 <contextlist><context>server config</context><context>virtual host</context>
 <context>directory</context><context>.htaccess</context></contextlist>
 <override>FileInfo</override>
+<compatibility><var>Condition</var> is available in version 2.0.51 and
+later</compatibility>
 
 <usage>
     <p>This directive can replace, merge or remove HTTP response
     headers. The header is modified just after the content handler
     and output filters are run, allowing outgoing headers to be
-    modified. The action it performs is determined by the first
+    modified.</p>
+
+    <p>The optional <var>condition</var> can be either <code>onsuccess</code>
+    or <code>always</code>. It determines, which internal header table should be
+    operated on. <code>onsuccess</code> stands for <code>2<var>xx</var></code>
+    status codes and <code>always</code> for all status codes (including
+    <code>2<var>xx</var></code>). Especially if you want to unset headers
+    set by certain modules, you should try out, which table is affected.</p>
+
+    <p>The action it performs is determined by the second
     argument. This can be one of the following values:</p>
 
     <dl>
@@ -231,6 +260,7 @@
     are supported in <var>value</var>:</p>
 
     <table border="1">
+    <columnspec><column width=".25"/><column width=".75"/></columnspec>
     <tr><td><code>%t</code></td>
         <td>The time the request was received in Universal Coordinated Time
         since the epoch (Jan. 1, 1970) measured in microseconds. The value
Index: docs/manual/mod/mpm_winnt.xml
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/docs/manual/mod/mpm_winnt.xml,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- docs/manual/mod/mpm_winnt.xml	29 Jul 2003 20:19:18 -0000	1.1.1.1
+++ docs/manual/mod/mpm_winnt.xml	19 Feb 2004 19:24:38 -0000	1.2
@@ -36,4 +36,23 @@
 <directivesynopsis location="mpm_common"><name>ThreadsPerChild</name>
 </directivesynopsis>
 
+<directivesynopsis>
+<name>Win32DisableAcceptEx</name>
+<description>This directive instructs the MPM to use accept() rather than AcceptEx() to accept network connections</description>
+<syntax>Win32DisableAcceptEx</syntax>
+<default>AcceptEx is enabled by default. Use this directive to disable use of AcceptEx</default>
+<contextlist><context>server config</context></contextlist>
+
+<usage>
+    <p>AcceptEx() is a Microsoft WinSock v2 API that provides
+    some performance improvements over the use of the BSD style
+    accept() API in certain circumstances. Some popular Windows
+    products, typically virus scanning or virtual private network
+    packages, have bugs that interfere with the proper operation of
+    AcceptEx(). If you encounter any of the conditions described
+    in the FAQ, you should use this directive to disable the use
+    of AcceptEx().</p>
+</usage>
+</directivesynopsis>
+
 </modulesynopsis>
Index: docs/manual/programs/rotatelogs.xml
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/docs/manual/programs/rotatelogs.xml,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- docs/manual/programs/rotatelogs.xml	29 Jul 2003 20:19:19 -0000	1.1.1.1
+++ docs/manual/programs/rotatelogs.xml	16 Jun 2004 21:35:49 -0000	1.2
@@ -31,7 +31,9 @@
 
 <section id="synopsis"><title>Synopsis</title>
 
-     <p><code><strong>rotatelogs</strong> <var>logfile</var>
+     <p><code><strong>rotatelogs</strong>
+     [ -<strong>l</strong> ]
+     <var>logfile</var>
      [ <var>rotationtime</var> [ <var>offset</var> ]] |
      [ <var>filesize</var>M ]</code></p>
 </section>
@@ -39,6 +41,11 @@
 <section id="options"><title>Options</title>
 
 <dl>
+
+<dt><code>-l</code></dt>
+<dd>Causes the use of local time rather than GMT as the base for the
+interval. Note that using <code>-l</code> in an environment which changes the
+GMT offset (such as for BST or DST) can lead to unpredictable results!</dd>
 
 <dt><code><var>logfile</var></code></dt>
 
Index: include/ap_config.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/ap_config.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- include/ap_config.h	29 Jul 2003 20:19:19 -0000	1.1.1.1
+++ include/ap_config.h	7 Mar 2004 12:35:47 -0000	1.2
@@ -269,6 +269,9 @@
 #include "ap_config_auto.h"
 #include "ap_config_layout.h"
 #endif
+#if defined(NETWARE)
+#define AP_NONBLOCK_WHEN_MULTI_LISTEN 1
+#endif
 
 /* TODO - We need to put OS detection back to make all the following work */
 
Index: include/ap_listen.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/ap_listen.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- include/ap_listen.h	29 Jul 2003 20:19:19 -0000	1.1.1.1
+++ include/ap_listen.h	22 Mar 2005 14:07:55 -0000	1.3
@@ -99,6 +99,9 @@
  */
 AP_DECLARE_DATA extern ap_listen_rec *ap_listeners;
 
+/* IBM: externalize for use by AFPA on Win32 */
+AP_DECLARE(const char *) ap_alloc_listener(process_rec *process, char *addr, apr_port_t port);
+
 /**
  * Setup all of the defaults for the listener list
  */
@@ -140,6 +143,8 @@
 const char *ap_set_listener(cmd_parms *cmd, void *dummy, const char *ips);
 const char *ap_set_send_buffer_size(cmd_parms *cmd, void *dummy,
 				    const char *arg);
+AP_DECLARE_NONSTD(const char *) ap_set_receive_buffer_size(cmd_parms *cmd, void *dummy,
+				    const char *arg);
 
 #define LISTEN_COMMANDS	\
 AP_INIT_TAKE1("ListenBacklog", ap_set_listenbacklog, NULL, RSRC_CONF, \
@@ -147,6 +152,8 @@
 AP_INIT_TAKE1("Listen", ap_set_listener, NULL, RSRC_CONF, \
   "A port number or a numeric IP address and a port number"), \
 AP_INIT_TAKE1("SendBufferSize", ap_set_send_buffer_size, NULL, RSRC_CONF, \
-  "Send buffer size in bytes")
+  "Send buffer size in bytes"), \
+AP_INIT_TAKE1("ReceiveBufferSize", ap_set_receive_buffer_size, NULL, RSRC_CONF, \
+  "Receive buffer size in bytes")
 
 #endif
Index: include/ap_mpm.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/ap_mpm.h,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- include/ap_mpm.h	29 Jul 2003 20:19:19 -0000	1.1.1.1
+++ include/ap_mpm.h	11 Nov 2004 23:10:29 -0000	1.4
@@ -52,8 +52,8 @@
  * <http://www.apache.org/>.
  */
 
-#ifndef AP_MMN_H
-#define AP_MMN_H
+#ifndef AP_MPM_H
+#define AP_MPM_H
 
 #include "apr_thread_proc.h"
 
@@ -196,5 +196,31 @@
 #else
 #define AP_MONCONTROL(x)
 #endif
+
+/* IMPORTANT NOTE: This fatal exception hook is not part of the Apache API
+ *                 and should not be used by third-party modules, as it may
+ *                 change in future IHS releases without warning.
+ */
+#ifndef WIN32
+typedef struct ihs_exception_info_tag {
+    int format;
+    int sig;
+    pid_t pid; /* deal with fact that getpid() from a thread on Linux
+                * doesn't return the real process id, and the hook may
+                * want to know that for logging purposes
+                */
+} ihs_exception_info_t;
+
+AP_DECLARE_HOOK(int,ihs_fatal_exception_received,(ihs_exception_info_t *ei))
+#endif /* WIN32 */
+
+#if AP_ENABLE_EXCEPTION_HOOK
+typedef struct ap_exception_info_t {
+    int sig;
+    pid_t pid;
+} ap_exception_info_t;
+
+AP_DECLARE_HOOK(int,fatal_exception,(ap_exception_info_t *ei))
+#endif /*AP_ENABLE_EXCEPTION_HOOK*/
 
 #endif
Index: include/ap_release.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/ap_release.h,v
retrieving revision 1.1.1.1
diff -u -u -r1.1.1.1 ap_release.h
--- include/ap_release.h	29 Jul 2003 20:19:19 -0000	1.1.1.1
+++ include/ap_release.h	13 Apr 2006 20:54:43 -0000
@@ -71,14 +71,16 @@
  *
  * Example: "Apache/1.1.0 MrWidget/0.1-alpha" 
  */
-#define AP_SERVER_BASEVENDOR "Apache Software Foundation"
-#define AP_SERVER_BASEPRODUCT "Apache"
+#define AP_SERVER_BASEVENDOR "International Business Machines"
+#define AP_SERVER_BASEPRODUCT "IBM_HTTP_Server"
 #define AP_SERVER_MAJORVERSION "2"
 #define AP_SERVER_MINORVERSION "0"
 #define AP_SERVER_PATCHLEVEL "47"
 #define AP_SERVER_MINORREVISION AP_SERVER_MAJORVERSION "." AP_SERVER_MINORVERSION
 #define AP_SERVER_BASEREVISION  AP_SERVER_MINORREVISION "." AP_SERVER_PATCHLEVEL
-#define AP_SERVER_BASEVERSION AP_SERVER_BASEPRODUCT "/" AP_SERVER_BASEREVISION
+#define IHS_VERSION "6.1"
+#define AP_DEFAULT_SERVICE_NAME "IBM HTTP Server 6.1"
+#define AP_SERVER_BASEVERSION AP_SERVER_BASEPRODUCT "/" IHS_VERSION " Apache/" AP_SERVER_BASEREVISION
 #define AP_SERVER_VERSION  AP_SERVER_BASEVERSION
 
 #endif
Index: include/http_config.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/http_config.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- include/http_config.h	29 Jul 2003 20:19:19 -0000	1.1.1.1
+++ include/http_config.h	8 Mar 2005 19:53:29 -0000	1.2
@@ -1033,6 +1033,10 @@
  */
 AP_DECLARE_HOOK(int,handler,(request_rec *r))
 
+/* IHS serviceability changes */
+AP_DECLARE(void) ihs_save_hook_info(void);
+AP_DECLARE(int) ihs_run_handler(request_rec *r);
+    
 /**
  * Run the quick handler functions for each module. The quick_handler
  * is run before any other requests hooks are called (location_walk,
Index: include/http_core.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/http_core.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- include/http_core.h	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ include/http_core.h	16 May 2005 12:25:22 -0000	1.3
@@ -367,6 +367,16 @@
      * won't actually be delivered as the response for the non-GET method.
      */
     int deliver_script;
+
+    /* Custom response strings registered via ap_custom_response(),
+     * or NULL; check per-dir config if nothing found here
+     */
+    char **response_code_strings; /* from ap_custom_response(), not from
+                                   * ErrorDocument
+                                   */
+    /* Should addition of charset= be suppressed for this request?
+     */
+    int suppress_charset;
 } core_request_config;
 
 /* Standard entries that are guaranteed to be accessible via
@@ -469,7 +479,8 @@
      * This lets us do quick merges in merge_core_dir_configs().
      */
   
-    char **response_code_strings;
+    char **response_code_strings; /* from ErrorDocument, not from
+                                   * ap_custom_response() */
 
     /* Hostname resolution etc */
 #define HOSTNAME_LOOKUP_OFF	0
Index: include/http_log.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/http_log.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- include/http_log.h	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ include/http_log.h	16 May 2005 12:09:58 -0000	1.3
@@ -158,6 +158,16 @@
 int ap_open_logs(apr_pool_t *pconf, apr_pool_t *plog, 
                  apr_pool_t *ptemp, server_rec *s_main);
 
+/**
+ * Perform special processing for piped loggers in MPM child
+ * processes.
+ * @param p Not used
+ * @param s Not used
+ * @tip ap_logs_child_init is not for use by modules; it is an
+ * internal core function
+ */
+void ap_logs_child_init(apr_pool_t *p, server_rec *s);
+
 /* 
  * The three primary logging functions, ap_log_error, ap_log_rerror, and 
  * ap_log_perror use a printf style format string to build the log message.  
@@ -240,6 +250,11 @@
                                const char *fmt, ...)
 			    __attribute__((format(printf,6,7)));
 
+AP_DECLARE(void) ap_log_cerror(const char *file, int line, int level, 
+                               apr_status_t status, const conn_rec *c, 
+                               const char *fmt, ...)
+			    __attribute__((format(printf,6,7)));
+                            
 /**
  * Convert stderr to the error log
  * @param s The current server
Index: include/http_protocol.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/http_protocol.h,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- include/http_protocol.h	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ include/http_protocol.h	13 Apr 2006 20:26:36 -0000	1.4
@@ -74,6 +74,13 @@
  * @package HTTP protocol handling
  */
 
+/**
+ * This hook allows modules to insert filters for the current error response
+ * @param r the current request
+ * @ingroup hooks
+ */
+AP_DECLARE_HOOK(void,insert_error_filter,(request_rec *r))
+
 /* This is an optimization.  We keep a record of the filter_rec that
  * stores the old_write filter, so that we can avoid strcmp's later.
  */
@@ -641,6 +648,9 @@
  * @deffunc int ap_run_log_transaction(request_rec *r)
  */
 AP_DECLARE_HOOK(int,log_transaction,(request_rec *r))
+
+/* IHS serviceability change */
+AP_DECLARE(int) ihs_run_log_transaction(request_rec *r);
 
 /**
  * This hook allows modules to retrieve the http method from a request.  This
Index: include/http_request.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/http_request.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- include/http_request.h	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ include/http_request.h	8 Mar 2005 19:53:29 -0000	1.2
@@ -353,6 +353,10 @@
  */
 AP_DECLARE_HOOK(int,check_user_id,(request_rec *r))
 
+/* IHS serviceability changes */
+AP_DECLARE(int) ihs_run_check_user_id(request_rec *r);
+AP_DECLARE(int) ihs_run_access_checker(request_rec *r);
+
 /**
  * Allows modules to perform module-specific fixing of header fields.  This
  * is invoked just before any content-handler
Index: include/httpd.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/httpd.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- include/httpd.h	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ include/httpd.h	22 Feb 2005 18:37:07 -0000	1.3
@@ -321,6 +321,9 @@
 /** The size of the server's internal read-write buffers */
 #define AP_IOBUFSIZE 8192
 
+/** The max number of regex captures that can be expanded by ap_pregsub */
+#define AP_MAX_REG_MATCH 10
+
 /**
  * APR_HAS_LARGE_FILES introduces the problem of spliting sendfile into 
  * mutiple buckets, no greater than MAX(apr_size_t), and more granular 
@@ -1367,10 +1370,20 @@
 /**
  * Escape a string for logging
  * @param p The pool to allocate from
- * @param s The string to escape
+ * @param str The string to escape
  * @return The escaped string
  */
 AP_DECLARE(char *) ap_escape_logitem(apr_pool_t *p, const char *str);
+
+/**
+ * Escape a string for logging into the error log (without a pool)
+ * @param dest The buffer to write to
+ * @param source The string to escape
+ * @param buflen The buffer size for the escaped string (including \0)
+ * @return The len of the escaped string (always < maxlen)
+ */
+AP_DECLARE(apr_size_t) ap_escape_errorlog_item(char *dest, const char *source,
+                                               apr_size_t buflen);
 
 /**
  * Construct a full hostname
Index: include/mpm_common.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/mpm_common.h,v
retrieving revision 1.1.1.1
retrieving revision 1.5
diff -u -u -r1.1.1.1 -r1.5
--- include/mpm_common.h	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ include/mpm_common.h	6 Dec 2004 16:16:43 -0000	1.5
@@ -102,7 +102,7 @@
  * Make sure all child processes that have been spawned by the parent process
  * have died.  This includes process registered as "other_children".
  * @warning This is only defined if the MPM defines 
- *          MPM_NEEDS_RECLAIM_CHILD_PROCESS
+ *          AP_MPM_WANT_RECLAIM_CHILD_PROCESSES
  * @param terminate Either 1 or 0.  If 1, send the child processes SIGTERM
  *        each time through the loop.  If 0, give the process time to die
  *        on its own before signalling it.
@@ -110,12 +110,43 @@
  *  MPM_CHILD_PID -- Get the pid from the specified spot in the scoreboard
  *  MPM_NOTE_CHILD_KILLED -- Note the child died in the scoreboard
  * </pre>
+ * @tip The MPM child processes which are reclaimed are those listed
+ * in the scoreboard as well as those currently registered via
+ * ap_register_extra_mpm_process().
  */
 #ifdef AP_MPM_WANT_RECLAIM_CHILD_PROCESSES
 void ap_reclaim_child_processes(int terminate);
 #endif
 
 /**
+ * Tell ap_reclaim_child_processes() about an MPM child process which has no
+ * entry in the scoreboard.
+ * @warning This is only defined if the MPM defines
+ *          AP_MPM_WANT_RECLAIM_CHILD_PROCESSES
+ * @param pid The process id of an MPM child process which should be
+ * reclaimed when ap_reclaim_child_processes() is called.
+ * @tip If an extra MPM child process terminates prior to calling
+ * ap_reclaim_child_processes(), remove it from the list of such processes
+ * by calling ap_unregister_extra_mpm_process().
+ */
+#ifdef AP_MPM_WANT_RECLAIM_CHILD_PROCESSES
+void ap_register_extra_mpm_process(pid_t pid);
+#endif
+
+/**
+ * Unregister an MPM child process which was previously registered by a
+ * call to ap_register_extra_mpm_process().
+ * @warning This is only defined if the MPM defines
+ *          AP_MPM_WANT_RECLAIM_CHILD_PROCESSES
+ * @param pid The process id of an MPM child process which no longer needs to
+ * be reclaimed.
+ * @return 1 if the process was found and removed, 0 otherwise
+ */
+#ifdef AP_MPM_WANT_RECLAIM_CHILD_PROCESSES
+int ap_unregister_extra_mpm_process(pid_t pid);
+#endif
+
+/**
  * Determine if any child process has died.  If no child process died, then
  * this process sleeps for the amount of time specified by the MPM defined
  * macro SCOREBOARD_MAINTENANCE_INTERVAL.
@@ -290,6 +321,18 @@
 extern apr_uint32_t ap_max_mem_free;
 extern const char *ap_mpm_set_max_mem_free(cmd_parms *cmd, void *dummy,
                                            const char *arg);
+#endif
+
+#ifdef AP_MPM_WANT_SET_STACKSIZE
+extern apr_size_t ap_thread_stacksize;
+extern const char *ap_mpm_set_thread_stacksize(cmd_parms *cmd, void *dummy,
+                                               const char *arg);
+#endif
+    
+#if AP_ENABLE_EXCEPTION_HOOK
+extern const char *ap_mpm_set_exception_hook(cmd_parms *cmd, void *dummy,
+                                             const char *arg);
+extern int ihs_exception_hook_enabled;
 #endif
 
 #ifdef __cplusplus
Index: include/scoreboard.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/include/scoreboard.h,v
retrieving revision 1.1.1.1
retrieving revision 1.5
diff -u -u -r1.1.1.1 -r1.5
--- include/scoreboard.h	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ include/scoreboard.h	24 Aug 2005 19:12:46 -0000	1.5
@@ -141,12 +141,14 @@
     apr_os_thread_t tid;
 #endif
     unsigned char status;
+    unsigned char short_module_index; /* does not change layout on IHS platforms */
     unsigned long access_count;
     apr_off_t     bytes_served;
     unsigned long my_access_count;
     apr_off_t     my_bytes_served;
     apr_off_t     conn_bytes;
     unsigned short conn_count;
+    unsigned char reserved2; /* does not change layout on IHS platforms */
     apr_time_t start_time;
     apr_time_t stop_time;
 #ifdef HAVE_TIMES
@@ -156,6 +158,7 @@
     char client[32];		/* Keep 'em small... */
     char request[64];		/* We just want an idea... */
     char vhost[32];	        /* What virtual host is being accessed? */
+    char reserved3[32];         /* After Apache fields */
 };
 
 typedef struct {
@@ -206,7 +209,7 @@
 AP_DECLARE(int) ap_update_child_status(ap_sb_handle_t *sbh, int status, request_rec *r);
 AP_DECLARE(int) ap_update_child_status_from_indexes(int child_num, int thread_num,
                                                     int status, request_rec *r);
-void ap_time_process_request(int child_num, int thread_num, int status);
+void ap_time_process_request(ap_sb_handle_t *sbh, int status);
 
 AP_DECLARE(worker_score *) ap_get_scoreboard_worker(int x, int y);
 AP_DECLARE(process_score *) ap_get_scoreboard_process(int x);
Index: modules/dav/fs/lock.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/dav/fs/lock.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- modules/dav/fs/lock.c	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ modules/dav/fs/lock.c	15 Sep 2004 12:56:42 -0000	1.3
@@ -105,7 +105,7 @@
 **    INDIRECT LOCK:   [char      (DAV_LOCK_INDIRECT),
 **			apr_uuid_t locktoken,
 **			time_t     expires,
-**			int        key_size,
+**			apr_size_t key_size,
 **			char[]     key]
 **       The key is to the collection lock that resulted in this indirect lock
 */
@@ -196,7 +196,7 @@
 /* Stored indirect lock info - lock token and apr_datum_t */
 #define dav_size_indirect(a)	(1 + sizeof(apr_uuid_t) \
 				 + sizeof(time_t) \
-				 + sizeof(int) + (a)->key.dsize)
+				 + sizeof((a)->key.dsize) + (a)->key.dsize)
 
 /*
 ** The lockdb structure.
@@ -691,7 +691,7 @@
 	    offset += sizeof(*ip->locktoken);
 	    memcpy(&ip->timeout, val.dptr + offset, sizeof(ip->timeout));
 	    offset += sizeof(ip->timeout);
-	    ip->key.dsize = *((int *) (val.dptr + offset));	/* length of datum */
+            memcpy(&ip->key.dsize, val.dptr + offset, sizeof(ip->key.dsize)); /* length of datum */
 	    offset += sizeof(ip->key.dsize);
 	    ip->key.dptr = apr_palloc(p, ip->key.dsize); 
 	    memcpy(ip->key.dptr, val.dptr + offset, ip->key.dsize);
@@ -1508,13 +1508,13 @@
 	}
 	if (dav_fs_do_refresh(dp_scan, ltl, new_time)) {
 	    /* the lock was refreshed. return the lock. */
-	    newlock = dav_fs_alloc_lock(lockdb, ip->key, dp->locktoken);
+	    newlock = dav_fs_alloc_lock(lockdb, ip->key, dp_scan->locktoken);
 	    newlock->is_locknull = !resource->exists;
-	    newlock->scope = dp->f.scope;
-	    newlock->type = dp->f.type;
-	    newlock->depth = dp->f.depth;
-	    newlock->timeout = dp->f.timeout;
-	    newlock->owner = dp->owner;
+	    newlock->scope = dp_scan->f.scope;
+	    newlock->type = dp_scan->f.type;
+	    newlock->depth = dp_scan->f.depth;
+	    newlock->timeout = dp_scan->f.timeout;
+	    newlock->owner = dp_scan->owner;
             newlock->auth_user = dp_scan->auth_user;
 
 	    newlock->next = *locks;
Index: modules/experimental/cache_cache.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/experimental/cache_cache.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/experimental/cache_cache.c	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ modules/experimental/cache_cache.c	5 Mar 2004 02:08:26 -0000	1.2
@@ -161,7 +161,7 @@
         /* FIX: If ejected is NULL, we'll segfault here */
         priority = c->get_pri(ejected);
 
-        if (c->queue_clock < priority)
+        if (c->queue_clock > priority)
             c->queue_clock = priority;
 
         cache_hash_set(c->ht,
Index: modules/experimental/cache_storage.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/experimental/cache_storage.c,v
retrieving revision 1.1.1.1
retrieving revision 1.5
diff -u -u -r1.1.1.1 -r1.5
--- modules/experimental/cache_storage.c	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ modules/experimental/cache_storage.c	13 Jan 2005 15:04:55 -0000	1.5
@@ -1,71 +1,22 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/* Copyright 2001-2004 The Apache Software Foundation
  *
- * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Apache" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- * Portions of this software are based upon public domain software
- * originally written at the National Center for Supercomputing Applications,
- * University of Illinois, Urbana-Champaign.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 #define CORE_PRIVATE
 
 #include "mod_cache.h"
 
-APR_HOOK_STRUCT(
-	APR_HOOK_LINK(remove_url)
-	APR_HOOK_LINK(create_entity)
-	APR_HOOK_LINK(open_entity)
-)
-
 extern APR_OPTIONAL_FN_TYPE(ap_cache_generate_key) *cache_generate_key;
 
 extern module AP_MODULE_DECLARE_DATA cache_module;
@@ -76,22 +27,25 @@
  * delete all URL entities from the cache
  *
  */
-int cache_remove_url(request_rec *r, const char *types, char *url)
+int cache_remove_url(request_rec *r, char *url)
 {
-    const char *next = types;
-    const char *type;
+    cache_provider_list *list;
     apr_status_t rv;
     char *key;
+    cache_request_rec *cache = (cache_request_rec *) 
+                         ap_get_module_config(r->request_config, &cache_module);
 
     rv = cache_generate_key(r,r->pool,&key);
     if (rv != APR_SUCCESS) {
         return rv;
     }
 
+    list = cache->providers;
+
     /* for each specified cache type, delete the URL */
-    while(next) {
-        type = ap_cache_tokstr(r->pool, next, &next);
-        cache_run_remove_url(type, key);
+    while(list) {
+        list->provider->remove_url(key);
+        list = list->next;
     }
     return OK;
 }
@@ -108,29 +62,32 @@
  * decide whether or not it wants to cache this particular entity.
  * If the size is unknown, a size of -1 should be set.
  */
-int cache_create_entity(request_rec *r, const char *types, char *url, apr_off_t size)
+int cache_create_entity(request_rec *r, char *url, apr_off_t size)
 {
+    cache_provider_list *list;
     cache_handle_t *h = apr_pcalloc(r->pool, sizeof(cache_handle_t));
-    const char *next = types;
-    const char *type;
     char *key;
     apr_status_t rv;
     cache_request_rec *cache = (cache_request_rec *) 
                          ap_get_module_config(r->request_config, &cache_module);
 
-    rv =  cache_generate_key(r,r->pool,&key);
+    rv = cache_generate_key(r,r->pool,&key);
     if (rv != APR_SUCCESS) {
         return rv;
     }
+
+    list = cache->providers;
     /* for each specified cache type, delete the URL */
-    while (next) {
-        type = ap_cache_tokstr(r->pool, next, &next);
-        switch (rv = cache_run_create_entity(h, r, type, key, size)) {
+    while (list) {
+        switch (rv = list->provider->create_entity(h, r, key, size)) {
         case OK: {
             cache->handle = h;
+            cache->provider = list->provider;
+            cache->provider_name = list->provider_name;
             return OK;
         }
         case DECLINED: {
+            list = list->next;
             continue;
         }
         default: {
@@ -141,19 +98,57 @@
     return DECLINED;
 }
 
-/*
- * remove a specific URL entity from the cache
- *
- * The specific entity referenced by the cache_handle is removed
- * from the cache, and the cache_handle is closed.
- */
-/* XXX Don't think we need to pass in request_rec or types ... */
-int cache_remove_entity(request_rec *r, const char *types, cache_handle_t *h)
+static int set_cookie_doo_doo(void *v, const char *key, const char *val)
 {
-    h->remove_entity(h);
+    apr_table_addn(v, key, val);
     return 1;
 }
 
+static void accept_headers(cache_handle_t *h, request_rec *r)
+{
+    apr_table_t *cookie_table;
+    const char *v;
+
+    v = apr_table_get(h->resp_hdrs, "Content-Type");
+    if (v) {
+        ap_set_content_type(r, v);
+        apr_table_unset(h->resp_hdrs, "Content-Type");
+    }
+
+    /* If the cache gave us a Last-Modified header, we can't just
+     * pass it on blindly because of restrictions on future values.
+     */
+    v = apr_table_get(h->resp_hdrs, "Last-Modified");
+    if (v) {
+        ap_update_mtime(r, apr_date_parse_http(v));
+        ap_set_last_modified(r);
+        apr_table_unset(h->resp_hdrs, "Last-Modified");
+    }
+
+    /* The HTTP specification says that it is legal to merge duplicate
+     * headers into one.  Some browsers that support Cookies don't like
+     * merged headers and prefer that each Set-Cookie header is sent
+     * separately.  Lets humour those browsers by not merging.
+     * Oh what a pain it is.
+     */
+    cookie_table = apr_table_make(r->pool, 2);
+    apr_table_do(set_cookie_doo_doo, cookie_table, r->err_headers_out,
+                 "Set-Cookie", NULL);
+    apr_table_do(set_cookie_doo_doo, cookie_table, h->resp_hdrs,
+                 "Set-Cookie", NULL);
+    apr_table_unset(r->err_headers_out, "Set-Cookie");
+    apr_table_unset(h->resp_hdrs, "Set-Cookie");
+
+    apr_table_overlap(r->headers_out, h->resp_hdrs,
+                      APR_OVERLAP_TABLES_SET);
+    apr_table_overlap(r->err_headers_out, h->resp_err_hdrs,
+                      APR_OVERLAP_TABLES_SET);
+    if (!apr_is_empty_table(cookie_table)) {
+        r->err_headers_out = apr_table_overlay(r->pool, r->err_headers_out,
+                                               cookie_table);
+    }
+}
+
 /*
  * select a specific URL entity in the cache
  *
@@ -165,29 +160,32 @@
  * This function returns OK if successful, DECLINED if no
  * cached entity fits the bill.
  */
-int cache_select_url(request_rec *r, const char *types, char *url)
+int cache_select_url(request_rec *r, char *url)
 {
-    const char *next = types;
-    const char *type;
+    cache_provider_list *list;
     apr_status_t rv;
     cache_handle_t *h;
     char *key;
     cache_request_rec *cache = (cache_request_rec *) 
                          ap_get_module_config(r->request_config, &cache_module);
 
-    rv =  cache_generate_key(r,r->pool,&key);
+    rv = cache_generate_key(r, r->pool, &key);
     if (rv != APR_SUCCESS) {
         return rv;
     }
     /* go through the cache types till we get a match */
-    h = cache->handle = apr_palloc(r->pool, sizeof(cache_handle_t));
+    h = apr_palloc(r->pool, sizeof(cache_handle_t));
+
+    list = cache->providers;
 
-    while (next) {
-        type = ap_cache_tokstr(r->pool, next, &next);
-        switch ((rv = cache_run_open_entity(h, r, type, key))) {
+    while (list) {
+        switch ((rv = list->provider->open_entity(h, r, key))) {
         case OK: {
             char *vary = NULL;
-            if (cache_read_entity_headers(h, r) != APR_SUCCESS) {
+            const char *varyhdr = NULL;
+            int fresh;
+
+            if (list->provider->recall_headers(h, r) != APR_SUCCESS) {
                 /* TODO: Handle this error */
                 return DECLINED;
             }
@@ -195,21 +193,25 @@
             /*
              * Check Content-Negotiation - Vary
              * 
-             * At this point we need to make sure that the object we found in the cache
-             * is the same object that would be delivered to the client, when the
-             * effects of content negotiation are taken into effect.
-             * 
+             * At this point we need to make sure that the object we found in
+             * the cache is the same object that would be delivered to the
+             * client, when the effects of content negotiation are taken into
+             * effect.
+             *
              * In plain english, we want to make sure that a language-negotiated
              * document in one language is not given to a client asking for a
              * language negotiated document in a different language by mistake.
-             * 
+             *
              * This code makes the assumption that the storage manager will
              * cache the req_hdrs if the response contains a Vary
              * header.
-             * 
+             *
              * RFC2616 13.6 and 14.44 describe the Vary mechanism.
              */
-            vary = apr_pstrdup(r->pool, apr_table_get(r->headers_out, "Vary"));
+            if ((varyhdr = apr_table_get(h->resp_err_hdrs, "Vary")) == NULL) {
+                varyhdr = apr_table_get(h->resp_hdrs, "Vary");
+            }
+            vary = apr_pstrdup(r->pool, varyhdr);
             while (vary && *vary) {
                 char *name = vary;
                 const char *h1, *h2;
@@ -236,62 +238,65 @@
                 }
                 else {
                     /* headers do not match, so Vary failed */
-                    ap_log_error(APLOG_MARK, APLOG_INFO, APR_SUCCESS, r->server,
-                                 "cache_select_url(): Vary header mismatch - Cached document cannot be used. \n");
-                    apr_table_clear(r->headers_out);
-                    r->status_line = NULL;
-                    cache->handle = NULL;
+                    ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS,
+                                r->server,
+                                "cache_select_url(): Vary header mismatch.");
                     return DECLINED;
                 }
             }
+
+            cache->provider = list->provider;
+            cache->provider_name = list->provider_name;
+
+            /* Is our cached response fresh enough? */
+            fresh = ap_cache_check_freshness(h, r);
+            if (!fresh) {
+                cache_info *info = &(h->cache_obj->info);
+
+                /* Make response into a conditional */
+                /* FIXME: What if the request is already conditional? */
+                if (info && info->etag) {
+                    /* if we have a cached etag */
+                    cache->stale_headers = apr_table_copy(r->pool,
+                                                          r->headers_in);
+                    apr_table_set(r->headers_in, "If-None-Match", info->etag);
+                    cache->stale_handle = h;
+                }
+                else if (info && info->lastmods) {
+                    /* if we have a cached Last-Modified header */
+                    cache->stale_headers = apr_table_copy(r->pool,
+                                                          r->headers_in);
+                    apr_table_set(r->headers_in, "If-Modified-Since",
+                                  info->lastmods);
+                    cache->stale_handle = h;
+                }
+
+                return DECLINED;
+            }
+
+            /* Okay, this response looks okay.  Merge in our stuff and go. */
+            apr_table_setn(r->headers_out, "Content-Type",
+                           ap_make_content_type(r, h->content_type));
+            r->filename = apr_pstrdup(r->pool, h->cache_obj->info.filename);
+            accept_headers(h, r);
+
+            cache->handle = h;
             return OK;
         }
         case DECLINED: {
             /* try again with next cache type */
+            list = list->next;
             continue;
         }
         default: {
             /* oo-er! an error */
-            cache->handle = NULL;
             return rv;
         }
         }
     }
-    cache->handle = NULL;
     return DECLINED;
 }
 
-apr_status_t cache_write_entity_headers(cache_handle_t *h, 
-                                        request_rec *r, 
-                                        cache_info *info)
-{
-    return (h->write_headers(h, r, info));
-}
-apr_status_t cache_write_entity_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b) 
-{
-    return (h->write_body(h, r, b));
-}
-
-apr_status_t cache_read_entity_headers(cache_handle_t *h, request_rec *r)
-{
-    apr_status_t rv;
-    cache_info *info = &(h->cache_obj->info);
-
-    /* Build the header table from info in the info struct */
-    rv = h->read_headers(h, r);
-    if (rv != APR_SUCCESS) {
-        return rv;
-    }
-
-    r->filename = apr_pstrdup(r->pool, info->filename );
-
-    return APR_SUCCESS;
-}
-apr_status_t cache_read_entity_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *b) 
-{
-    return (h->read_body(h, p, b));
-}
-
 apr_status_t cache_generate_key_default( request_rec *r, apr_pool_t*p, char**key ) 
 {
     if (r->hostname) {
@@ -302,17 +307,4 @@
     }
     return APR_SUCCESS;
 }
-
-APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(cache, CACHE, int, create_entity, 
-                                      (cache_handle_t *h, request_rec *r, const char *type, 
-                                      const char *urlkey, apr_off_t len),
-                                      (h, r, type,urlkey,len),DECLINED)
-APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(cache, CACHE, int, open_entity,  
-                                      (cache_handle_t *h, request_rec *r, const char *type, 
-                                      const char *urlkey),(h,r,type,urlkey),
-                                      DECLINED)
-APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL(cache, CACHE, int, remove_url, 
-                                    (const char *type, const char *urlkey),
-                                    (type,urlkey),OK,DECLINED)
-
 
Index: modules/experimental/cache_util.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/experimental/cache_util.c,v
retrieving revision 1.1.1.1
retrieving revision 1.5
diff -u -u -r1.1.1.1 -r1.5
--- modules/experimental/cache_util.c	29 Jul 2003 20:19:20 -0000	1.1.1.1
+++ modules/experimental/cache_util.c	13 Jan 2005 15:04:55 -0000	1.5
@@ -1,155 +1,115 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/* Copyright 2001-2004 The Apache Software Foundation
  *
- * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
- * reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Apache" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- * Portions of this software are based upon public domain software
- * originally written at the National Center for Supercomputing Applications,
- * University of Illinois, Urbana-Champaign.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 #define CORE_PRIVATE
 
 #include "mod_cache.h"
 
-
+#include <ap_provider.h>
 
 /* -------------------------------------------------------------- */
 
 /* return true if the request is conditional */
-CACHE_DECLARE(int) ap_cache_request_is_conditional(request_rec *r)
+CACHE_DECLARE(int) ap_cache_request_is_conditional(apr_table_t *table)
 {
-    if (apr_table_get(r->headers_in, "If-Match") ||
-        apr_table_get(r->headers_in, "If-None-Match") ||
-        apr_table_get(r->headers_in, "If-Modified-Since") ||
-        apr_table_get(r->headers_in, "If-Unmodified-Since")) {
-
+    if (apr_table_get(table, "If-Match") ||
+        apr_table_get(table, "If-None-Match") ||
+        apr_table_get(table, "If-Modified-Since") ||
+        apr_table_get(table, "If-Unmodified-Since")) {
         return 1;
     }
     return 0;
 }
 
-
-/* remove other filters from filter stack */
-CACHE_DECLARE(void) ap_cache_reset_output_filters(request_rec *r)
-{
-    ap_filter_t *f = r->output_filters;
-
-    while (f) {
-        if (!strcasecmp(f->frec->name, "CORE") ||
-            !strcasecmp(f->frec->name, "CONTENT_LENGTH") ||
-            !strcasecmp(f->frec->name, "HTTP_HEADER")) {
-            f = f->next;
-            continue;
-        }
-        else {
-            ap_remove_output_filter(f);
-            f = f->next;
-        }
-    }
-}
-
-CACHE_DECLARE(const char *)ap_cache_get_cachetype(request_rec *r, 
+CACHE_DECLARE(cache_provider_list *)ap_cache_get_providers(request_rec *r,
                                                   cache_server_conf *conf, 
                                                   const char *url)
 {
-    const char *type = NULL;
+    cache_provider_list *providers = NULL;
     int i;
 
     /* we can't cache if there's no URL */
+    /* Is this case even possible?? */
     if (!url) return NULL;
 
     /* loop through all the cacheenable entries */
     for (i = 0; i < conf->cacheenable->nelts; i++) {
         struct cache_enable *ent = 
                                 (struct cache_enable *)conf->cacheenable->elts;
-        const char *thisurl = ent[i].url;
-        const char *thistype = ent[i].type;
-        if ((thisurl) && !strncasecmp(thisurl, url, strlen(thisurl))) {
-            if (!type) {
-                type = thistype;
+        if ((ent[i].url) && !strncasecmp(url, ent[i].url, ent[i].urllen)) {
+            /* Fetch from global config and add to the list. */
+            cache_provider *provider;
+            provider = ap_lookup_provider(CACHE_PROVIDER_GROUP, ent[i].type,
+                                          "0");
+            if (!provider) {
+                /* Log an error! */
             }
             else {
-                type = apr_pstrcat(r->pool, type, ",", thistype, NULL);
+                cache_provider_list *newp;
+                newp = apr_pcalloc(r->pool, sizeof(cache_provider_list));
+                newp->provider_name = ent[i].type;
+                newp->provider = provider;
+
+                if (!providers) {
+                    providers = newp;
+                }
+                else {
+                    cache_provider_list *last = providers;
+
+                    while (last->next) {
+                        last = last->next;
+                    }
+                    last->next = newp;
+                }
             }
         }
     }
 
-    /* then loop through all the cachedisable entries */
-    /* Looking for urls that contain the full cachedisable url and possibly more. */
-    /*   This means we are disabling cachedisable url and below... */
+    /* then loop through all the cachedisable entries
+     * Looking for urls that contain the full cachedisable url and possibly
+     * more.
+     * This means we are disabling cachedisable url and below...
+     */
     for (i = 0; i < conf->cachedisable->nelts; i++) {
         struct cache_disable *ent = 
                                (struct cache_disable *)conf->cachedisable->elts;
-        const char *thisurl = ent[i].url;
-        if ((thisurl) && !strncasecmp(thisurl, url, strlen(thisurl))) {
-            type = NULL;
+        if ((ent[i].url) && !strncasecmp(url, ent[i].url, ent[i].urllen)) {
+            /* Stop searching now. */
+            return NULL;
         }
     }
 
-    return type;
+    return providers;
 }
 
 
 /* do a HTTP/1.1 age calculation */
-CACHE_DECLARE(apr_int64_t) ap_cache_current_age(cache_info *info, const apr_time_t age_value,
+CACHE_DECLARE(apr_int64_t) ap_cache_current_age(cache_info *info,
+                                                const apr_time_t age_value,
                                                 apr_time_t now)
 {
-    apr_time_t apparent_age, corrected_received_age, response_delay, corrected_initial_age,
-           resident_time, current_age;
+    apr_time_t apparent_age, corrected_received_age, response_delay,
+               corrected_initial_age, resident_time, current_age,
+               age_value_usec;
+
+    age_value_usec = apr_time_from_sec(age_value);
 
     /* Perform an HTTP/1.1 age calculation. (RFC2616 13.2.3) */
 
     apparent_age = MAX(0, info->response_time - info->date);
-    corrected_received_age = MAX(apparent_age, age_value);
+    corrected_received_age = MAX(apparent_age, age_value_usec);
     response_delay = info->response_time - info->request_time;
     corrected_initial_age = corrected_received_age + response_delay;
     resident_time = now - info->response_time;
@@ -158,21 +118,24 @@
     return apr_time_sec(current_age);
 }
 
-CACHE_DECLARE(int) ap_cache_check_freshness(cache_request_rec *cache, 
+CACHE_DECLARE(int) ap_cache_check_freshness(cache_handle_t *h,
                                             request_rec *r)
 {
-    apr_int64_t age, maxage_req, maxage_cresp, maxage, smaxage, maxstale, minfresh;
-    const char *cc_cresp, *cc_req, *pragma_cresp;
+    apr_int64_t age, maxage_req, maxage_cresp, maxage, smaxage, maxstale;
+    apr_int64_t minfresh;
+    int age_in_errhdr = 0;
+    const char *cc_cresp, *cc_ceresp, *cc_req;
     const char *agestr = NULL;
+    const char *expstr = NULL;
     char *val;
     apr_time_t age_c = 0;
-    cache_info *info = &(cache->handle->cache_obj->info);
+    cache_info *info = &(h->cache_obj->info);
 
     /*
      * We now want to check if our cached data is still fresh. This depends
      * on a few things, in this order:
      *
-     * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache no-cache in
+     * - RFC2616 14.9.4 End to end reload, Cache-Control: no-cache. no-cache in
      * either the request or the cached response means that we must
      * revalidate the request unconditionally, overriding any expiration
      * mechanism. It's equivalent to max-age=0,must-revalidate.
@@ -200,86 +163,164 @@
      * entity, and it's value is in the past, it has expired.
      * 
      */
-    cc_cresp = apr_table_get(r->headers_out, "Cache-Control");
-    cc_req = apr_table_get(r->headers_in, "Cache-Control");
-    /* TODO: pragma_cresp not being used? */
-    pragma_cresp = apr_table_get(r->headers_out, "Pragma");  
-    if ((agestr = apr_table_get(r->headers_out, "Age"))) {
+    cc_cresp = apr_table_get(h->resp_hdrs, "Cache-Control");
+    cc_ceresp = apr_table_get(h->resp_err_hdrs, "Cache-Control");
+    cc_req = apr_table_get(h->req_hdrs, "Cache-Control");
+
+    if ((agestr = apr_table_get(h->resp_hdrs, "Age"))) {
         age_c = apr_atoi64(agestr);
     }
+    else if ((agestr = apr_table_get(h->resp_err_hdrs, "Age"))) {
+        age_c = apr_atoi64(agestr);
+        age_in_errhdr = 1;
+    }
+
+    if (!(expstr = apr_table_get(h->resp_err_hdrs, "Expires"))) {
+        expstr = apr_table_get(h->resp_hdrs, "Expires");
+    }
 
     /* calculate age of object */
     age = ap_cache_current_age(info, age_c, r->request_time);
 
     /* extract s-maxage */
-    if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "s-maxage", &val))
+    if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "s-maxage", &val)) {
         smaxage = apr_atoi64(val);
-    else
+    }
+    else if (cc_ceresp && ap_cache_liststr(r->pool, cc_ceresp, "s-maxage", &val)) {
+        smaxage = apr_atoi64(val);
+    }
+    else {
         smaxage = -1;
+    }
 
     /* extract max-age from request */
-    if (cc_req && ap_cache_liststr(r->pool, cc_req, "max-age", &val))
+    if (cc_req && ap_cache_liststr(r->pool, cc_req, "max-age", &val)) {
         maxage_req = apr_atoi64(val);
-    else
+    }
+    else {
         maxage_req = -1;
+    }
 
     /* extract max-age from response */
-    if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "max-age", &val))
+    if (cc_cresp && ap_cache_liststr(r->pool, cc_cresp, "max-age", &val)) {
         maxage_cresp = apr_atoi64(val);
+    }
+    else if (cc_ceresp && ap_cache_liststr(r->pool, cc_ceresp, "max-age", &val)) {
+        maxage_cresp = apr_atoi64(val);
+    }
     else
+    {
         maxage_cresp = -1;
+    }
 
     /*
      * if both maxage request and response, the smaller one takes priority
      */
-    if (-1 == maxage_req)
+    if (-1 == maxage_req) {
         maxage = maxage_cresp;
-    else if (-1 == maxage_cresp)
+    }
+    else if (-1 == maxage_cresp) {
         maxage = maxage_req;
-    else
+    }
+    else {
         maxage = MIN(maxage_req, maxage_cresp);
+    }
 
     /* extract max-stale */
-    if (cc_req && ap_cache_liststr(r->pool, cc_req, "max-stale", &val))
+    if (cc_req && ap_cache_liststr(r->pool, cc_req, "max-stale", &val)) {
         maxstale = apr_atoi64(val);
-    else
+    }
+    else {
         maxstale = 0;
+    }
 
     /* extract min-fresh */
-    if (cc_req && ap_cache_liststr(r->pool, cc_req, "min-fresh", &val))
+    if (cc_req && ap_cache_liststr(r->pool, cc_req, "min-fresh", &val)) {
         minfresh = apr_atoi64(val);
-    else
+    }
+    else {
         minfresh = 0;
+    }
 
     /* override maxstale if must-revalidate or proxy-revalidate */
     if (maxstale && ((cc_cresp &&
-                      ap_cache_liststr(NULL,
-                                       cc_cresp, "must-revalidate", NULL))
-                     || (cc_cresp && ap_cache_liststr(NULL,
-                                                      cc_cresp,
-                                                      "proxy-revalidate", NULL))))
+                      ap_cache_liststr(NULL, cc_cresp,
+                                       "must-revalidate", NULL)) ||
+                     (cc_cresp &&
+                      ap_cache_liststr(NULL, cc_cresp,
+                                       "proxy-revalidate", NULL)) ||
+                     (cc_ceresp &&
+                      ap_cache_liststr(NULL, cc_ceresp,
+                                       "must-revalidate", NULL)) ||
+                     (cc_ceresp &&
+                      ap_cache_liststr(NULL, cc_ceresp,
+                                       "proxy-revalidate", NULL)))) {
         maxstale = 0;
+    }
+
     /* handle expiration */
-    if ((-1 < smaxage && age < (smaxage - minfresh)) ||
-        (-1 < maxage && age < (maxage + maxstale - minfresh)) ||
-        (info->expire != APR_DATE_BAD && age < (apr_time_sec(info->expire - info->date) + maxstale - minfresh))) {
+    if (((smaxage != -1) && (age < (smaxage - minfresh))) ||
+        ((maxage != -1) && (age < (maxage + maxstale - minfresh))) ||
+        ((smaxage == -1) && (maxage == -1) &&
+         (info->expire != APR_DATE_BAD) &&
+         (age < (apr_time_sec(info->expire - info->date) + maxstale - minfresh)))) {
+        const char *warn_head;
+        apr_table_t *head_ptr;
+
+        warn_head = apr_table_get(h->resp_hdrs, "Warning");
+        if (warn_head != NULL) {
+            head_ptr = h->resp_hdrs;
+        }
+        else {
+            warn_head = apr_table_get(h->resp_err_hdrs, "Warning");
+            head_ptr = h->resp_err_hdrs;
+        }
+
         /* it's fresh darlings... */
         /* set age header on response */
-        apr_table_set(r->headers_out, "Age",
-                      apr_psprintf(r->pool, "%lu", (unsigned long)age));
+        if (age_in_errhdr) {
+            apr_table_set(h->resp_err_hdrs, "Age",
+                          apr_psprintf(r->pool, "%lu", (unsigned long)age));
+        }
+        else {
+            apr_table_set(h->resp_hdrs, "Age",
+                          apr_psprintf(r->pool, "%lu", (unsigned long)age));
+        }
 
         /* add warning if maxstale overrode freshness calculation */
-        if (!((-1 < smaxage && age < smaxage) ||
-              (-1 < maxage && age < maxage) ||
-              (info->expire != APR_DATE_BAD && (info->expire - info->date) > age))) {
+        if (!(((smaxage != -1) && age < smaxage) ||
+              ((maxage != -1) && age < maxage) ||
+              (info->expire != APR_DATE_BAD &&
+               (info->expire - info->date) > age))) {
             /* make sure we don't stomp on a previous warning */
-            apr_table_merge(r->headers_out, "Warning", "110 Response is stale");
+            if ((warn_head == NULL) ||
+                ((warn_head != NULL) && (ap_strstr_c(warn_head, "110") == NULL))) {
+                apr_table_merge(head_ptr, "Warning", "110 Response is stale");
+            }
+        }
+        /* 
+         * If none of Expires, Cache-Control: max-age, or Cache-Control: 
+         * s-maxage appears in the response, and the respose header age 
+         * calculated is more than 24 hours add the warning 113 
+         */
+        if ((maxage_cresp == -1) && (smaxage == -1) &&
+            (expstr == NULL) && (age > 86400)) {
+
+            /* Make sure we don't stomp on a previous warning, and don't dup
+             * a 113 marning that is already present. Also, make sure to add
+             * the new warning to the correct *headers_out location.
+             */
+            if ((warn_head == NULL) ||
+                ((warn_head != NULL) && (ap_strstr_c(warn_head, "113") == NULL))) {
+                apr_table_merge(head_ptr, "Warning", "113 Heuristic expiration");
+            }
         }
-        return 1;    /* Cache object is fresh */
+        return 1;    /* Cache object is fresh (enough) */
     }
     return 0;        /* Cache object is stale */
 }
-/* 
+
+/*
  * list is a comma-separated list of case-insensitive tokens, with
  * optional whitespace around the tokens.
  * The return returns 1 if the token val is found in the list, or 0
@@ -356,7 +397,8 @@
 }
 
 /* return each comma separated token, one at a time */
-CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list, const char **str)
+CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list,
+                                           const char **str)
 {
     apr_size_t i;
     const char *s;
@@ -463,24 +505,26 @@
     val[i + 22 - k] = '\0';
 }
 
-CACHE_DECLARE(char *)generate_name(apr_pool_t *p, int dirlevels, int dirlength, const char *name)
+CACHE_DECLARE(char *)generate_name(apr_pool_t *p, int dirlevels,
+                                   int dirlength, const char *name)
 {
     char hashfile[66];
     cache_hash(name, hashfile, dirlevels, dirlength);
     return apr_pstrdup(p, hashfile);
 }
 
-/* Create a new table consisting of those elements from a request_rec's
- * headers_out that are allowed to be stored in a cache.
+/* Create a new table consisting of those elements from an input
+ * headers table that are allowed to be stored in a cache.
  */
-CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_hdrs_out(request_rec *r)
+CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_hdrs_out(apr_pool_t *pool,
+                                                        apr_table_t *t)
 {
-    /* Make a copy of the response headers, and remove from
+    /* Make a copy of the headers, and remove from
      * the copy any hop-by-hop headers, as defined in Section
      * 13.5.1 of RFC 2616
      */
     apr_table_t *headers_out;
-    headers_out = apr_table_copy(r->pool, r->headers_out);
+    headers_out = apr_table_copy(pool, t);
     apr_table_unset(headers_out, "Connection");
     apr_table_unset(headers_out, "Keep-Alive");
     apr_table_unset(headers_out, "Proxy-Authenticate");
Index: modules/experimental/mod_cache.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/experimental/mod_cache.c,v
retrieving revision 1.1.1.1
retrieving revision 1.7
diff -u -u -r1.1.1.1 -r1.7
--- modules/experimental/mod_cache.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/experimental/mod_cache.c	13 Jan 2005 15:15:44 -0000	1.7
@@ -1,59 +1,16 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/* Copyright 2000-2004 The Apache Software Foundation
  *
- * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Apache" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- * Portions of this software are based upon public domain software
- * originally written at the National Center for Supercomputing Applications,
- * University of Illinois, Urbana-Champaign.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 #define CORE_PRIVATE
@@ -69,9 +26,8 @@
 /* Handles for cache filters, resolved at startup to eliminate
  * a name-to-function mapping on each request
  */
-static ap_filter_rec_t *cache_in_filter_handle;
+static ap_filter_rec_t *cache_save_filter_handle;
 static ap_filter_rec_t *cache_out_filter_handle;
-static ap_filter_rec_t *cache_conditional_filter_handle;
 
 /*
  * CACHE handler
@@ -83,7 +39,7 @@
  * If no:
  *   check whether we're allowed to try cache it
  *   If yes:
- *     add CACHE_IN filter
+ *     add CACHE_SAVE filter
  *   If No:
  *     oh well.
  */
@@ -91,59 +47,52 @@
 static int cache_url_handler(request_rec *r, int lookup)
 {
     apr_status_t rv;
-    const char *cc_in, *pragma, *auth;
-    apr_uri_t uri = r->parsed_uri;
-    char *url = r->unparsed_uri;
-    apr_size_t urllen;
-    char *path = uri.path;
-    const char *types;
-    cache_info *info = NULL;
+    const char *pragma, *auth;
+    apr_uri_t uri;
+    char *url;
+    char *path;
+    cache_provider_list *providers;
+    cache_info *info;
     cache_request_rec *cache;
     cache_server_conf *conf;
+    apr_bucket_brigade *out;
 
-    conf = (cache_server_conf *) ap_get_module_config(r->server->module_config,
-                                                      &cache_module);
-
-    /* we don't handle anything but GET */
+    /* Delay initialization until we know we are handling a GET */
     if (r->method_number != M_GET) {
         return DECLINED;
     }
 
+    uri = r->parsed_uri;
+    url = r->unparsed_uri;
+    path = uri.path;
+    info = NULL;
+
+    conf = (cache_server_conf *) ap_get_module_config(r->server->module_config,
+                                                      &cache_module);
+
     /*
      * Which cache module (if any) should handle this request?
      */
-    if (!(types = ap_cache_get_cachetype(r, conf, path))) {
-        return DECLINED;
-    }
-
-    urllen = strlen(url);
-    if (urllen > MAX_URL_LENGTH) {
-        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
-                     "cache: URL exceeds length threshold: %s", url);
-        return DECLINED;
-    }
-    /* DECLINE urls ending in / ??? EGP: why? */
-    if (url[urllen-1] == '/') {
+    if (!(providers = ap_cache_get_providers(r, conf, path))) {
         return DECLINED;
     }
 
     /* make space for the per request config */
-    cache = (cache_request_rec *) ap_get_module_config(r->request_config, 
+    cache = (cache_request_rec *) ap_get_module_config(r->request_config,
                                                        &cache_module);
     if (!cache) {
         cache = apr_pcalloc(r->pool, sizeof(cache_request_rec));
         ap_set_module_config(r->request_config, &cache_module, cache);
     }
 
-    /* save away the type */
-    cache->types = types;
+    /* save away the possible providers */
+    cache->providers = providers;
 
     /*
      * Are we allowed to serve cached info at all?
      */
 
     /* find certain cache controlling headers */
-    cc_in = apr_table_get(r->headers_in, "Cache-Control");
     pragma = apr_table_get(r->headers_in, "Pragma");
     auth = apr_table_get(r->headers_in, "Authorization");
 
@@ -166,13 +115,11 @@
                      "%s, but we know better and are ignoring it", url);
     }
     else {
-        if (ap_cache_liststr(NULL, cc_in, "no-store", NULL) ||
-            ap_cache_liststr(NULL, pragma, "no-cache", NULL) || (auth != NULL)) {
-            /* delete the previously cached file */
-            cache_remove_url(r, cache->types, url);
-
+        if (ap_cache_liststr(NULL, pragma, "no-cache", NULL) ||
+            auth != NULL) {
             ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
-                         "cache: no-store forbids caching of %s", url);
+                         "cache: no-cache or authorization forbids caching "
+                         "of %s", url);
             return DECLINED;
         }
     }
@@ -180,152 +127,70 @@
     /*
      * Try to serve this request from the cache.
      *
-     * If no existing cache file
-     *   add cache_in filter
-     * If stale cache file
-     *   If conditional request
-     *     add cache_in filter
-     *   If non-conditional request
-     *     fudge response into a conditional
-     *     add cache_conditional filter
-     * If fresh cache file
+     * If no existing cache file (DECLINED)
+     *   add cache_save filter
+     * If cached file (OK)
      *   clear filter stack
      *   add cache_out filter
+     *   return OK
      */
-
-    rv = cache_select_url(r, cache->types, url);
-    if (DECLINED == rv) {
-        if (!lookup) {
-            /* no existing cache file */
-            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
-                         "cache: no cache - add cache_in filter and DECLINE");
-            /* add cache_in filter to cache this request */
-            ap_add_output_filter_handle(cache_in_filter_handle, NULL, r,
-                                        r->connection);
+    rv = cache_select_url(r, url);
+    if (rv != OK) {
+        if (rv == DECLINED) {
+            if (!lookup) {
+                /* add cache_save filter to cache this request */
+                ap_add_output_filter_handle(cache_save_filter_handle, NULL, r,
+                                            r->connection);
+            }
+        }
+        else {
+            /* error */
+            ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
+                         "cache: error returned while checking for cached "
+                         "file by %s cache", cache->provider_name);
         }
         return DECLINED;
     }
-    else if (OK == rv) {
-        /* RFC2616 13.2 - Check cache object expiration */
-        cache->fresh = ap_cache_check_freshness(cache, r);
-        if (cache->fresh) {
-            /* fresh data available */
-            apr_bucket_brigade *out;
-            conn_rec *c = r->connection;
 
-            if (lookup) {
-                return OK;
-            }
-            rv = ap_meets_conditions(r);
-            if (rv != OK) {
-                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
-                             "cache: fresh cache - returning status %d", rv);
-                return rv;
-            }
+    /* We have located a suitable cache file now. */
+    info = &(cache->handle->cache_obj->info);
 
-            /*
-             * Not a conditionl request. Serve up the content 
-             */
-            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
-                         "cache: fresh cache - add cache_out filter and "
-                         "handle request");
+    if (info && info->lastmod) {
+        ap_update_mtime(r, info->lastmod);
+    }
 
-            /* We are in the quick handler hook, which means that no output
-             * filters have been set. So lets run the insert_filter hook.
-             */
-            ap_run_insert_filter(r);
-            ap_add_output_filter_handle(cache_out_filter_handle, NULL,
-                                        r, r->connection);
-
-            /* kick off the filter stack */
-            out = apr_brigade_create(r->pool, c->bucket_alloc);
-            if (APR_SUCCESS
-                != (rv = ap_pass_brigade(r->output_filters, out))) {
-                ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
-                             "cache: error returned while trying to return %s "
-                             "cached data", 
-                             cache->type);
-                return rv;
-            }
-            return OK;
-        }
-        else {
-	    r->err_headers_out = apr_table_make(r->pool, 3);
-            /* stale data available */
-            if (lookup) {
-                return DECLINED;
-            }
+    rv = ap_meets_conditions(r);
+    if (rv != OK) {
+        /* Return cached status. */
+        return rv;
+    }
 
-            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
-                         "cache: stale cache - test conditional");
-            /* if conditional request */
-            if (ap_cache_request_is_conditional(r)) {
-                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, 
-                             r->server,
-                             "cache: conditional - add cache_in filter and "
-                             "DECLINE");
-                /* Why not add CACHE_CONDITIONAL? */
-                ap_add_output_filter_handle(cache_in_filter_handle, NULL,
-                                            r, r->connection);
+    /* If we're a lookup, we can exit now instead of serving the content. */
+    if (lookup) {
+        return OK;
+    }
 
-                return DECLINED;
-            }
-            /* else if non-conditional request */
-            else {
-                /* fudge response into a conditional */
-                if (info && info->etag) {
-                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, 
-                                 r->server,
-                                 "cache: nonconditional - fudge conditional "
-                                 "by etag");
-                    /* if we have a cached etag */
-                    apr_table_set(r->headers_in, "If-None-Match", info->etag);
-                }
-                else if (info && info->lastmods) {
-                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, 
-                                 r->server,
-                                 "cache: nonconditional - fudge conditional "
-                                 "by lastmod");
-                    /* if we have a cached IMS */
-                    apr_table_set(r->headers_in, 
-                                  "If-Modified-Since", 
-                                  info->lastmods);
-                }
-                else {
-                    /* something else - pretend there was no cache */
-                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, 
-                                 r->server,
-                                 "cache: nonconditional - no cached "
-                                 "etag/lastmods - add cache_in and DECLINE");
-
-                    ap_add_output_filter_handle(cache_in_filter_handle, NULL,
-                                                r, r->connection);
-
-                    return DECLINED;
-                }
-                /* add cache_conditional filter */
-                ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, 
-                             r->server,
-                             "cache: nonconditional - add cache_conditional "
-                             "and DECLINE");
-                ap_add_output_filter_handle(cache_conditional_filter_handle,
-                                            NULL, 
-                                            r, 
-                                            r->connection);
+    /* Serve up the content */
 
-                return DECLINED;
-            }
-        }
-    }
-    else {
-        /* error */
-        ap_log_error(APLOG_MARK, APLOG_ERR, rv, 
-                     r->server,
-                     "cache: error returned while checking for cached file by "
-                     "%s cache", 
-                     cache->type);
-        return DECLINED;
+    /* We are in the quick handler hook, which means that no output
+     * filters have been set. So lets run the insert_filter hook.
+     */
+    ap_run_insert_filter(r);
+    ap_add_output_filter_handle(cache_out_filter_handle, NULL,
+                                r, r->connection);
+
+    /* kick off the filter stack */
+    out = apr_brigade_create(r->pool, r->connection->bucket_alloc);
+    rv = ap_pass_brigade(r->output_filters, out);
+    if (rv != APR_SUCCESS) {
+        ap_log_error(APLOG_MARK, APLOG_ERR, rv, r->server,
+                     "cache: error returned while trying to return %s "
+                     "cached data", 
+                     cache->provider_name);
+        return rv;
     }
+
+    return OK;
 }
 
 /*
@@ -354,8 +219,8 @@
     ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, r->server,
                  "cache: running CACHE_OUT filter");
 
-    /* cache_read_entity_headers() was called in cache_select_url() */
-    cache_read_entity_body(cache->handle, r->pool, bb);
+    /* recall_headers() was called in cache_select_url() */
+    cache->provider->recall_body(cache->handle, r->pool, bb);
 
     /* This filter is done once it has served up its content */
     ap_remove_output_filter(f);
@@ -367,59 +232,30 @@
 
 
 /*
- * CACHE_CONDITIONAL filter
- * ------------------------
- *
- * Decide whether or not cached content should be delivered
- * based on our fudged conditional request.
- * If response HTTP_NOT_MODIFIED
- *   replace ourselves with cache_out filter
- * Otherwise
- *   replace ourselves with cache_in filter
- */
-
-static int cache_conditional_filter(ap_filter_t *f, apr_bucket_brigade *in)
-{
-    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, f->r->server,
-                 "cache: running CACHE_CONDITIONAL filter");
-
-    if (f->r->status == HTTP_NOT_MODIFIED) {
-        /* replace ourselves with CACHE_OUT filter */
-        ap_add_output_filter_handle(cache_out_filter_handle, NULL,
-                                    f->r, f->r->connection);
-    }
-    else {
-        /* replace ourselves with CACHE_IN filter */
-        ap_add_output_filter_handle(cache_in_filter_handle, NULL,
-                                    f->r, f->r->connection);
-    }
-    ap_remove_output_filter(f);
-
-    return ap_pass_brigade(f->next, in);
-}
-
-
-/*
- * CACHE_IN filter
+ * CACHE_SAVE filter
  * ---------------
  *
  * Decide whether or not this content should be cached.
- * If we decide no it should:
+ * If we decide no it should not:
  *   remove the filter from the chain
  * If we decide yes it should:
- *   pass the data to the storage manager
- *   pass the data to the next filter (the network)
- *
+ *   Have we already started saving the response?
+ *      If we have started, pass the data to the storage manager via store_body
+ *      Otherwise:
+ *        Check to see if we *can* save this particular response.
+ *        If we can, call cache_create_entity() and save the headers and body
+ *   Finally, pass the data to the next filter (the network or whatever)
  */
 
-static int cache_in_filter(ap_filter_t *f, apr_bucket_brigade *in)
+static int cache_save_filter(ap_filter_t *f, apr_bucket_brigade *in)
 {
     int rv;
+    int date_in_errhdr = 0;
     request_rec *r = f->r;
     cache_request_rec *cache;
     cache_server_conf *conf;
     char *url = r->unparsed_uri;
-    const char *cc_out, *cl;
+    const char *cc_in, *cc_out, *cl;
     const char *exps, *lastmods, *dates, *etag;
     apr_time_t exp, date, lastmod, now;
     apr_off_t size;
@@ -428,17 +264,20 @@
     apr_pool_t *p;
 
     /* check first whether running this filter has any point or not */
-    if(r->no_cache) {
+    /* If the user has Cache-Control: no-store from RFC 2616, don't store! */
+    cc_in = apr_table_get(r->headers_in, "Cache-Control");
+    if (r->no_cache || ap_cache_liststr(NULL, cc_in, "no-store", NULL)) {
         ap_remove_output_filter(f);
         return ap_pass_brigade(f->next, in);
     }
 
-    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
-                 "cache: running CACHE_IN filter");
-
     /* Setup cache_request_rec */
-    cache = (cache_request_rec *) ap_get_module_config(r->request_config, &cache_module);
+    cache = (cache_request_rec *) ap_get_module_config(r->request_config,
+                                                       &cache_module);
     if (!cache) {
+        /* user likely configured CACHE_SAVE manually; they should really use
+         * mod_cache configuration to do that
+         */
         cache = apr_pcalloc(r->pool, sizeof(cache_request_rec));
         ap_set_module_config(r->request_config, &cache_module, cache);
     }
@@ -451,6 +290,12 @@
      * This section passes the brigades into the cache modules, but only
      * if the setup section (see below) is complete.
      */
+    if (cache->block_response) {
+        /* We've already sent down the response and EOS.  So, ignore
+         * whatever comes now.
+         */
+        return APR_SUCCESS;
+    }
 
     /* have we already run the cachability check and set up the
      * cached file handle? 
@@ -459,7 +304,7 @@
         /* pass the brigades into the cache, then pass them
          * up the filter stack
          */
-        rv = cache_write_entity_body(cache->handle, r, in);
+        rv = cache->provider->store_body(cache->handle, r, in);
         if (rv != APR_SUCCESS) {
             ap_remove_output_filter(f);
         }
@@ -473,12 +318,14 @@
      * parameters, and decides whether this URL should be cached at
      * all. This section is* run before the above section.
      */
-    info = apr_pcalloc(r->pool, sizeof(cache_info));
 
     /* read expiry date; if a bad date, then leave it so the client can
      * read it 
      */
-    exps = apr_table_get(r->headers_out, "Expires");
+    exps = apr_table_get(r->err_headers_out, "Expires");
+    if (exps == NULL) {
+        exps = apr_table_get(r->headers_out, "Expires");
+    }
     if (exps != NULL) {
         if (APR_DATE_BAD == (exp = apr_date_parse_http(exps))) {
             exps = NULL;
@@ -489,7 +336,10 @@
     }
 
     /* read the last-modified date; if the date is bad, then delete it */
-    lastmods = apr_table_get(r->headers_out, "Last-Modified");
+    lastmods = apr_table_get(r->err_headers_out, "Last-Modified");
+    if (lastmods == NULL) {
+        lastmods = apr_table_get(r->headers_out, "Last-Modified");
+    }
     if (lastmods != NULL) {
         if (APR_DATE_BAD == (lastmod = apr_date_parse_http(lastmods))) {
             lastmods = NULL;
@@ -501,8 +351,14 @@
 
     conf = (cache_server_conf *) ap_get_module_config(r->server->module_config, &cache_module);
     /* read the etag and cache-control from the entity */
-    etag = apr_table_get(r->headers_out, "Etag");
-    cc_out = apr_table_get(r->headers_out, "Cache-Control");
+    etag = apr_table_get(r->err_headers_out, "Etag");
+    if (etag == NULL) {
+        etag = apr_table_get(r->headers_out, "Etag");
+    }
+    cc_out = apr_table_get(r->err_headers_out, "Cache-Control");
+    if (cc_out == NULL) {
+        cc_out = apr_table_get(r->headers_out, "Cache-Control");
+    }
 
     /*
      * what responses should we not cache?
@@ -533,21 +389,22 @@
          */
         reason = "Query string present but no expires header";
     }
-    else if (r->status == HTTP_NOT_MODIFIED && (NULL == cache->handle)) {
+    else if (r->status == HTTP_NOT_MODIFIED &&
+             !cache->handle && !cache->stale_handle) {
         /* if the server said 304 Not Modified but we have no cache
          * file - pass this untouched to the user agent, it's not for us.
          */
         reason = "HTTP Status 304 Not Modified";
     }
     else if (r->status == HTTP_OK && lastmods == NULL && etag == NULL 
-             && (conf->no_last_mod_ignore ==0)) {
-        /* 200 OK response from HTTP/1.0 and up without a Last-Modified
-         * header/Etag 
+             && (exps == NULL) && (conf->no_last_mod_ignore ==0)) {
+        /* 200 OK response from HTTP/1.0 and up without Last-Modified,
+         * Etag, or Expires headers.
          */
-        /* XXX mod-include clears last_modified/expires/etags - this
+        /* Note: mod-include clears last_modified/expires/etags - this
          * is why we have an optional function for a key-gen ;-) 
          */
-        reason = "No Last-Modified or Etag header";
+        reason = "No Last-Modified, Etag, or Expires headers";
     }
     else if (r->header_only) {
         /* HEAD requests */
@@ -591,7 +448,7 @@
          * BillS Asks.. Why do we need to make this call to remove_url?
          * leave it in for now..
          */
-        cache_remove_url(r, cache->types, url);
+        cache_remove_url(r, url);
 
         /* remove this filter from the chain */
         ap_remove_output_filter(f);
@@ -599,15 +456,31 @@
         /* ship the data up the stack */
         return ap_pass_brigade(f->next, in);
     }
+
+    /* Make it so that we don't execute this path again. */
     cache->in_checked = 1;
 
     /* Set the content length if known. 
      */
-    cl = apr_table_get(r->headers_out, "Content-Length");
+    cl = apr_table_get(r->err_headers_out, "Content-Length");
+    if (cl == NULL) {
+        cl = apr_table_get(r->headers_out, "Content-Length");
+    }
     if (cl) {
+#if 0
+        char *errp;
+        if (apr_strtoff(&size, cl, &errp, 10) || *errp || size < 0) {
+            cl = NULL; /* parse error, see next 'if' block */
+        }
+#else
         size = apr_atoi64(cl);
+        if (size < 0) {
+            cl = NULL;
+        }
+#endif
     }
-    else {
+
+    if (!cl) {
         /* if we don't get the content-length, see if we have all the 
          * buckets and use their length to calculate the size 
          */
@@ -615,7 +488,10 @@
         int all_buckets_here=0;
         int unresolved_length = 0;
         size=0;
-        APR_BRIGADE_FOREACH(e, in) {
+        for (e = APR_BRIGADE_FIRST(in);
+             e != APR_BRIGADE_SENTINEL(in);
+             e = APR_BUCKET_NEXT(e))
+        {
             if (APR_BUCKET_IS_EOS(e)) {
                 all_buckets_here=1;
                 break;
@@ -640,35 +516,36 @@
      * - cache->handle == NULL. In this case there is no previously
      * cached entity anywhere on the system. We must create a brand
      * new entity and store the response in it.
-     * - cache->handle != NULL. In this case there is a stale
+     * - cache->stale_handle != NULL. In this case there is a stale
      * entity in the system which needs to be replaced by new
      * content (unless the result was 304 Not Modified, which means
      * the cached entity is actually fresh, and we should update
      * the headers).
      */
+
+    /* Did we have a stale cache entry that really is stale? */
+    if (cache->stale_handle) {
+        if (r->status == HTTP_NOT_MODIFIED) {
+            /* Oh, hey.  It isn't that stale!  Yay! */
+            cache->handle = cache->stale_handle;
+            info = &cache->handle->cache_obj->info;
+        }
+        else {
+            /* Oh, well.  Toss it. */
+            cache->provider->remove_entity(cache->stale_handle);
+            /* Treat the request as if it wasn't conditional. */
+            cache->stale_handle = NULL;
+        }
+    }
+
     /* no cache handle, create a new entity */
     if (!cache->handle) {
-        rv = cache_create_entity(r, cache->types, url, size);
+        rv = cache_create_entity(r, url, size);
+        info = apr_pcalloc(r->pool, sizeof(cache_info));
+        /* We only set info->status upon the initial creation. */
+        info->status = r->status;
     }
-    /* pre-existing cache handle and 304, make entity fresh */
-    else if (r->status == HTTP_NOT_MODIFIED) {
-        /* update headers */
-
-        /* remove this filter ??? */
 
-        /* XXX is this right?  we must set rv to something other than OK 
-         * in this path
-         */
-        rv = HTTP_NOT_MODIFIED;
-    }
-    /* pre-existing cache handle and new entity, replace entity
-     * with this one
-     */
-    else {
-        cache_remove_entity(r, cache->types, cache->handle);
-        rv = cache_create_entity(r, cache->types, url, size);
-    }
-    
     if (rv != OK) {
         /* Caching layer declined the opportunity to cache the response */
         ap_remove_output_filter(f);
@@ -689,7 +566,13 @@
      */
 
     /* Read the date. Generate one if one is not supplied */
-    dates = apr_table_get(r->headers_out, "Date");
+    dates = apr_table_get(r->err_headers_out, "Date");
+    if (dates != NULL) {
+        date_in_errhdr = 1;
+    }
+    else {
+        dates = apr_table_get(r->headers_out, "Date");
+    }
     if (dates != NULL) {
         info->date = apr_date_parse_http(dates);
     }
@@ -700,10 +583,13 @@
     now = apr_time_now();
     if (info->date == APR_DATE_BAD) {  /* No, or bad date */
         char *dates;
-        /* no date header! */
+        /* no date header (or bad header)! */
         /* add one; N.B. use the time _now_ rather than when we were checking
          * the cache 
          */
+        if (date_in_errhdr == 1) {
+            apr_table_unset(r->err_headers_out, "Date");
+        }
         date = now;
         dates = apr_pcalloc(r->pool, MAX_STRING_LEN);
         apr_rfc822_date(dates, now);
@@ -723,7 +609,6 @@
     info->request_time = r->request_time;
 
     /* check last-modified date */
-    /* XXX FIXME we're referencing date on a path where we didn't set it */
     if (lastmod != APR_DATE_BAD && lastmod > date) {
         /* if it's in the future, then replace by date */
         lastmod = date;
@@ -737,9 +622,9 @@
 
     /* if no expiry date then
      *   if lastmod
-     *      expiry date = now + min((date - lastmod) * factor, maxexpire)
+     *      expiry date = date + min((date - lastmod) * factor, maxexpire)
      *   else
-     *      expire date = now + defaultexpire
+     *      expire date = date + defaultexpire
      */
     if (exp == APR_DATE_BAD) {
         /* if lastmod == date then you get 0*conf->factor which results in
@@ -748,26 +633,54 @@
          */
         if ((lastmod != APR_DATE_BAD) && (lastmod < date)) {
             apr_time_t x = (apr_time_t) ((date - lastmod) * conf->factor);
+
             if (x > conf->maxex) {
                 x = conf->maxex;
             }
-            exp = now + x;
+            exp = date + x;
         }
         else {
-            exp = now + conf->defex;
+            exp = date + conf->defex;
         }
     }
     info->expire = exp;
 
     info->content_type = apr_pstrdup(r->pool, r->content_type);
-    info->filename = apr_pstrdup(r->pool, r->filename );
+    info->etag = apr_pstrdup(r->pool, etag);
+    info->lastmods = apr_pstrdup(r->pool, lastmods);
+    info->filename = apr_pstrdup(r->pool, r->filename);
 
     /*
      * Write away header information to cache.
      */
-    rv = cache_write_entity_headers(cache->handle, r, info);
+    rv = cache->provider->store_headers(cache->handle, r, info);
+
+    /* Did we actually find an entity before, but it wasn't really stale? */
+    if (rv == APR_SUCCESS && cache->stale_handle) {
+        apr_bucket_brigade *bb;
+        apr_bucket *bkt;
+
+        bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
+
+        /* Were we initially a conditional request? */
+        if (ap_cache_request_is_conditional(cache->stale_headers)) {
+            /* FIXME: Should we now go and make sure it's really not
+             * modified since what the user thought?
+             */
+            bkt = apr_bucket_eos_create(bb->bucket_alloc);
+            APR_BRIGADE_INSERT_TAIL(bb, bkt);
+        }
+        else {
+            r->status = info->status;
+            cache->provider->recall_body(cache->handle, r->pool, bb);
+        }
+
+        cache->block_response = 1;
+        return ap_pass_brigade(f->next, bb);
+    }
+
     if (rv == APR_SUCCESS) {
-        rv = cache_write_entity_body(cache->handle, r, in);
+        rv = cache->provider->store_body(cache->handle, r, in);
     }
     if (rv != APR_SUCCESS) {
         ap_remove_output_filter(f);
@@ -881,6 +794,7 @@
     new = apr_array_push(conf->cacheenable);
     new->type = type;
     new->url = url;
+    new->urllen = strlen(url);
     return NULL;
 }
 
@@ -888,13 +802,14 @@
                                      const char *url)
 {
     cache_server_conf *conf;
-    struct cache_enable *new;
+    struct cache_disable *new;
 
     conf =
         (cache_server_conf *)ap_get_module_config(parms->server->module_config,
                                                   &cache_module);
     new = apr_array_push(conf->cachedisable);
     new->url = url;
+    new->urllen = strlen(url);
     return NULL;
 }
 
@@ -1018,9 +933,9 @@
      * Make them AP_FTYPE_CONTENT for now.
      * XXX ianhH:they should run AFTER all the other content filters.
      */
-    cache_in_filter_handle = 
-        ap_register_output_filter("CACHE_IN", 
-                                  cache_in_filter, 
+    cache_save_filter_handle = 
+        ap_register_output_filter("CACHE_SAVE", 
+                                  cache_save_filter, 
                                   NULL,
                                   AP_FTYPE_CONTENT_SET-1);
     /* CACHE_OUT must go into the filter chain before SUBREQ_CORE to
@@ -1032,11 +947,6 @@
                                   cache_out_filter, 
                                   NULL,
                                   AP_FTYPE_CONTENT_SET-1);
-    cache_conditional_filter_handle =
-        ap_register_output_filter("CACHE_CONDITIONAL", 
-                                  cache_conditional_filter, 
-                                  NULL,
-                                  AP_FTYPE_CONTENT_SET);
     ap_hook_post_config(cache_post_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
 }
 
Index: modules/experimental/mod_cache.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/experimental/mod_cache.h,v
retrieving revision 1.1.1.1
retrieving revision 1.5
diff -u -u -r1.1.1.1 -r1.5
--- modules/experimental/mod_cache.h	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/experimental/mod_cache.h	13 Jan 2005 15:04:55 -0000	1.5
@@ -1,59 +1,16 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/* Copyright 2000-2004 The Apache Software Foundation
  *
- * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
- * reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Apache" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- * Portions of this software are based upon public domain software
- * originally written at the National Center for Supercomputing Applications,
- * University of Illinois, Urbana-Champaign.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 #ifndef MOD_CACHE_H
@@ -107,11 +64,7 @@
 #include <arpa/inet.h>
 #endif
 
-/* USE_ATOMICS should be replaced with the appropriate APR feature macro */
-#define USE_ATOMICS
-#ifdef USE_ATOMICS
 #include "apr_atomic.h"
-#endif
 
 #ifndef MAX
 #define MAX(a,b)                ((a) > (b) ? (a) : (b))
@@ -122,7 +75,6 @@
 
 /* default completion is 60% */
 #define DEFAULT_CACHE_COMPLETION (60)
-#define MAX_URL_LENGTH 1024
 #define MSEC_ONE_DAY    ((apr_time_t)(86400*APR_USEC_PER_SEC)) /* one day, in microseconds */
 #define MSEC_ONE_HR     ((apr_time_t)(3600*APR_USEC_PER_SEC))  /* one hour, in microseconds */
 #define MSEC_ONE_MIN    ((apr_time_t)(60*APR_USEC_PER_SEC))    /* one minute, in microseconds */
@@ -155,10 +107,12 @@
 struct cache_enable {
     const char *url;
     const char *type;
+    apr_size_t urllen;
 };
 
 struct cache_disable {
     const char *url;
+    apr_size_t urllen;
 };
 
 /* static information about the local cache */
@@ -184,6 +138,7 @@
 /* cache info information */
 typedef struct cache_info cache_info;
 struct cache_info {
+    int status;
     char *content_type;
     char *etag;
     char *lastmods;         /* last modified of cache entity */
@@ -199,7 +154,6 @@
     apr_time_t ius;    /*  If-UnModified_Since header value    */
     const char *im;         /* If-Match header value */
     const char *inm;         /* If-None-Match header value */
-
 };
 
 /* cache handle information */
@@ -218,32 +172,56 @@
     void *vobj;         /* Opaque portion (specific to the cache implementation) of the cache object */
     apr_size_t count;   /* Number of body bytes written to the cache so far */
     int complete;
-#ifdef USE_ATOMICS
     apr_atomic_t refcount;
-#else
-    apr_size_t refcount;
-#endif
     apr_size_t cleanup;
 };
 
 typedef struct cache_handle cache_handle_t;
+
+#define CACHE_PROVIDER_GROUP "cache"
+
+typedef struct {
+    int (*remove_entity) (cache_handle_t *h);
+    apr_status_t (*store_headers)(cache_handle_t *h, request_rec *r, cache_info *i);
+    apr_status_t (*store_body)(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b);
+    apr_status_t (*recall_headers) (cache_handle_t *h, request_rec *r);
+    apr_status_t (*recall_body) (cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb); 
+    int (*create_entity) (cache_handle_t *h, request_rec *r,
+                           const char *urlkey, apr_off_t len);
+    int (*open_entity) (cache_handle_t *h, request_rec *r,
+                           const char *urlkey);
+    int (*remove_url) (const char *urlkey);
+} cache_provider;
+
+/* A linked-list of authn providers. */
+typedef struct cache_provider_list cache_provider_list;
+
+struct cache_provider_list {
+    const char *provider_name;
+    const cache_provider *provider;
+    cache_provider_list *next;
+};
+
 struct cache_handle {
     cache_object_t *cache_obj;
-    int (*remove_entity) (cache_handle_t *h);
-    apr_status_t (*write_headers)(cache_handle_t *h, request_rec *r, cache_info *i);
-    apr_status_t (*write_body)(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b);
-    apr_status_t (*read_headers) (cache_handle_t *h, request_rec *r);
-    apr_status_t (*read_body) (cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb); 
-    apr_table_t *req_hdrs;   /* These are the original request headers */
+    apr_table_t *req_hdrs;        /* cached request headers */
+    apr_table_t *resp_hdrs;       /* cached response headers */
+    apr_table_t *resp_err_hdrs;   /* cached response err headers */
+    const char *content_type;     /* cached content type */
+    int status;                   /* cached status */
 };
 
 /* per request cache information */
 typedef struct {
-    const char *types;			/* the types of caches allowed */
-    const char *type;			/* the type of cache selected */
+    cache_provider_list *providers;         /* possible cache providers */
+    const cache_provider *provider;         /* current cache provider */
+    const char *provider_name;              /* current cache provider name */
     int fresh;				/* is the entitey fresh? */
     cache_handle_t *handle;		/* current cache handle */
-    int in_checked;			/* CACHE_IN must cache the entity */
+    cache_handle_t *stale_handle;	/* stale cache handle */
+    apr_table_t *stale_headers;		/* original request headers. */
+    int in_checked;			/* CACHE_SAVE must cache the entity */
+    int block_response;			/* CACHE_SAVE must block response. */
     apr_bucket_brigade *saved_brigade;  /* copy of partial response */
     apr_off_t saved_size;               /* length of saved_brigade */
     apr_time_t exp;                     /* expiration */
@@ -259,19 +237,18 @@
 
 /**
  * Check the freshness of the cache object per RFC2616 section 13.2 (Expiration Model)
- * @param cache cache_request_rec
+ * @param h cache_handle_t
  * @param r request_rec
  * @return 0 ==> cache object is stale, 1 ==> cache object is fresh
  */
-CACHE_DECLARE(int) ap_cache_check_freshness(cache_request_rec *cache, request_rec *r);
+CACHE_DECLARE(int) ap_cache_check_freshness(cache_handle_t *h, request_rec *r);
 CACHE_DECLARE(apr_time_t) ap_cache_hex2usec(const char *x);
 CACHE_DECLARE(void) ap_cache_usec2hex(apr_time_t j, char *y);
 CACHE_DECLARE(char *) generate_name(apr_pool_t *p, int dirlevels, 
                                     int dirlength, 
                                     const char *name);
-CACHE_DECLARE(int) ap_cache_request_is_conditional(request_rec *r);
-CACHE_DECLARE(void) ap_cache_reset_output_filters(request_rec *r);
-CACHE_DECLARE(const char *)ap_cache_get_cachetype(request_rec *r, cache_server_conf *conf, const char *url);
+CACHE_DECLARE(int) ap_cache_request_is_conditional(apr_table_t *table);
+CACHE_DECLARE(cache_provider_list *)ap_cache_get_providers(request_rec *r, cache_server_conf *conf, const char *url);
 CACHE_DECLARE(int) ap_cache_liststr(apr_pool_t *p, const char *list,
                                     const char *key, char **val);
 CACHE_DECLARE(const char *)ap_cache_tokstr(apr_pool_t *p, const char *list, const char **str);
@@ -279,15 +256,14 @@
 /* Create a new table consisting of those elements from a request_rec's
  * headers_out that are allowed to be stored in a cache
  */
-CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_hdrs_out(request_rec *r);
+CACHE_DECLARE(apr_table_t *)ap_cache_cacheable_hdrs_out(apr_pool_t *pool, apr_table_t *t);
 
 /**
  * cache_storage.c
  */
-int cache_remove_url(request_rec *r, const char *types, char *url);
-int cache_create_entity(request_rec *r, const char *types, char *url, apr_off_t size);
-int cache_remove_entity(request_rec *r, const char *types, cache_handle_t *h);
-int cache_select_url(request_rec *r, const char *types, char *url);
+int cache_remove_url(request_rec *r, char *url);
+int cache_create_entity(request_rec *r, char *url, apr_off_t size);
+int cache_select_url(request_rec *r, char *url);
 apr_status_t cache_generate_key_default( request_rec *r, apr_pool_t*p, char**key );
 /**
  * create a key for the cache based on the request record
@@ -295,12 +271,13 @@
  */
 const char* cache_create_key( request_rec*r );
 
-apr_status_t cache_write_entity_headers(cache_handle_t *h, request_rec *r, cache_info *info);
-apr_status_t cache_write_entity_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *bb);
-
-apr_status_t cache_read_entity_headers(cache_handle_t *h, request_rec *r);
-apr_status_t cache_read_entity_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb);
+/*
+apr_status_t cache_store_entity_headers(cache_handle_t *h, request_rec *r, cache_info *info);
+apr_status_t cache_store_entity_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *bb);
 
+apr_status_t cache_recall_entity_headers(cache_handle_t *h, request_rec *r);
+apr_status_t cache_recall_entity_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb);
+*/
 
 /* hooks */
 
@@ -324,17 +301,6 @@
 #define CACHE_DECLARE_NONSTD(type)     __declspec(dllimport) type
 #define CACHE_DECLARE_DATA             __declspec(dllimport)
 #endif
-
-APR_DECLARE_EXTERNAL_HOOK(cache, CACHE, int, create_entity, 
-                          (cache_handle_t *h, request_rec *r, const char *type,
-                           const char *urlkey, apr_off_t len))
-APR_DECLARE_EXTERNAL_HOOK(cache, CACHE, int, open_entity,  
-                          (cache_handle_t *h, request_rec *r, const char *type,
-                           const char *urlkey))
-APR_DECLARE_EXTERNAL_HOOK(cache, CACHE, int, remove_url, 
-                          (const char *type, const char *urlkey))
-
-
 
 APR_DECLARE_OPTIONAL_FN(apr_status_t, 
                         ap_cache_generate_key, 
Index: modules/experimental/mod_disk_cache.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/experimental/mod_disk_cache.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- modules/experimental/mod_disk_cache.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/experimental/mod_disk_cache.c	13 Jan 2005 15:27:54 -0000	1.4
@@ -1,64 +1,22 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/* Copyright 2000-2004 The Apache Software Foundation
  *
- * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
- * reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Apache" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- * Portions of this software are based upon public domain software
- * originally written at the National Center for Supercomputing Applications,
- * University of Illinois, Urbana-Champaign.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
-#include "mod_cache.h"
 #include "apr_file_io.h"
 #include "apr_strings.h"
+#include "mod_cache.h"
+#include "ap_provider.h"
 #include "util_filter.h"
 #include "util_script.h"
 
@@ -66,6 +24,32 @@
 #include <unistd.h> /* needed for unlink/link */
 #endif
 
+/* Our on-disk header format is:
+ *
+ * disk_cache_info_t
+ * entity name (dobj->name) [length is in disk_cache_info_t->name_len]
+ * r->headers_out (delimited by CRLF)
+ * CRLF
+ * r->headers_in (delimited by CRLF)
+ * CRLF
+ */
+#define DISK_FORMAT_VERSION 0
+typedef struct {
+    /* Indicates the format of the header struct stored on-disk. */
+    int format;
+    /* The HTTP status code returned for this response.  */
+    int status;
+    /* The size of the entity name that follows. */
+    apr_size_t name_len;
+    /* The number of times we've cached this entity. */
+    apr_size_t entity_version;
+    /* Miscellaneous time values. */
+    apr_time_t date;
+    apr_time_t expire;
+    apr_time_t request_time;
+    apr_time_t response_time;
+} disk_cache_info_t;
+
 /*
  * disk_cache_object_t
  * Pointed to by cache_object_t::vobj
@@ -75,17 +59,20 @@
     char *tempfile;          /* temp file tohold the content */
 #if 0
     int dirlevels;              /* Number of levels of subdirectories */
-    int dirlength;            /* Length of subdirectory names */   
+    int dirlength;            /* Length of subdirectory names */
 #endif
     char *datafile;          /* name of file where the data will go */
     char *hdrsfile;          /* name of file where the hdrs will go */
+    char *hashfile;          /* Computed hash key for this URI */
     char *name;
-    apr_time_t version;      /* update count of the file */
     apr_file_t *fd;          /* data file */
     apr_file_t *hfd;         /* headers file */
-    apr_off_t file_size;     /*  File size of the cached data file  */    
+    apr_file_t *tfd;         /* temporary file for data */
+    apr_off_t file_size;     /*  File size of the cached data file  */
+    disk_cache_info_t disk_info; /* Header information. */
 } disk_cache_object_t;
 
+
 /*
  * mod_disk_cache configuration
  */
@@ -96,7 +83,7 @@
 #define DEFAULT_MIN_FILE_SIZE 1
 #define DEFAULT_MAX_FILE_SIZE 1000000
 #define DEFAULT_CACHE_SIZE 1000000
- 
+
 typedef struct {
     const char* cache_root;
     apr_size_t cache_root_len;
@@ -107,7 +94,7 @@
     apr_time_t gcinterval;       /* garbage collection interval, in msec */
     int dirlevels;               /* Number of levels of subdirectories */
     int dirlength;               /* Length of subdirectory names */
-    int	expirychk;               /* true if expiry time is observed for cached files */
+    int        expirychk;               /* true if expiry time is observed for cached files */
     apr_size_t minfs;            /* minumum file size for cached files */
     apr_size_t maxfs;            /* maximum file size for cached files */
     apr_time_t mintm;            /* minimum time margin for caching files */
@@ -121,30 +108,36 @@
 
 /* Forward declarations */
 static int remove_entity(cache_handle_t *h);
-static apr_status_t write_headers(cache_handle_t *h, request_rec *r, cache_info *i);
-static apr_status_t write_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b);
-static apr_status_t read_headers(cache_handle_t *h, request_rec *r);
-static apr_status_t read_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb);
+static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *i);
+static apr_status_t store_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b);
+static apr_status_t recall_headers(cache_handle_t *h, request_rec *r);
+static apr_status_t recall_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb);
 
 /*
  * Local static functions
  */
 #define CACHE_HEADER_SUFFIX ".header"
 #define CACHE_DATA_SUFFIX   ".data"
-static char *header_file(apr_pool_t *p, int dirlevels, int dirlength, 
-                         const char *root, const char *name)
+static char *header_file(apr_pool_t *p, disk_cache_conf *conf,
+                         disk_cache_object_t *dobj, const char *name)
 {
-    char *hashfile;
-    hashfile = generate_name(p, dirlevels, dirlength, name);
-    return apr_pstrcat(p, root, "/", hashfile, CACHE_HEADER_SUFFIX, NULL);
+    if (!dobj->hashfile) {
+        dobj->hashfile = generate_name(p, conf->dirlevels, conf->dirlength,
+                                       name);
+    }
+    return apr_pstrcat(p, conf->cache_root, "/", dobj->hashfile,
+                       CACHE_HEADER_SUFFIX, NULL);
 }
 
-static char *data_file(apr_pool_t *p, int dirlevels, int dirlength, 
-                       const char *root, const char *name)
+static char *data_file(apr_pool_t *p, disk_cache_conf *conf,
+                       disk_cache_object_t *dobj, const char *name)
 {
-    char *hashfile;
-    hashfile = generate_name(p, dirlevels, dirlength, name);
-    return apr_pstrcat(p, root, "/", hashfile, CACHE_DATA_SUFFIX, NULL);
+    if (!dobj->hashfile) {
+        dobj->hashfile = generate_name(p, conf->dirlevels, conf->dirlength,
+                                       name);
+    }
+    return apr_pstrcat(p, conf->cache_root, "/", dobj->hashfile,
+                       CACHE_DATA_SUFFIX, NULL);
 }
 
 static void mkdir_structure(disk_cache_conf *conf, char *file, apr_pool_t *pool)
@@ -158,7 +151,7 @@
             break;
         *p = '\0';
 
-        rv = apr_dir_make(file, 
+        rv = apr_dir_make(file,
                           APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);
         if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
             /* XXX */
@@ -168,31 +161,16 @@
     }
 }
 
-static apr_status_t file_cache_el_final(cache_handle_t *h, request_rec *r)
+static apr_status_t file_cache_el_final(disk_cache_object_t *dobj,
+                                        request_rec *r)
 {
-    apr_status_t rv;
-    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
-                                                 &disk_cache_module);
-    disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
-
     /* move the data over */
-    if (dobj->fd) {
-        apr_file_flush(dobj->fd);
-        if (!dobj->datafile) {
-            dobj->datafile = data_file(r->pool, conf->dirlevels, conf->dirlength,
-                                       conf->cache_root, h->cache_obj->key);
-        }
-        /* Remove old file with the same name. If remove fails, then
-         * perhaps we need to create the directory tree where we are
-         * about to write the new file.
-         */
-        rv = apr_file_remove(dobj->datafile, r->pool);
-        if (rv != APR_SUCCESS) {
-            mkdir_structure(conf, dobj->datafile, r->pool);
-        }
+    if (dobj->tfd) {
+        apr_status_t rv;
+
+        apr_file_close(dobj->tfd);
 
-        /*
-         * This assumes that the tempfile is on the same file system
+        /* This assumes that the tempfile is on the same file system
          * as the cache_root. If not, then we need a file copy/move
          * rather than a rename.
          */
@@ -201,116 +179,80 @@
             /* XXX log */
         }
 
-        apr_file_close(dobj->fd);
-        dobj->fd = NULL;
-       /* XXX log */
-   }
+        dobj->tfd = NULL;
+    }
+
+    return APR_SUCCESS;
+}
+
+static apr_status_t file_cache_errorcleanup(disk_cache_object_t *dobj, request_rec *r)
+{
+    /* Remove the header file and the body file. */
+    apr_file_remove(dobj->hdrsfile, r->pool);
+    apr_file_remove(dobj->datafile, r->pool);
+
+    /* If we opened the temporary data file, close and remove it. */
+    if (dobj->tfd) {
+        apr_file_close(dobj->tfd);
+        apr_file_remove(dobj->tempfile, r->pool);
+        dobj->tfd = NULL;
+    }
 
-   return APR_SUCCESS;
+    return APR_SUCCESS;
 }
 
 
-/* These two functions get and put state information into the data 
- * file for an ap_cache_el, this state information will be read 
- * and written transparent to clients of this module 
+/* These two functions get and put state information into the data
+ * file for an ap_cache_el, this state information will be read
+ * and written transparent to clients of this module
  */
-static int file_cache_read_mydata(apr_file_t *fd, cache_info *info, 
-                                  disk_cache_object_t *dobj)
+static int file_cache_recall_mydata(apr_file_t *fd, cache_info *info,
+                                    disk_cache_object_t *dobj, request_rec *r)
 {
     apr_status_t rv;
-    char urlbuff[1034]; /* XXX FIXME... THIS IS A POTENTIAL SECURITY HOLE */
-    int urllen = sizeof(urlbuff);
-    int offset=0;
-    char * temp;
+    char *urlbuff;
+    disk_cache_info_t disk_info;
+    apr_size_t len;
 
     /* read the data from the cache file */
-    /* format
-     * date SP expire SP count CRLF
-     * dates are stored as a hex representation of apr_time_t (number of
-     * microseconds since 00:00:00 january 1, 1970 UTC)
-     */
-    rv = apr_file_gets(&urlbuff[0], urllen, fd);
+    len = sizeof(disk_cache_info_t);
+    rv = apr_file_read_full(fd, &disk_info, len, &len);
     if (rv != APR_SUCCESS) {
         return rv;
     }
 
-    if ((temp = strchr(&urlbuff[0], '\n')) != NULL) /* trim off new line character */
-        *temp = '\0';      /* overlay it with the null terminator */
-
-    if (!apr_date_checkmask(urlbuff, "&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&")) {
+    if (disk_info.format != DISK_FORMAT_VERSION) {
+        ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
+                     "cache_disk: URL %s had a on-disk version mismatch",
+                     r->uri);
         return APR_EGENERAL;
     }
 
-    info->date = ap_cache_hex2usec(urlbuff + offset);
-    offset += (sizeof(info->date)*2) + 1;
-    info->expire = ap_cache_hex2usec(urlbuff + offset);
-    offset += (sizeof(info->expire)*2) + 1;
-    dobj->version = ap_cache_hex2usec(urlbuff + offset);
-    offset += (sizeof(info->expire)*2) + 1;
-    info->request_time = ap_cache_hex2usec(urlbuff + offset);
-    offset += (sizeof(info->expire)*2) + 1;
-    info->response_time = ap_cache_hex2usec(urlbuff + offset);
-    
-    /* check that we have the same URL */
-    rv = apr_file_gets(&urlbuff[0], urllen, fd);
+    /* Store it away so we can get it later. */
+    dobj->disk_info = disk_info;
+
+    info->date = disk_info.date;
+    info->expire = disk_info.expire;
+    info->request_time = disk_info.request_time;
+    info->response_time = disk_info.response_time;
+
+    /* Note that we could optimize this by conditionally doing the palloc
+     * depending upon the size. */
+    urlbuff = apr_palloc(r->pool, disk_info.name_len + 1);
+    len = disk_info.name_len;
+    rv = apr_file_read_full(fd, urlbuff, len, &len);
     if (rv != APR_SUCCESS) {
         return rv;
     }
+    urlbuff[disk_info.name_len] = '\0';
 
-    if ((temp = strchr(&urlbuff[0], '\n')) != NULL) { /* trim off new line character */
-        *temp = '\0';      /* overlay it with the null terminator */
-    }
-
-    if (strncmp(urlbuff, "X-NAME: ", 7) != 0) {
-        return APR_EGENERAL;
-    }
-    if (strcmp(urlbuff + 8, dobj->name) != 0) {
+    /* check that we have the same URL */
+    /* Would strncmp be correct? */
+    if (strcmp(urlbuff, dobj->name) != 0) {
         return APR_EGENERAL;
     }
-    
-    return APR_SUCCESS;
-}
 
-static int file_cache_write_mydata(apr_file_t *fd , cache_handle_t *h, request_rec *r)
-{
-    apr_status_t rc;
-    char *buf;
-    apr_size_t amt;
-
-    char	dateHexS[sizeof(apr_time_t) * 2 + 1];
-    char	expireHexS[sizeof(apr_time_t) * 2 + 1];
-    char	verHexS[sizeof(apr_time_t) * 2 + 1];
-    char	requestHexS[sizeof(apr_time_t) * 2 + 1];
-    char	responseHexS[sizeof(apr_time_t) * 2 + 1];
-    cache_info *info = &(h->cache_obj->info);
-    disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
-    
-    if (!r->headers_out) {
-        /* XXX log message */
-        return 0;
-    }
-
-    ap_cache_usec2hex(info->date, dateHexS);
-    ap_cache_usec2hex(info->expire, expireHexS);
-    ap_cache_usec2hex(dobj->version++, verHexS);
-    ap_cache_usec2hex(info->request_time, requestHexS);
-    ap_cache_usec2hex(info->response_time, responseHexS);
-    buf = apr_pstrcat(r->pool, dateHexS, " ", expireHexS, " ", verHexS, " ", requestHexS, " ", responseHexS, "\n", NULL);
-    amt = strlen(buf);
-    rc = apr_file_write(fd, buf, &amt);
-    if (rc != APR_SUCCESS) {
-        /* XXX log message */
-        return 0;
-    }
-
-    buf = apr_pstrcat(r->pool, "X-NAME: ", dobj->name, "\n", NULL);
-    amt = strlen(buf);
-    rc = apr_file_write(fd, buf, &amt);
-    if (rc != APR_SUCCESS) {
-        /* XXX log message */
-        return 0;
-    }
-    return 1;
+    return APR_SUCCESS;
 }
 
 /*
@@ -318,35 +260,31 @@
  */
 #define AP_TEMPFILE "/aptmpXXXXXX"
 static int create_entity(cache_handle_t *h, request_rec *r,
-                         const char *type, 
-                         const char *key, 
+                         const char *key,
                          apr_off_t len)
-{ 
-    disk_cache_conf *conf = ap_get_module_config(r->server->module_config, 
+{
+    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
                                                  &disk_cache_module);
     apr_status_t rv;
     cache_object_t *obj;
     disk_cache_object_t *dobj;
     apr_file_t *tmpfile;
 
-    if (strcasecmp(type, "disk")) {
-        return DECLINED;
-    }
-
     if (conf->cache_root == NULL) {
         return DECLINED;
     }
 
-    if (len < conf->minfs || len > conf->maxfs) {
+    /* If the Content-Length is still unknown, cache anyway */
+    if (len != -1 && (len < conf->minfs || len > conf->maxfs)) {
         ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
                      "cache_disk: URL %s failed the size check, "
-                     "or is incomplete", 
+                     "or is incomplete",
                      key);
         return DECLINED;
     }
 
     /* Allocate and initialize cache_object_t and disk_cache_object_t */
-    obj = apr_pcalloc(r->pool, sizeof(*obj));
+    h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(*obj));
     obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(*dobj));
 
     obj->key = apr_pstrdup(r->pool, key);
@@ -355,56 +293,28 @@
     obj->complete = 0;   /* Cache object is not complete */
 
     dobj->name = obj->key;
-
-    /* open temporary file */
+    dobj->datafile = data_file(r->pool, conf, dobj, key);
+    dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
     dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
-    rv = apr_file_mktemp(&tmpfile, dobj->tempfile,  
-                         APR_CREATE | APR_READ | APR_WRITE | APR_EXCL, r->pool);
-
-    if (rv == APR_SUCCESS) {
-        /* Populate the cache handle */
-        h->cache_obj = obj;
-        h->read_body = &read_body;
-        h->read_headers = &read_headers;
-        h->write_body = &write_body;
-        h->write_headers = &write_headers;
-        h->remove_entity = &remove_entity;
-
-        ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
-                     "disk_cache: Caching URL %s",  key);
-    }
-    else {
-        ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
-                     "disk_cache: Could not cache URL %s [%d]", key, rv);
-
-        return DECLINED;
-    }
 
     return OK;
 }
 
-static int open_entity(cache_handle_t *h, request_rec *r, const char *type, const char *key)
+static int open_entity(cache_handle_t *h, request_rec *r, const char *key)
 {
     apr_status_t rc;
     static int error_logged = 0;
-    disk_cache_conf *conf = ap_get_module_config(r->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
                                                  &disk_cache_module);
-    char *data;
-    char *headers;
-    apr_file_t *fd;
-    apr_file_t *hfd;
     apr_finfo_t finfo;
     cache_object_t *obj;
     cache_info *info;
     disk_cache_object_t *dobj;
+    int flags;
 
     h->cache_obj = NULL;
 
     /* Look up entity keyed to 'url' */
-    if (strcasecmp(type, "disk")) {
-        return DECLINED;
-    }
-
     if (conf->cache_root == NULL) {
         if (!error_logged) {
             error_logged = 1;
@@ -414,137 +324,186 @@
         return DECLINED;
     }
 
-    data = data_file(r->pool, conf->dirlevels, conf->dirlength, 
-                     conf->cache_root, key);
-    headers = header_file(r->pool, conf->dirlevels, conf->dirlength, 
-                          conf->cache_root, key);
+    /* Create and init the cache object */
+    h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(cache_object_t));
+    obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(disk_cache_object_t));
+
+    info = &(obj->info);
+    obj->key = (char *) key;
+    dobj->name = (char *) key;
+    dobj->datafile = data_file(r->pool, conf, dobj, key);
+    dobj->hdrsfile = header_file(r->pool, conf, dobj, key);
+    dobj->tempfile = apr_pstrcat(r->pool, conf->cache_root, AP_TEMPFILE, NULL);
 
     /* Open the data file */
-    rc = apr_file_open(&fd, data, APR_READ|APR_BINARY, 0, r->pool);
+    flags = APR_READ|APR_BINARY;
+#ifdef APR_SENDFILE_ENABLED
+    flags |= APR_SENDFILE_ENABLED;
+#endif
+    rc = apr_file_open(&dobj->fd, dobj->datafile, flags, 0, r->pool);
     if (rc != APR_SUCCESS) {
         /* XXX: Log message */
         return DECLINED;
     }
 
     /* Open the headers file */
-    rc = apr_file_open(&hfd, headers, APR_READ|APR_BINARY, 0, r->pool);
+    flags = APR_READ|APR_BINARY|APR_BUFFERED;
+    rc = apr_file_open(&dobj->hfd, dobj->hdrsfile, flags, 0, r->pool);
     if (rc != APR_SUCCESS) {
         /* XXX: Log message */
         return DECLINED;
     }
 
-    /* Create and init the cache object */
-    h->cache_obj = obj = apr_pcalloc(r->pool, sizeof(cache_object_t));
-    obj->vobj = dobj = apr_pcalloc(r->pool, sizeof(disk_cache_object_t));
-
-    info = &(obj->info);
-    obj->key = (char *) key;
-    dobj->name = (char *) key;
-    dobj->fd = fd;
-    dobj->hfd = hfd;
-    dobj->datafile = data;
-    dobj->hdrsfile = headers;
-
-    rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, fd);
+    rc = apr_file_info_get(&finfo, APR_FINFO_SIZE, dobj->fd);
     if (rc == APR_SUCCESS) {
         dobj->file_size = finfo.size;
     }
-    
+
     /* Read the bytes to setup the cache_info fields */
-    rc = file_cache_read_mydata(hfd, info, dobj);
+    rc = file_cache_recall_mydata(dobj->hfd, info, dobj, r);
     if (rc != APR_SUCCESS) {
         /* XXX log message */
         return DECLINED;
     }
 
     /* Initialize the cache_handle callback functions */
-    h->read_body = &read_body;
-    h->read_headers = &read_headers;
-    h->write_body = &write_body;
-    h->write_headers = &write_headers;
-    h->remove_entity = &remove_entity;
-
-    ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
-                 "disk_cache: Serving Cached URL %s",  dobj->name);
+    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
+                 "disk_cache: Recalled cached URL info header %s",  dobj->name);
     return OK;
 }
 
-static int remove_entity(cache_handle_t *h) 
+static int remove_entity(cache_handle_t *h)
 {
     /* Null out the cache object pointer so next time we start from scratch  */
     h->cache_obj = NULL;
     return OK;
 }
 
+static int remove_url(const char *key)
+{
+    /* XXX: Delete file from cache! */
+    return OK;
+}
+
+static apr_status_t read_table(cache_handle_t *handle, request_rec *r,
+                               apr_table_t *table, apr_file_t *file)
+{
+    char w[MAX_STRING_LEN];
+    char *l;
+    int p;
+    apr_status_t rv;
+
+    while (1) {
+
+        /* ### What about APR_EOF? */
+        rv = apr_file_gets(w, MAX_STRING_LEN - 1, file);
+        if (rv != APR_SUCCESS) {
+            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                          "Premature end of cache headers.");
+            return rv;
+        }
+
+        /* Delete terminal (CR?)LF */
+
+        p = strlen(w);
+        /* Indeed, the host's '\n':
+           '\012' for UNIX; '\015' for MacOS; '\025' for OS/390
+           -- whatever the script generates.
+        */
+        if (p > 0 && w[p - 1] == '\n') {
+            if (p > 1 && w[p - 2] == CR) {
+                w[p - 2] = '\0';
+            }
+            else {
+                w[p - 1] = '\0';
+            }
+        }
+
+        /* If we've finished reading the headers, break out of the loop. */
+        if (w[0] == '\0') {
+            break;
+        }
+
+#if APR_CHARSET_EBCDIC
+        /* Chances are that we received an ASCII header text instead of
+         * the expected EBCDIC header lines. Try to auto-detect:
+         */
+        if (!(l = strchr(w, ':'))) {
+            int maybeASCII = 0, maybeEBCDIC = 0;
+            unsigned char *cp, native;
+            apr_size_t inbytes_left, outbytes_left;
+
+            for (cp = w; *cp != '\0'; ++cp) {
+                native = apr_xlate_conv_byte(ap_hdrs_from_ascii, *cp);
+                if (apr_isprint(*cp) && !apr_isprint(native))
+                    ++maybeEBCDIC;
+                if (!apr_isprint(*cp) && apr_isprint(native))
+                    ++maybeASCII;
+            }
+            if (maybeASCII > maybeEBCDIC) {
+                ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
+                             "CGI Interface Error: Script headers apparently ASCII: (CGI = %s)",
+                             r->filename);
+                inbytes_left = outbytes_left = cp - w;
+                apr_xlate_conv_buffer(ap_hdrs_from_ascii,
+                                      w, &inbytes_left, w, &outbytes_left);
+            }
+        }
+#endif /*APR_CHARSET_EBCDIC*/
+
+        /* if we see a bogus header don't ignore it. Shout and scream */
+        if (!(l = strchr(w, ':'))) {
+            return APR_EGENERAL;
+        }
+
+        *l++ = '\0';
+        while (*l && apr_isspace(*l)) {
+            ++l;
+        }
+
+        apr_table_add(table, w, l);
+    }
+
+    return APR_SUCCESS;
+}
+
 /*
  * Reads headers from a buffer and returns an array of headers.
  * Returns NULL on file error
  * This routine tries to deal with too long lines and continuation lines.
- * @@@: XXX: FIXME: currently the headers are passed thru un-merged. 
+ * @@@: XXX: FIXME: currently the headers are passed thru un-merged.
  * Is that okay, or should they be collapsed where possible?
  */
-static apr_status_t read_headers(cache_handle_t *h, request_rec *r) 
+static apr_status_t recall_headers(cache_handle_t *h, request_rec *r)
 {
-    apr_status_t rv;
-    char urlbuff[1034];
-    int urllen = sizeof(urlbuff);
     disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
     apr_table_t * tmp;
 
     /* This case should not happen... */
-    if (!dobj->fd || !dobj->hfd) {
+    if (!dobj->hfd) {
         /* XXX log message */
-        return APR_NOTFOUND; 
-    }
-
-    if(!r->headers_out) {
-        r->headers_out = apr_table_make(r->pool, 20);
+        return APR_NOTFOUND;
     }
-    
-    /*
-     * Call routine to read the header lines/status line 
-     */
-    ap_scan_script_header_err(r, dobj->hfd, NULL);
- 
-    apr_table_setn(r->headers_out, "Content-Type", 
-                   ap_make_content_type(r, r->content_type));
 
-    rv = apr_file_gets(&urlbuff[0], urllen, dobj->hfd);           /* Read status  */
-    if (rv != APR_SUCCESS) {
-        /* XXX log message */
-	return rv;
-    }
+    h->req_hdrs = apr_table_make(r->pool, 20);
+    h->resp_hdrs = apr_table_make(r->pool, 20);
+    h->resp_err_hdrs = apr_table_make(r->pool, 20);
 
-    r->status = atoi(urlbuff);                           /* Save status line into request rec  */
+    /* Call routine to read the header lines/status line */
+    read_table(h, r, h->resp_hdrs, dobj->hfd);
+    read_table(h, r, h->req_hdrs, dobj->hfd);
 
-    /* Read and ignore the status line (This request might result in a
-     * 304, so we don't necessarily want to retransmit a 200 from the cache.)
-     */
-    rv = apr_file_gets(&urlbuff[0], urllen, dobj->hfd);
-    if (rv != APR_SUCCESS) {
-        /* XXX log message */
-	return rv;
-    }
-
-    h->req_hdrs = apr_table_make(r->pool, 20);
-    
-    /*
-     * Call routine to read the header lines/status line 
-     */
-    tmp = r->err_headers_out;
-    r->err_headers_out = h->req_hdrs;
-    rv = apr_file_gets(&urlbuff[0], urllen, dobj->hfd);           /* Read status  */
-    ap_scan_script_header_err(r, dobj->hfd, NULL);
-    r->err_headers_out = tmp;
- 
     apr_file_close(dobj->hfd);
 
-    ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
-                 "disk_cache: Served headers for URL %s",  dobj->name);
+    h->status = dobj->disk_info.status;
+    h->content_type = apr_table_get(h->resp_hdrs, "Content-Type");
+
+    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
+                 "disk_cache: Recalled headers for URL %s",  dobj->name);
     return APR_SUCCESS;
 }
 
-static apr_status_t read_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb) 
+static apr_status_t recall_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb)
 {
     apr_bucket *e;
     disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;
@@ -558,29 +517,55 @@
     return APR_SUCCESS;
 }
 
-static apr_status_t write_headers(cache_handle_t *h, request_rec *r, cache_info *info)
+static apr_status_t store_table(apr_file_t *fd, apr_table_t *table)
+{
+    int i;
+    apr_status_t rv;
+    struct iovec iov[4];
+    apr_size_t amt;
+    apr_table_entry_t *elts;
+
+    elts = (apr_table_entry_t *) apr_table_elts(table)->elts;
+    for (i = 0; i < apr_table_elts(table)->nelts; ++i) {
+        if (elts[i].key != NULL) {
+            iov[0].iov_base = elts[i].key;
+            iov[0].iov_len = strlen(elts[i].key);
+            iov[1].iov_base = ": ";
+            iov[1].iov_len = sizeof(": ") - 1;
+            iov[2].iov_base = elts[i].val;
+            iov[2].iov_len = strlen(elts[i].val);
+            iov[3].iov_base = CRLF;
+            iov[3].iov_len = sizeof(CRLF) - 1;
+
+            rv = apr_file_writev(fd, (const struct iovec *) &iov, 4,
+                                 &amt);
+            if (rv != APR_SUCCESS) {
+                return rv;
+            }
+        }
+    }
+    iov[0].iov_base = CRLF;
+    iov[0].iov_len = sizeof(CRLF) - 1;
+    rv = apr_file_writev(fd, (const struct iovec *) &iov, 1,
+                         &amt);
+    return rv;
+}
+
+static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *info)
 {
-    disk_cache_conf *conf = ap_get_module_config(r->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
                                                  &disk_cache_module);
     apr_status_t rv;
-    char *buf;
-    char statusbuf[8];
     apr_size_t amt;
     disk_cache_object_t *dobj = (disk_cache_object_t*) h->cache_obj->vobj;
-    apr_file_t *hfd = dobj->hfd;
 
-    if (!hfd)  {
-        if (!dobj->hdrsfile) {
-            dobj->hdrsfile = header_file(r->pool, 
-                                         conf->dirlevels, 
-                                         conf->dirlength, 
-                                         conf->cache_root,
-                                         h->cache_obj->key);
-        }
-        
+    if (!dobj->hfd)  {
+        disk_cache_info_t disk_info;
+        struct iovec iov[2];
+
         /* This is flaky... we need to manage the cache_info differently */
         h->cache_obj->info = *info;
-        
+
         /* Remove old file with the same name. If remove fails, then
          * perhaps we need to create the directory tree where we are
          * about to write the new headers file.
@@ -596,102 +581,171 @@
         if (rv != APR_SUCCESS) {
             return rv;
         }
-        hfd = dobj->hfd;
         dobj->name = h->cache_obj->key;
 
-        file_cache_write_mydata(dobj->hfd, h, r);
+        disk_info.format = DISK_FORMAT_VERSION;
+        disk_info.date = info->date;
+        disk_info.expire = info->expire;
+        disk_info.entity_version = dobj->disk_info.entity_version++;
+        disk_info.request_time = info->request_time;
+        disk_info.response_time = info->response_time;
+        disk_info.status = info->status;
+
+        disk_info.name_len = strlen(dobj->name);
+
+        iov[0].iov_base = (void*)&disk_info;
+        iov[0].iov_len = sizeof(disk_cache_info_t);
+        iov[1].iov_base = dobj->name;
+        iov[1].iov_len = disk_info.name_len;
+
+        rv = apr_file_writev(dobj->hfd, (const struct iovec *) &iov, 2, &amt);
+        if (rv != APR_SUCCESS) {
+            return rv;
+        }
 
         if (r->headers_out) {
-            int i;
-            apr_table_t* headers_out = ap_cache_cacheable_hdrs_out(r);
-            apr_table_entry_t *elts = (apr_table_entry_t *) apr_table_elts(headers_out)->elts;
-            for (i = 0; i < apr_table_elts(headers_out)->nelts; ++i) {
-                if (elts[i].key != NULL) {
-                    buf = apr_pstrcat(r->pool, elts[i].key, ": ",  elts[i].val, CRLF, NULL);
-                    amt = strlen(buf);
-                    apr_file_write(hfd, buf, &amt);
-                }
-            }
-            buf = apr_pstrcat(r->pool, CRLF, NULL);
-            amt = strlen(buf);
-            apr_file_write(hfd, buf, &amt);
-            
-            /* This case only occurs when the content is generated locally */
-            if (!apr_table_get(r->headers_out, "Content-Type") && r->content_type) {
-                apr_table_setn(r->headers_out, "Content-Type", 
+            apr_table_t *headers_out;
+
+            headers_out = ap_cache_cacheable_hdrs_out(r->pool, r->headers_out);
+
+            if (!apr_table_get(headers_out, "Content-Type") &&
+                r->content_type) {
+                apr_table_setn(headers_out, "Content-Type",
                                ap_make_content_type(r, r->content_type));
             }
+
+            rv = store_table(dobj->hfd, headers_out);
+            if (rv != APR_SUCCESS) {
+                return rv;
+            }
+
         }
-        sprintf(statusbuf,"%d", r->status);
-        buf = apr_pstrcat(r->pool, statusbuf, CRLF, NULL);
-        amt = strlen(buf);
-        apr_file_write(hfd, buf, &amt);
-
-        /* This case only occurs when the content is generated locally */
-        if (!r->status_line) {
-            r->status_line = ap_get_status_line(r->status);
-        }
-        buf = apr_pstrcat(r->pool, r->status_line, "\n", NULL);
-        amt = strlen(buf);
-        apr_file_write(hfd, buf, &amt);
-        buf = apr_pstrcat(r->pool, CRLF, NULL);
-        amt = strlen(buf);
-        apr_file_write(hfd, buf, &amt);
-
-	/* Parse the vary header and dump those fields from the headers_in. */
-	/* Make call to the same thing cache_select_url calls to crack Vary. */
-	/* @@@ Some day, not today. */
+
+        /* Parse the vary header and dump those fields from the headers_in. */
+        /* Make call to the same thing cache_select_url calls to crack Vary. */
+        /* @@@ Some day, not today. */
         if (r->headers_in) {
-            int i;
-            apr_table_entry_t *elts = (apr_table_entry_t *) apr_table_elts(r->headers_in)->elts;
-            for (i = 0; i < apr_table_elts(r->headers_in)->nelts; ++i) {
-                if (elts[i].key != NULL) {
-                    buf = apr_pstrcat(r->pool, elts[i].key, ": ",  elts[i].val, CRLF, NULL);
-                    amt = strlen(buf);
-                    apr_file_write(hfd, buf, &amt);
-                }
+            apr_table_t *headers_in;
+
+            headers_in = ap_cache_cacheable_hdrs_out(r->pool, r->headers_in);
+            rv = store_table(dobj->hfd, headers_in);
+            if (rv != APR_SUCCESS) {
+                return rv;
             }
-            buf = apr_pstrcat(r->pool, CRLF, NULL);
-            amt = strlen(buf);
-            apr_file_write(hfd, buf, &amt);
         }
-        apr_file_close(hfd); /* flush and close */
+        apr_file_close(dobj->hfd); /* flush and close */
     }
     else {
         /* XXX log message */
     }
 
-    ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
-                 "disk_cache: Caching headers for URL %s",  dobj->name);
+    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
+                 "disk_cache: Stored headers for URL %s",  dobj->name);
     return APR_SUCCESS;
 }
-static apr_status_t write_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b) 
+
+static apr_status_t store_body(cache_handle_t *h, request_rec *r,
+                               apr_bucket_brigade *bb)
 {
     apr_bucket *e;
     apr_status_t rv;
     disk_cache_object_t *dobj = (disk_cache_object_t *) h->cache_obj->vobj;
+    disk_cache_conf *conf = ap_get_module_config(r->server->module_config,
+                                                 &disk_cache_module);
 
-    if (!dobj->fd) {
-        rv = apr_file_open(&dobj->fd, dobj->tempfile, 
-                           APR_WRITE | APR_CREATE | APR_BINARY| APR_TRUNCATE | APR_BUFFERED,
-                           APR_UREAD | APR_UWRITE, r->pool);
+    /* We write to a temp file and then atomically rename the file over
+     * in file_cache_el_final().
+     */
+    if (!dobj->tfd) {
+        rv = apr_file_mktemp(&dobj->tfd, dobj->tempfile,
+                             APR_CREATE | APR_WRITE | APR_BINARY |
+                             APR_BUFFERED | APR_EXCL, r->pool);
         if (rv != APR_SUCCESS) {
             return rv;
         }
+        dobj->file_size = 0;
     }
-    APR_BRIGADE_FOREACH(e, b) {
+
+    for (e = APR_BRIGADE_FIRST(bb);
+         e != APR_BRIGADE_SENTINEL(bb);
+         e = APR_BUCKET_NEXT(e))
+    {
         const char *str;
-        apr_size_t length;
+        apr_size_t length, written;
         apr_bucket_read(e, &str, &length, APR_BLOCK_READ);
-        apr_file_write(dobj->fd, str, &length);
+        rv = apr_file_write_full(dobj->tfd, str, length, &written);
+        if (rv != APR_SUCCESS) {
+            ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
+                         "cache_disk: Error when writing cache file for URL %s",
+                         h->cache_obj->key);
+            /* Remove the intermediate cache file and return non-APR_SUCCESS */
+            file_cache_errorcleanup(dobj, r);
+            return APR_EGENERAL;
+        }
+        dobj->file_size += written;
+        if (dobj->file_size > conf->maxfs) {
+            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
+                         "cache_disk: URL %s failed the size check (%lu>%lu)",
+                         h->cache_obj->key, (unsigned long)dobj->file_size,
+                         (unsigned long)conf->maxfs);
+            /* Remove the intermediate cache file and return non-APR_SUCCESS */
+            file_cache_errorcleanup(dobj, r);
+            return APR_EGENERAL;
+        }
     }
-    if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(b))) {
-        file_cache_el_final(h, r);    /* Link to the perm file, and close the descriptor  */
-        ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
-                     "disk_cache: Cached body for URL %s",  dobj->name);
+
+    /* Was this the final bucket? If yes, close the temp file and perform
+     * sanity checks.
+     */
+    if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
+        if (h->cache_obj->info.len <= 0) {
+          /* If the target value of the content length is unknown
+           * (h->cache_obj->info.len <= 0), check if connection has been
+           * aborted by client to avoid caching incomplete request bodies.
+           *
+           * This can happen with large responses from slow backends like
+           * Tomcat via mod_jk.
+           */
+          if (r->connection->aborted) {
+            ap_log_error(APLOG_MARK, APLOG_INFO, 0, r->server,
+                         "disk_cache: Discarding body for URL %s "
+                         "because connection has been aborted.",
+                         h->cache_obj->key);
+            /* Remove the intermediate cache file and return non-APR_SUCCESS */
+            file_cache_errorcleanup(dobj, r);
+            return APR_EGENERAL;
+          }
+          /* XXX Fixme: file_size isn't constrained by size_t. */
+          h->cache_obj->info.len = dobj->file_size;
+        }
+        else if (h->cache_obj->info.len != dobj->file_size) {
+          /* "Content-Length" and actual content disagree in size. Log that. */
+          ap_log_error(APLOG_MARK, APLOG_ERR, 0, r->server,
+                       "disk_cache: URL %s failed the size check (%lu != %lu)",
+                       h->cache_obj->key,
+                       (unsigned long)h->cache_obj->info.len,
+                       (unsigned long)dobj->file_size);
+          /* Remove the intermediate cache file and return non-APR_SUCCESS */
+          file_cache_errorcleanup(dobj, r);
+          return APR_EGENERAL;
+        }
+        if (dobj->file_size < conf->minfs) {
+          ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
+                     "cache_disk: URL %s failed the size check (%lu<%lu)",
+                     h->cache_obj->key, (unsigned long)dobj->file_size, (unsigned long)conf->minfs);
+          /* Remove the intermediate cache file and return non-APR_SUCCESS */
+          file_cache_errorcleanup(dobj, r);
+          return APR_EGENERAL;
+        }
+
+        /* All checks were fine. Move tempfile to final destination */
+        /* Link to the perm file, and close the descriptor */
+        file_cache_el_final(dobj, r);
+        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
+                     "disk_cache: Body for URL %s cached.",  dobj->name);
     }
 
-    return APR_SUCCESS;	
+    return APR_SUCCESS;
 }
 
 static void *create_config(apr_pool_t *p, server_rec *s)
@@ -718,7 +772,7 @@
 static const char
 *set_cache_root(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     conf->cache_root = arg;
     conf->cache_root_len = strlen(arg);
@@ -729,7 +783,7 @@
 static const char
 *set_cache_size(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     conf->space = atoi(arg);
     return NULL;
@@ -738,7 +792,7 @@
 *set_cache_gcint(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
 /*
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
 */
     /* XXX */
@@ -747,13 +801,13 @@
 /*
  * Consider eliminating the next two directives in favor of
  * Ian's prime number hash...
- * key = hash_fn( r->uri) 
- * filename = "/key % prime1 /key %prime2/key %prime3" 
+ * key = hash_fn( r->uri)
+ * filename = "/key % prime1 /key %prime2/key %prime3"
  */
 static const char
 *set_cache_dirlevels(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     int val = atoi(arg);
     if (val < 1)
@@ -766,7 +820,7 @@
 static const char
 *set_cache_dirlength(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     int val = atoi(arg);
     if (val < 1)
@@ -780,7 +834,7 @@
 static const char
 *set_cache_exchk(cmd_parms *parms, void *in_struct_ptr, int flag)
 {
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     conf->expirychk = flag;
 
@@ -789,7 +843,7 @@
 static const char
 *set_cache_minfs(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     conf->minfs = atoi(arg);
     return NULL;
@@ -797,7 +851,7 @@
 static const char
 *set_cache_maxfs(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     conf->maxfs = atoi(arg);
     return NULL;
@@ -806,7 +860,7 @@
 *set_cache_minetm(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
     /* XXX
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     */
     return NULL;
@@ -815,7 +869,7 @@
 *set_cache_gctime(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
     /* XXX
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     */
     return NULL;
@@ -824,7 +878,7 @@
 *add_cache_gcclean(cmd_parms *parms, void *in_struct_ptr, const char *arg, const char *arg1)
 {
     /* XXX
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     */
     return NULL;
@@ -833,7 +887,7 @@
 *add_cache_gcclnun(cmd_parms *parms, void *in_struct_ptr, const char *arg, const char *arg1)
 {
     /* XXX
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     */
     return NULL;
@@ -842,7 +896,7 @@
 *set_cache_maxgcmem(cmd_parms *parms, void *in_struct_ptr, const char *arg)
 {
     /* XXX
-    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config, 
+    disk_cache_conf *conf = ap_get_module_config(parms->server->module_config,
                                                  &disk_cache_module);
     */
     return NULL;
@@ -879,12 +933,23 @@
     {NULL}
 };
 
+static const cache_provider cache_disk_provider =
+{
+    &remove_entity,
+    &store_headers,
+    &store_body,
+    &recall_headers,
+    &recall_body,
+    &create_entity,
+    &open_entity,
+    &remove_url,
+};
+
 static void disk_cache_register_hook(apr_pool_t *p)
 {
     /* cache initializer */
-    cache_hook_create_entity(create_entity, NULL, NULL, APR_HOOK_MIDDLE);
-    cache_hook_open_entity(open_entity,  NULL, NULL, APR_HOOK_MIDDLE);
-/*    cache_hook_remove_entity(remove_entity, NULL, NULL, APR_HOOK_MIDDLE); */
+    ap_register_provider(p, CACHE_PROVIDER_GROUP, "disk", "0",
+                         &cache_disk_provider);
 }
 
 module AP_MODULE_DECLARE_DATA disk_cache_module = {
Index: modules/experimental/mod_mem_cache.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/experimental/mod_mem_cache.c,v
retrieving revision 1.1.1.1
retrieving revision 1.8
diff -u -u -r1.1.1.1 -r1.8
--- modules/experimental/mod_mem_cache.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/experimental/mod_mem_cache.c	13 Jan 2005 15:04:55 -0000	1.8
@@ -1,65 +1,44 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/* Copyright 2001-2004 The Apache Software Foundation
  *
- * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
- * reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Apache" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Rules for managing obj->refcount:
+ * refcount should be incremented when an object is placed in the cache. Insertion 
+ *   of an object into the cache and the refcount increment should happen under 
+ *   protection of the sconf->lock.
  *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
+ * refcount should be decremented when the object is removed from the cache.
+ *   Object should be removed from the cache and the refcount decremented while
+ *   under protection of the sconf->lock.
+ * 
+ * refcount should be incremented when an object is retrieved from the cache
+ *   by a worker thread. The retrieval/find operation and refcount increment
+ *   should occur under protection of the sconf->lock
  *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
+ * refcount can be atomically decremented w/o protection of the sconf->lock
+ *   by worker threads.
  *
- * Portions of this software are based upon public domain software
- * originally written at the National Center for Supercomputing Applications,
- * University of Illinois, Urbana-Champaign.
+ * Any object whose refcount drops to 0 should be freed/cleaned up. A refcount 
+ * of 0 means the object is not in the cache and no worker threads are accessing 
+ * it.
  */
-
 #define CORE_PRIVATE
 #include "mod_cache.h"
 #include "cache_pqueue.h"
 #include "cache_cache.h"
+#include "ap_provider.h"
 #include "ap_mpm.h"
 #include "apr_thread_mutex.h"
 #if APR_HAVE_UNISTD_H
@@ -86,10 +65,12 @@
 typedef struct mem_cache_object {
     cache_type_e type;
     apr_ssize_t num_header_out;
+    apr_ssize_t num_err_header_out;
     apr_ssize_t num_subprocess_env;
     apr_ssize_t num_notes;
     apr_ssize_t num_req_hdrs;
     cache_header_tbl_t *header_out;
+    cache_header_tbl_t *err_header_out;
     cache_header_tbl_t *subprocess_env;
     cache_header_tbl_t *notes;
     cache_header_tbl_t *req_hdrs; /* for Vary negotiation */
@@ -100,19 +81,13 @@
     long priority;      /**< the priority of this entry */
     long total_refs;          /**< total number of references this entry has had */
 
-#ifdef USE_ATOMICS
-    apr_atomic_t pos;   /**< the position of this entry in the cache */
-#else
-    apr_ssize_t pos;
-#endif
+    apr_uint32_t pos;   /**< the position of this entry in the cache */
 
 } mem_cache_object_t;
 
 typedef struct {
     apr_thread_mutex_t *lock;
     cache_cache_t *cache_cache;
-    apr_size_t cache_size;
-    apr_size_t object_cnt;
 
     /* Fields set by config directives */
     apr_size_t min_cache_object_size;   /* in bytes */
@@ -136,10 +111,10 @@
 
 /* Forward declarations */
 static int remove_entity(cache_handle_t *h);
-static apr_status_t write_headers(cache_handle_t *h, request_rec *r, cache_info *i);
-static apr_status_t write_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b);
-static apr_status_t read_headers(cache_handle_t *h, request_rec *r);
-static apr_status_t read_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb);
+static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *i);
+static apr_status_t store_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b);
+static apr_status_t recall_headers(cache_handle_t *h, request_rec *r);
+static apr_status_t recall_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb);
 
 static void cleanup_cache_object(cache_object_t *obj);
 
@@ -165,22 +140,14 @@
     cache_object_t *obj = (cache_object_t *)a;
     mem_cache_object_t *mobj = obj->vobj;
 
-#ifdef USE_ATOMICS
     apr_atomic_set(&mobj->pos, pos);
-#else
-    mobj->pos = pos;
-#endif    
 }
 static apr_ssize_t memcache_get_pos(void *a)
 {
     cache_object_t *obj = (cache_object_t *)a;
     mem_cache_object_t *mobj = obj->vobj;
 
-#ifdef USE_ATOMICS
     return apr_atomic_read(&mobj->pos);
-#else
-    return mobj->pos;
-#endif    
 }
 
 static apr_size_t memcache_cache_get_size(void*a)
@@ -196,54 +163,40 @@
     return obj->key;
 }
 /** 
- * callback to free an entry 
- * There is way too much magic in this code. Right now, this callback
- * is only called out of cache_insert() which is called under protection
- * of the sconf->lock, which means that we do not (and should not)
- * attempt to obtain the lock recursively. 
+ * memcache_cache_free()
+ * memcache_cache_free is a callback that is only invoked by a thread 
+ * running in cache_insert(). cache_insert() runs under protection
+ * of sconf->lock.  By the time this function has been entered, the cache_object
+ * has been ejected from the cache. decrement the refcount and if the refcount drops
+ * to 0, cleanup the cache object.
  */
 static void memcache_cache_free(void*a)
 {
     cache_object_t *obj = (cache_object_t *)a;
 
-    /* Cleanup the cache object. Object should be removed from the cache
-     * now. Increment the refcount before setting cleanup to avoid a race 
-     * condition. A similar pattern is used in remove_url()
+    /* Decrement the refcount to account for the object being ejected
+     * from the cache. If the refcount is 0, free the object.
      */
-#ifdef USE_ATOMICS
-    apr_atomic_inc(&obj->refcount);
-#else
-    obj->refcount++;
-#endif
-
-    obj->cleanup = 1;
-
-#ifdef USE_ATOMICS
     if (!apr_atomic_dec(&obj->refcount)) {
         cleanup_cache_object(obj);
     }
-#else
-    obj->refcount--;
-    if (!obj->refcount) {
-        cleanup_cache_object(obj);
-    }
-#endif
 }
 /*
- * functions return a 'negative' score as lower is better in a priority Q
+ * functions return a 'negative' score since priority queues
+ * dequeue the object with the highest value first
  */
 static long memcache_lru_algorithm(long queue_clock, void *a) 
 {
     cache_object_t *obj = (cache_object_t *)a;
     mem_cache_object_t *mobj = obj->vobj;
     if (mobj->priority == 0)
-        mobj->priority = ((long)(queue_clock + mobj->total_refs));
+        mobj->priority = queue_clock - mobj->total_refs;
 
     /*	
      * a 'proper' LRU function would just be
      *  mobj->priority = mobj->total_refs; 
      */
-    return -1*mobj->priority;
+    return mobj->priority;
 }
 
 static long memcache_gdsf_algorithm(long queue_clock, void *a) 
@@ -252,9 +205,10 @@
     mem_cache_object_t *mobj = obj->vobj;
 
     if (mobj->priority == 0)
-        mobj->priority = queue_clock + (long)(mobj->total_refs*1000 / mobj->m_len);
+        mobj->priority = queue_clock -
+                           (long)(mobj->total_refs*1000 / mobj->m_len);
 
-    return -1*mobj->priority;
+    return mobj->priority;
 }
 
 static void cleanup_cache_object(cache_object_t *obj)
@@ -303,6 +257,11 @@
                 free(mobj->header_out[0].hdr);
             free(mobj->header_out);
         }
+        if (mobj->err_header_out) {
+            if (mobj->err_header_out[0].hdr) 
+                free(mobj->err_header_out[0].hdr);
+            free(mobj->err_header_out);
+        }
         if (mobj->subprocess_env) {
             if (mobj->subprocess_env[0].hdr) 
                 free(mobj->subprocess_env[0].hdr);
@@ -327,49 +286,29 @@
 
     /* If obj->complete is not set, the cache update failed and the
      * object needs to be removed from the cache then cleaned up.
+     * The garbage collector may have ejected the object from the
+     * cache already, so make sure it is really still in the cache
+     * before attempting to remove it.
      */
     if (!obj->complete) {
-        mem_cache_object_t *mobj = (mem_cache_object_t *) obj->vobj;
+        cache_object_t *tobj = NULL;
         if (sconf->lock) {
             apr_thread_mutex_lock(sconf->lock);
         }
-        /* Remember, objects marked for cleanup are, by design, already
-         * removed from the cache. remove_url() could have already
-         * removed the object from the cache (and set obj->cleanup)
-         */
-        if (!obj->cleanup) {
+        tobj = cache_find(sconf->cache_cache, obj->key);
+        if (tobj == obj) {
             cache_remove(sconf->cache_cache, obj);
-            sconf->object_cnt--;
-            sconf->cache_size -= mobj->m_len;
-            obj->cleanup = 1;
+            apr_atomic_dec(&obj->refcount);
         }
         if (sconf->lock) {
             apr_thread_mutex_unlock(sconf->lock);
         }
-    }
+    } 
 
-    /* Cleanup the cache object */
-#ifdef USE_ATOMICS
+    /* If the refcount drops to 0, cleanup the cache object */
     if (!apr_atomic_dec(&obj->refcount)) {
-        if (obj->cleanup) {
-            cleanup_cache_object(obj);
-        }
-    }
-#else
-    if (sconf->lock) {
-        apr_thread_mutex_lock(sconf->lock);
-    }
-    obj->refcount--;
-    /* If the object is marked for cleanup and the refcount
-     * has dropped to zero, cleanup the object
-     */
-    if ((obj->cleanup) && (!obj->refcount)) {
         cleanup_cache_object(obj);
     }
-    if (sconf->lock) {
-        apr_thread_mutex_unlock(sconf->lock);
-    }
-#endif
     return APR_SUCCESS;
 }
 static apr_status_t cleanup_cache_mem(void *sconfv)
@@ -389,16 +328,8 @@
     }
     obj = cache_pop(co->cache_cache);
     while (obj) {         
-    /* Iterate over the cache and clean up each entry */  
-    /* Free the object if the recount == 0 */
-#ifdef USE_ATOMICS
-        apr_atomic_inc(&obj->refcount);
-        obj->cleanup = 1;
+        /* Iterate over the cache and clean up each unreferenced entry */
         if (!apr_atomic_dec(&obj->refcount)) {
-#else
-        obj->cleanup = 1;
-        if (!obj->refcount) {
-#endif
             cleanup_cache_object(obj);
         }
         obj = cache_pop(co->cache_cache);
@@ -423,10 +354,8 @@
     sconf->max_cache_object_size = DEFAULT_MAX_CACHE_OBJECT_SIZE;
     /* Number of objects in the cache */
     sconf->max_object_cnt = DEFAULT_MAX_OBJECT_CNT;
-    sconf->object_cnt = 0;
     /* Size of the cache in bytes */
     sconf->max_cache_size = DEFAULT_MAX_CACHE_SIZE;
-    sconf->cache_size = 0;
     sconf->cache_cache = NULL;
     sconf->cache_remove_algorithm = memcache_gdsf_algorithm;
     sconf->max_streaming_buffer_size = DEFAULT_MAX_STREAMING_BUFFER_SIZE;
@@ -434,30 +363,17 @@
     return sconf;
 }
 
-static int create_entity(cache_handle_t *h, request_rec *r,
-                         const char *type, 
-                         const char *key, 
-                         apr_off_t len) 
+static int create_entity(cache_handle_t *h, cache_type_e type_e,
+                         request_rec *r, const char *key, apr_off_t len) 
 {
     cache_object_t *obj, *tmp_obj;
     mem_cache_object_t *mobj;
-    cache_type_e type_e;
     apr_size_t key_len;
 
-    if (!strcasecmp(type, "mem")) {
-        type_e = CACHE_TYPE_HEAP;
-    } 
-    else if (!strcasecmp(type, "fd")) {
-        type_e = CACHE_TYPE_FILE;
-    }
-    else {
-        return DECLINED;
-    }
-
     if (len == -1) {
         /* Caching a streaming response. Assume the response is
          * less than or equal to max_streaming_buffer_size. We will
-         * correct all the cache size counters in write_body once
+         * correct all the cache size counters in store_body once
          * we know exactly know how much we are caching.
          */
         len = sconf->max_streaming_buffer_size;
@@ -509,14 +425,9 @@
     }
 
     /* Finish initing the cache object */
-#ifdef USE_ATOMICS
     apr_atomic_set(&obj->refcount, 1);
-#else 
-    obj->refcount = 1;
-#endif
     mobj->total_refs = 1;
     obj->complete = 0;
-    obj->cleanup = 0;
     obj->vobj = mobj;
     /* Safe cast: We tested < sconf->max_cache_object_size above */
     mobj->m_len = (apr_size_t)len;
@@ -526,7 +437,7 @@
      * Note: Perhaps we should wait to put the object in the
      * hash table when the object is complete?  I add the object here to
      * avoid multiple threads attempting to cache the same content only
-     * to discover at the very end that only one of them will suceed.
+     * to discover at the very end that only one of them will succeed.
      * Furthermore, adding the cache object to the table at the end could
      * open up a subtle but easy to exploit DoS hole: someone could request 
      * a very large file with multiple requests. Better to detect this here
@@ -540,10 +451,12 @@
     tmp_obj = (cache_object_t *) cache_find(sconf->cache_cache, key);
 
     if (!tmp_obj) {
-        cache_insert(sconf->cache_cache, obj);     
-        sconf->object_cnt++;
-        /* Safe cast: Must fit in cache_size or alloc would have failed */
-        sconf->cache_size += (apr_size_t)len;
+        cache_insert(sconf->cache_cache, obj);
+        /* Add a refcount to account for the reference by the 
+         * hashtable in the cache. Refcount should be 2 now, one
+         * for this thread, and one for the cache.
+         */
+        apr_atomic_inc(&obj->refcount);
     }
     if (sconf->lock) {
         apr_thread_mutex_unlock(sconf->lock);
@@ -563,23 +476,27 @@
 
     /* Populate the cache handle */
     h->cache_obj = obj;
-    h->read_body = &read_body;
-    h->read_headers = &read_headers;
-    h->write_body = &write_body;
-    h->write_headers = &write_headers;
-    h->remove_entity = &remove_entity;
 
     return OK;
 }
 
-static int open_entity(cache_handle_t *h, request_rec *r, const char *type, const char *key) 
+static int create_mem_entity(cache_handle_t *h, request_rec *r,
+                             const char *key, apr_off_t len) 
+{
+    return create_entity(h, CACHE_TYPE_HEAP, r, key, len);
+}
+
+static int create_fd_entity(cache_handle_t *h, request_rec *r,
+                            const char *key, apr_off_t len) 
+{
+    return create_entity(h, CACHE_TYPE_FILE, r, key, len);
+}
+
+static int open_entity(cache_handle_t *h, request_rec *r, const char *key) 
 {
     cache_object_t *obj;
 
     /* Look up entity keyed to 'url' */
-    if (strcasecmp(type, "mem") && strcasecmp(type, "fd")) {
-        return DECLINED;
-    }
     if (sconf->lock) {
         apr_thread_mutex_lock(sconf->lock);
     }
@@ -587,11 +504,7 @@
     if (obj) {
         if (obj->complete) {
             request_rec *rmain=r, *rtmp;
-#ifdef USE_ATOMICS
             apr_atomic_inc(&obj->refcount);
-#else
-            obj->refcount++;
-#endif
             /* cache is worried about overall counts, not 'open' ones */
             cache_update(sconf->cache_cache, obj);
 
@@ -622,38 +535,38 @@
     }
 
     /* Initialize the cache_handle */
-    h->read_body = &read_body;
-    h->read_headers = &read_headers;
-    h->write_body = &write_body;
-    h->write_headers = &write_headers;
-    h->remove_entity = &remove_entity;
     h->cache_obj = obj;
-    h->req_hdrs = NULL;  /* Pick these up in read_headers() */
+    h->req_hdrs = NULL;  /* Pick these up in recall_headers() */
     return OK;
 }
 
+/* remove_entity()
+ * Notes: 
+ *   refcount should be at least 1 upon entry to this function to account
+ *   for this thread's reference to the object. If the refcount is 1, then
+ *   object has been removed from the cache by another thread and this thread
+ *   is the last thread accessing the object.
+ */
 static int remove_entity(cache_handle_t *h) 
 {
     cache_object_t *obj = h->cache_obj;
+    cache_object_t *tobj = NULL;
 
-    /* Remove the cache object from the cache under protection */
     if (sconf->lock) {
         apr_thread_mutex_lock(sconf->lock);
     }
-    /* If the object is not already marked for cleanup, remove
-     * it from the cache and mark it for cleanup. Remember,
-     * an object marked for cleanup is by design not in the
-     * hash table.
+
+    /* If the entity is still in the cache, remove it and decrement the
+     * refcount. If the entity is not in the cache, do nothing. In both cases
+     * decrement_refcount called by the last thread referencing the object will 
+     * trigger the cleanup.
      */
-    if (!obj->cleanup) {
-        mem_cache_object_t *mobj = (mem_cache_object_t *) obj->vobj;
+    tobj = cache_find(sconf->cache_cache, obj->key);
+    if (tobj == obj) {
         cache_remove(sconf->cache_cache, obj);
-        sconf->object_cnt--;
-        sconf->cache_size -= mobj->m_len;
-        obj->cleanup = 1;
-        ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL, "gcing a cache entry");
+        apr_atomic_dec(&obj->refcount);
     }
-
+    
     if (sconf->lock) {
         apr_thread_mutex_unlock(sconf->lock);
     }
@@ -719,69 +632,44 @@
     return APR_SUCCESS;
 }
 /* Define request processing hook handlers */
-static int remove_url(const char *type, const char *key) 
+/* remove_url()
+ * Notes:
+ */
+static int remove_url(const char *key) 
 {
     cache_object_t *obj;
+    int cleanup = 0;
 
-    if (strcasecmp(type, "mem") && strcasecmp(type, "fd")) {
-        return DECLINED;
-    }
-    /* Order of the operations is important to avoid race conditions. 
-     * First, remove the object from the cache. Remember, all additions
-     * deletions from the cache are protected by sconf->lock.
-     * Increment the ref count on the object to indicate our thread
-     * is accessing the object. Then set the cleanup flag on the
-     * object. Remember, the cleanup flag is NEVER set on an
-     * object in the hash table.  If an object has the cleanup
-     * flag set, it is guaranteed to NOT be in the hash table.
-     */
     if (sconf->lock) {
         apr_thread_mutex_lock(sconf->lock);
     }
   
     obj = cache_find(sconf->cache_cache, key);       
     if (obj) {
-        mem_cache_object_t *mobj;
         cache_remove(sconf->cache_cache, obj);
-        mobj = (mem_cache_object_t *) obj->vobj;
-        sconf->object_cnt--;
-        sconf->cache_size -= mobj->m_len;
-
-#ifdef USE_ATOMICS
-        /* Refcount increment in this case MUST be made under 
-         * protection of the lock 
-         */
-        apr_atomic_inc(&obj->refcount);
-#else
-        if (!obj->refcount) {
-            cleanup_cache_object(obj);
-            obj = NULL;
-        }
-#endif
-        if (obj) {
-            obj->cleanup = 1;
-        }
+        /* For performance, cleanup cache object after releasing the lock */
+        cleanup = !apr_atomic_dec(&obj->refcount);
     }
     if (sconf->lock) {
         apr_thread_mutex_unlock(sconf->lock);
     }
-#ifdef USE_ATOMICS
-    if (obj) {
-        if (!apr_atomic_dec(&obj->refcount)) {
-            cleanup_cache_object(obj);
-        }
+
+    if (cleanup) {
+        cleanup_cache_object(obj);
     }
-#endif
+
     return OK;
 }
 
-static apr_status_t read_headers(cache_handle_t *h, request_rec *r) 
+static apr_status_t recall_headers(cache_handle_t *h, request_rec *r) 
 {
     int rc;
     mem_cache_object_t *mobj = (mem_cache_object_t*) h->cache_obj->vobj;
  
     h->req_hdrs = apr_table_make(r->pool, mobj->num_req_hdrs);
-    r->headers_out = apr_table_make(r->pool, mobj->num_header_out);
+    h->resp_hdrs = apr_table_make(r->pool, mobj->num_header_out);
+    h->resp_err_hdrs = apr_table_make(r->pool, mobj->num_err_header_out);
+    /* ### FIXME: These two items should not be saved. */
     r->subprocess_env = apr_table_make(r->pool, mobj->num_subprocess_env);
     r->notes = apr_table_make(r->pool, mobj->num_notes);
 
@@ -790,7 +678,10 @@
                            h->req_hdrs);
     rc = unserialize_table( mobj->header_out,
                             mobj->num_header_out, 
-                            r->headers_out);
+                            h->resp_hdrs);
+    rc = unserialize_table( mobj->err_header_out,
+                            mobj->num_err_header_out, 
+                            h->resp_err_hdrs);
     rc = unserialize_table( mobj->subprocess_env, 
                             mobj->num_subprocess_env, 
                             r->subprocess_env);
@@ -801,12 +692,13 @@
     /* Content-Type: header may not be set if content is local since
      * CACHE_IN runs before header filters....
      */
-    ap_set_content_type(r, apr_pstrdup(r->pool, h->cache_obj->info.content_type));
+    h->content_type = h->cache_obj->info.content_type;
+    h->status = h->cache_obj->info.status;
 
     return rc;
 }
 
-static apr_status_t read_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb) 
+static apr_status_t recall_body(cache_handle_t *h, apr_pool_t *p, apr_bucket_brigade *bb) 
 {
     apr_bucket *b;
     mem_cache_object_t *mobj = (mem_cache_object_t*) h->cache_obj->vobj;
@@ -829,7 +721,7 @@
 }
 
 
-static apr_status_t write_headers(cache_handle_t *h, request_rec *r, cache_info *info)
+static apr_status_t store_headers(cache_handle_t *h, request_rec *r, cache_info *info)
 {
     cache_object_t *obj = h->cache_obj;
     mem_cache_object_t *mobj = (mem_cache_object_t*) obj->vobj;
@@ -852,7 +744,13 @@
     /* Precompute how much storage we need to hold the headers */
     rc = serialize_table(&mobj->header_out, 
                          &mobj->num_header_out, 
-                         ap_cache_cacheable_hdrs_out(r));   
+                         ap_cache_cacheable_hdrs_out(r->pool, r->headers_out));   
+    if (rc != APR_SUCCESS) {
+        return rc;
+    }
+    rc = serialize_table(&mobj->err_header_out, 
+                         &mobj->num_err_header_out, 
+                         ap_cache_cacheable_hdrs_out(r->pool, r->err_headers_out));   
     if (rc != APR_SUCCESS) {
         return rc;
     }
@@ -869,6 +767,7 @@
     }
  
     /* Init the info struct */
+    obj->info.status = info->status;
     if (info->date) {
         obj->info.date = info->date;
     }
@@ -892,6 +791,22 @@
         }
         memcpy(obj->info.content_type, info->content_type, len);
     }
+    if (info->etag) {
+        apr_size_t len = strlen(info->etag) + 1;
+        obj->info.etag = (char*) malloc(len);
+        if (!obj->info.etag) {
+            return APR_ENOMEM;
+        }
+        memcpy(obj->info.etag, info->etag, len);
+    }
+    if (info->lastmods) {
+        apr_size_t len = strlen(info->lastmods) + 1;
+        obj->info.lastmods = (char*) malloc(len);
+        if (!obj->info.lastmods) {
+            return APR_ENOMEM;
+        }
+        memcpy(obj->info.lastmods, info->lastmods, len);
+    }
     if ( info->filename) {
         apr_size_t len = strlen(info->filename) + 1;
         obj->info.filename = (char*) malloc(len);
@@ -904,10 +819,11 @@
     return APR_SUCCESS;
 }
 
-static apr_status_t write_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b) 
+static apr_status_t store_body(cache_handle_t *h, request_rec *r, apr_bucket_brigade *b) 
 {
     apr_status_t rv;
     cache_object_t *obj = h->cache_obj;
+    cache_object_t *tobj = NULL;
     mem_cache_object_t *mobj = (mem_cache_object_t*) obj->vobj;
     apr_read_type_e eblock = APR_BLOCK_READ;
     apr_bucket *e;
@@ -924,7 +840,10 @@
          * - the brigade is complete &&
          * - the file_bucket is the last data bucket in the brigade
          */
-        APR_BRIGADE_FOREACH(e, b) {
+        for (e = APR_BRIGADE_FIRST(b);
+             e != APR_BRIGADE_SENTINEL(b);
+             e = APR_BUCKET_NEXT(e))
+        {
             if (APR_BUCKET_IS_EOS(e)) {
                 eos = 1;
             }
@@ -949,7 +868,7 @@
             if (rv != APR_SUCCESS) {
                 return rv;
             }
-            apr_file_unset_inherit(tmpfile);
+            apr_file_inherit_unset(tmpfile);
             apr_os_file_get(&(mobj->fd), tmpfile);
 
             /* Open for business */
@@ -977,7 +896,10 @@
     cur = (char*) mobj->m + obj->count;
 
     /* Iterate accross the brigade and populate the cache storage */
-    APR_BRIGADE_FOREACH(e, b) {
+    for (e = APR_BRIGADE_FIRST(b);
+         e != APR_BRIGADE_SENTINEL(b);
+         e = APR_BUCKET_NEXT(e))
+    {
         const char *s;
         apr_size_t len;
 
@@ -1002,10 +924,39 @@
                 if (sconf->lock) {
                     apr_thread_mutex_lock(sconf->lock);
                 }
-                cache_remove(sconf->cache_cache, obj);
-                mobj->m_len = obj->count;
-                cache_insert(sconf->cache_cache, obj);                
-                sconf->cache_size -= (mobj->m_len - obj->count);
+                /* Has the object been ejected from the cache?
+                 */
+                tobj = (cache_object_t *) cache_find(sconf->cache_cache, obj->key);
+                if (tobj == obj) {
+                    /* Object is still in the cache, remove it, update the len field then
+                     * replace it under protection of sconf->lock.
+                     */
+                    cache_remove(sconf->cache_cache, obj);
+                    /* For illustration, cache no longer has reference to the object
+                     * so decrement the refcount
+                     * apr_atomic_dec(&obj->refcount); 
+                     */
+                    mobj->m_len = obj->count;
+
+                    cache_insert(sconf->cache_cache, obj);
+                    /* For illustration, cache now has reference to the object, so
+                     * increment the refcount
+                     * apr_atomic_inc(&obj->refcount); 
+                     */
+                }
+                else if (tobj) {
+                    /* Different object with the same key found in the cache. Doing nothing
+                     * here will cause the object refcount to drop to 0 in decrement_refcount
+                     * and the object will be cleaned up.
+                     */
+
+                } else {
+                    /* Object has been ejected from the cache, add it back to the cache */
+                    mobj->m_len = obj->count;
+                    cache_insert(sconf->cache_cache, obj);
+                    apr_atomic_inc(&obj->refcount); 
+                }
+
                 if (sconf->lock) {
                     apr_thread_mutex_unlock(sconf->lock);
                 }
@@ -1163,13 +1114,14 @@
 static const char *set_max_streaming_buffer(cmd_parms *parms, void *dummy,
                                             const char *arg)
 {
-    apr_off_t val;
+#if 0
     char *err;
-    val = (apr_off_t)strtol(arg, &err, 10);
-    if (*err != 0) {
+    if (apr_strtoff(&sconf->max_streaming_buffer_size, arg, &err, 10) || *err) {
         return "MCacheMaxStreamingBuffer value must be a number";
     }
-    sconf->max_streaming_buffer_size = val;
+#else
+    sconf->max_streaming_buffer_size = apr_atoi64(arg);
+#endif
     return NULL;
 }
 
@@ -1190,14 +1142,44 @@
     {NULL}
 };
 
+static const cache_provider cache_mem_provider =
+{
+    &remove_entity,
+    &store_headers,
+    &store_body,
+    &recall_headers,
+    &recall_body,
+    &create_mem_entity,
+    &open_entity,
+    &remove_url,
+};
+
+static const cache_provider cache_fd_provider =
+{
+    &remove_entity,
+    &store_headers,
+    &store_body,
+    &recall_headers,
+    &recall_body,
+    &create_fd_entity,
+    &open_entity,
+    &remove_url,
+};
+
 static void register_hooks(apr_pool_t *p)
 {
     ap_hook_post_config(mem_cache_post_config, NULL, NULL, APR_HOOK_MIDDLE);
     /* cache initializer */
     /* cache_hook_init(cache_mem_init, NULL, NULL, APR_HOOK_MIDDLE);  */
+    /*
     cache_hook_create_entity(create_entity, NULL, NULL, APR_HOOK_MIDDLE);
     cache_hook_open_entity(open_entity,  NULL, NULL, APR_HOOK_MIDDLE);
     cache_hook_remove_url(remove_url, NULL, NULL, APR_HOOK_MIDDLE);
+    */
+    ap_register_provider(p, CACHE_PROVIDER_GROUP, "mem", "0",
+                         &cache_mem_provider);
+    ap_register_provider(p, CACHE_PROVIDER_GROUP, "fd", "0",
+                         &cache_fd_provider);
 }
 
 module AP_MODULE_DECLARE_DATA mem_cache_module =
Index: modules/filters/mod_deflate.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/filters/mod_deflate.c,v
retrieving revision 1.1.1.1
retrieving revision 1.6
diff -u -u -r1.1.1.1 -r1.6
--- modules/filters/mod_deflate.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/filters/mod_deflate.c	2 Dec 2004 19:27:30 -0000	1.6
@@ -286,6 +286,11 @@
     deflate_filter_config *c = ap_get_module_config(r->server->module_config,
                                                     &deflate_module);
 
+    /* Do nothing if asked to filter nothing. */
+    if (APR_BRIGADE_EMPTY(bb)) {
+        return APR_SUCCESS;
+    }
+
     /* If we don't have a context, we need to ensure that it is okay to send
      * the deflated content.  If we have a context, that means we've done
      * this before and we liked it.
@@ -294,10 +299,10 @@
      */
     if (!ctx) {
         char *buf, *token;
-        const char *encoding, *accepts;
+        const char *encoding;
 
         /* only work on main request/no subrequests */
-        if (r->main) {
+        if (!ap_is_initial_req(r)) {
             ap_remove_output_filter(f);
             return ap_pass_brigade(f->next, bb);
         }
@@ -325,7 +330,8 @@
         }
 
         /* Let's see what our current Content-Encoding is.
-         * If gzip is present, don't gzip again.  (We could, but let's not.)
+         * If it's already encoded, don't compress again.
+         * (We could, but let's not.)
          */
         encoding = apr_table_get(r->headers_out, "Content-Encoding");
         if (encoding) {
@@ -350,14 +356,20 @@
             const char *tmp = encoding;
 
             token = ap_get_token(r->pool, &tmp, 0);
-            while (token && token[0]) {
-                if (!strcasecmp(token, "gzip")) {
+            while (token && *token) {
+                /* stolen from mod_negotiation: */
+                if (strcmp(token, "identity") && strcmp(token, "7bit") &&
+                    strcmp(token, "8bit") && strcmp(token, "binary")) {
+
                     ap_remove_output_filter(f);
                     return ap_pass_brigade(f->next, bb);			
                 }
+
                 /* Otherwise, skip token */
-                tmp++;
-                token = ap_get_token(r->pool, &tmp, 0);
+                if (*tmp) {
+                    ++tmp;
+                }
+                token = (*tmp) ? ap_get_token(r->pool, &tmp, 0) : NULL;
             }
         }
 
@@ -367,22 +379,43 @@
          */
         apr_table_setn(r->headers_out, "Vary", "Accept-Encoding");
 
-        /* if they don't have the line, then they can't play */
-        accepts = apr_table_get(r->headers_in, "Accept-Encoding");
-        if (accepts == NULL) {
-            ap_remove_output_filter(f);
-            return ap_pass_brigade(f->next, bb);
-        }
+        /* force-gzip will just force it out regardless if the browser
+         * can actually do anything with it.
+         */
+        if (!apr_table_get(r->subprocess_env, "force-gzip")) {
+            const char *accepts;
+            /* if they don't have the line, then they can't play */
+            accepts = apr_table_get(r->headers_in, "Accept-Encoding");
+            if (accepts == NULL) {
+                ap_remove_output_filter(f);
+                return ap_pass_brigade(f->next, bb);
+            }
 
-        token = ap_get_token(r->pool, &accepts, 0);
-        while (token && token[0] && strcasecmp(token, "gzip")) {
-            /* skip token */
-            accepts++;
             token = ap_get_token(r->pool, &accepts, 0);
+            while (token && token[0] && strcasecmp(token, "gzip")) {
+                /* skip parameters, XXX: ;q=foo evaluation? */
+                while (*accepts == ';') { 
+                    ++accepts;
+                    token = ap_get_token(r->pool, &accepts, 1);
+                }
+
+                /* retrieve next token */
+                if (*accepts == ',') {
+                    ++accepts;
+                }
+                token = (*accepts) ? ap_get_token(r->pool, &accepts, 0) : NULL;
+            }
+
+            /* No acceptable token found. */
+            if (token == NULL || token[0] == '\0') {
+                ap_remove_output_filter(f);
+                return ap_pass_brigade(f->next, bb);
+            }
         }
 
-        /* No acceptable token found. */
-        if (token == NULL || token[0] == '\0') {
+        /* For a 304 or 204 response there is no entity included in
+         * the response and hence nothing to deflate. */
+        if (r->status == HTTP_NOT_MODIFIED || r->status == HTTP_NO_CONTENT) {
             ap_remove_output_filter(f);
             return ap_pass_brigade(f->next, bb);
         }
@@ -437,13 +470,15 @@
         ctx->stream.avail_out = c->bufferSize;
     }
     
-    APR_BRIGADE_FOREACH(e, bb) {
+    while (!APR_BRIGADE_EMPTY(bb))
+    {
         const char *data;
         apr_bucket *b;
         apr_size_t len;
-
         int done = 0;
 
+        e = APR_BRIGADE_FIRST(bb);
+
         if (APR_BUCKET_IS_EOS(e)) {
             char *buf;
             unsigned int deflate_len;
@@ -529,9 +564,15 @@
 
         if (APR_BUCKET_IS_FLUSH(e)) {
             apr_bucket *bkt;
-            zRC = deflate(&(ctx->stream), Z_SYNC_FLUSH);
-            if (zRC != Z_OK) {
-                return APR_EGENERAL;
+            apr_status_t rv;
+
+            apr_bucket_delete(e);
+
+            if (ctx->stream.avail_in > 0) {
+                zRC = deflate(&(ctx->stream), Z_SYNC_FLUSH);
+                if (zRC != Z_OK) {
+                    return APR_EGENERAL;
+                }
             }
 
             ctx->stream.next_out = ctx->buffer;
@@ -544,7 +585,10 @@
 
             bkt = apr_bucket_flush_create(f->c->bucket_alloc);
             APR_BRIGADE_INSERT_TAIL(ctx->bb, bkt);
-            ap_pass_brigade(f->next, ctx->bb);
+            rv = ap_pass_brigade(f->next, ctx->bb);
+            if (rv != APR_SUCCESS) {
+                return rv;
+            }
             continue;
         }
 
@@ -562,6 +606,8 @@
 
         while (ctx->stream.avail_in != 0) {
             if (ctx->stream.avail_out == 0) {
+                apr_status_t rv;
+
                 ctx->stream.next_out = ctx->buffer;
                 len = c->bufferSize - ctx->stream.avail_out;
 
@@ -569,6 +615,11 @@
                                            NULL, f->c->bucket_alloc);
                 APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
                 ctx->stream.avail_out = c->bufferSize;
+                /* Send what we have right now to the next filter. */
+                rv = ap_pass_brigade(f->next, ctx->bb);
+                if (rv != APR_SUCCESS) {
+                    return rv;
+                }
             }
 
             zRC = deflate(&(ctx->stream), Z_NO_FLUSH);
@@ -576,6 +627,8 @@
             if (zRC != Z_OK)
                 return APR_EGENERAL;
         }
+
+        apr_bucket_delete(e);
     }
 
     apr_brigade_cleanup(bb);
@@ -610,7 +663,7 @@
         apr_size_t len;
 
         /* only work on main request/no subrequests */
-        if (r->main) {
+        if (!ap_is_initial_req(r)) {
             ap_remove_input_filter(f);
             return ap_get_brigade(f->next, bb, mode, block, readbytes);
         }
Index: modules/filters/mod_ext_filter.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/filters/mod_ext_filter.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/filters/mod_ext_filter.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/filters/mod_ext_filter.c	28 Feb 2006 19:22:27 -0000	1.2
@@ -75,6 +75,7 @@
 #include "apr_poll.h"
 #define APR_WANT_STRFUNC
 #include "apr_want.h"
+#include "apr_thread_mutex.h"
 
 typedef struct ef_server_t {
     apr_pool_t *p;
@@ -124,6 +125,10 @@
 
 #define ERRFN_USERDATA_KEY         "EXTFILTCHILDERRFN"
 
+#ifdef APR_HAS_THREADS
+static apr_thread_mutex_t *pipe_inherit_mutex;
+#endif
+
 static void *create_ef_dir_conf(apr_pool_t *p, char *dummy)
 {
     ef_dir_t *dc = (ef_dir_t *)apr_pcalloc(p, sizeof(ef_dir_t));
@@ -385,9 +390,20 @@
     return OK;
 }
 
+static void ef_child_init(apr_pool_t *p, server_rec *s)
+{
+#if APR_HAS_THREADS
+    apr_status_t rv;
+
+    rv = apr_thread_mutex_create(&pipe_inherit_mutex, APR_THREAD_MUTEX_DEFAULT, p);
+    ap_assert(rv == APR_SUCCESS);
+#endif
+}
+
 static void register_hooks(apr_pool_t *p)
 {
     ap_hook_post_config(ef_init, NULL, NULL, APR_HOOK_MIDDLE);
+    ap_hook_child_init(ef_child_init, NULL, NULL, APR_HOOK_MIDDLE);
 }
 
 static apr_status_t set_resource_limits(request_rec *r, 
@@ -449,6 +465,19 @@
     rc = apr_procattr_create(&ctx->procattr, ctx->p);
     ap_assert(rc == APR_SUCCESS);
 
+    /* hold a mutex between the time we create pipes in 
+     * apr_procattr_io_set() and when we get a child cleanup 
+     * registered...  otherwise, children created by other threads
+     * running this code can inherit pipes, and if child a's input
+     * pipe is inherited by another child, child a won't terminate
+     * properly when the filter closes the handle because another
+     * process will still have the handle open
+     */
+#if APR_HAS_THREADS
+    rc = apr_thread_mutex_lock(pipe_inherit_mutex);
+    ap_assert(rc == APR_SUCCESS);
+#endif
+
     rc = apr_procattr_io_set(ctx->procattr,
                             APR_CHILD_BLOCK,
                             APR_CHILD_BLOCK,
@@ -498,6 +527,9 @@
                             ctx->procattr, 
                             ctx->p);
     if (rc != APR_SUCCESS) {
+#ifdef APR_HAS_THREADS
+        apr_thread_mutex_unlock(pipe_inherit_mutex);
+#endif
         ap_log_rerror(APLOG_MARK, APLOG_ERR, rc, f->r,
                       "couldn't create child process to run `%s'",
                       ctx->filter->command);
@@ -510,11 +542,20 @@
      * other processes created by httpd.  Otherwise, when we close our
      * handle, the child won't see EOF because another handle will still
      * be open.
+     * Other processes shouldn't see the other handles either.
      */
 
     apr_pool_cleanup_register(ctx->p, ctx->proc->in, 
                          apr_pool_cleanup_null, /* other mechanism */
                          ef_close_file);
+    apr_pool_cleanup_register(ctx->p, ctx->proc->out,
+                              apr_pool_cleanup_null, ef_close_file);
+    apr_pool_cleanup_register(ctx->p, ctx->proc->err,
+                              apr_pool_cleanup_null, ef_close_file);
+
+#if APR_HAS_THREADS
+    apr_thread_mutex_unlock(pipe_inherit_mutex);
+#endif
 
 #if APR_FILES_AS_SOCKETS
     {
@@ -792,6 +833,9 @@
         if (len > 0 &&
             (rv = pass_data_to_filter(f, data, (apr_size_t)len)) 
                 != APR_SUCCESS) {
+            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r,
+                          "pass_data_to_filter for process %" APR_PID_T_FMT,
+                          ctx->proc->pid);
             return rv;
         }
     }
@@ -810,6 +854,13 @@
                           "apr_file_close(child input)");
             return rv;
         }
+
+        if (dc->debug >= DBGLVL_GORY) {
+            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, rv, r,
+                          "server closed input to script %" APR_PID_T_FMT,
+                           ctx->proc->pid);
+        }
+
         /* since we've seen eos and closed the child's stdin, set the proper pipe 
          * timeout; we don't care if we don't return from apr_file_read() for a while... 
          */
Index: modules/filters/mod_include.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/filters/mod_include.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- modules/filters/mod_include.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/filters/mod_include.c	29 Dec 2005 18:41:55 -0000	1.4
@@ -1,7 +1,7 @@
 /* ====================================================================
  * The Apache Software License, Version 1.1
  *
- * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
+ * Copyright (c) 2000-2004 The Apache Software Foundation.  All rights
  * reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -73,6 +73,7 @@
 #include "apr_optional.h"
 
 #define APR_WANT_STRFUNC
+#define APR_WANT_MEMFUNC
 #include "apr_want.h"
 
 #define CORE_PRIVATE
@@ -89,6 +90,8 @@
 #include "http_main.h"
 #include "util_script.h"
 #include "http_core.h"
+
+#define MOD_INCLUDE_REDESIGN
 #include "mod_include.h"
 #include "util_ebcdic.h"
 
@@ -126,6 +129,58 @@
     int  undefinedEchoLen;
 } include_server_config;
 
+/* main parser states */
+typedef enum {
+    PARSE_PRE_HEAD,
+    PARSE_HEAD,
+    PARSE_DIRECTIVE,
+    PARSE_DIRECTIVE_POSTNAME,
+    PARSE_DIRECTIVE_TAIL,
+    PARSE_DIRECTIVE_POSTTAIL,
+    PARSE_PRE_ARG,
+    PARSE_ARG,
+    PARSE_ARG_NAME,
+    PARSE_ARG_POSTNAME,
+    PARSE_ARG_EQ,
+    PARSE_ARG_PREVAL,
+    PARSE_ARG_VAL,
+    PARSE_ARG_VAL_ESC,
+    PARSE_ARG_POSTVAL,
+    PARSE_TAIL,
+    PARSE_TAIL_SEQ,
+    PARSE_EXECUTE
+} parse_state_t;
+
+typedef struct ssi_arg_item {
+    struct ssi_arg_item *next;
+    char                *name;
+    apr_size_t           name_len;
+    char                *value;
+    apr_size_t           value_len;
+} ssi_arg_item_t;
+
+typedef struct {
+    parse_state_t state;
+    int           seen_eos;
+    int           error;
+    char          quote;         /* quote character value (or \0) */
+
+    apr_bucket_brigade *tmp_bb;
+
+    apr_size_t    end_seq_len;
+    char         *directive;     /* name of the current directive */
+
+    unsigned        argc;        /* argument counter (of the current
+                                  * directive)
+                                  */
+    ssi_arg_item_t *argv;        /* all arguments */
+    ssi_arg_item_t *current_arg; /* currently parsed argument */
+    request_rec    *r;
+    include_ctx_t  *ctx;         /* public part of the context structure */
+
+    apr_pool_t     *dpool;
+} ssi_ctx_t;
+
 #ifdef XBITHACK
 #define DEFAULT_XBITHACK xbithack_full
 #else
@@ -134,6 +189,11 @@
 
 #define BYTE_COUNT_THRESHOLD AP_MIN_BYTES_TO_WRITE
 
+#define SSI_CREATE_ERROR_BUCKET(ctx, f, bb) APR_BRIGADE_INSERT_TAIL((bb),   \
+    apr_bucket_pool_create(apr_pstrdup((ctx)->pool, (ctx)->error_str),  \
+                           strlen((ctx)->error_str), (ctx)->pool,       \
+                           (f)->c->bucket_alloc))
+
 /* ------------------------ Environment function -------------------------- */
 
 /* Sentinel value to store in subprocess_env for items that
@@ -155,7 +215,7 @@
         apr_table_setn(e, "DOCUMENT_PATH_INFO", r->path_info);
     }
     apr_table_setn(e, "USER_NAME", LAZY_VALUE);
-    if ((t = strrchr(r->filename, '/'))) {
+    if (r->filename && (t = strrchr(r->filename, '/'))) {
         apr_table_setn(e, "DOCUMENT_NAME", ++t);
     }
     else {
@@ -316,461 +376,6 @@
     return hl;
 }
 
-/* We've now found a start sequence tag... */
-static apr_bucket* found_start_sequence(apr_bucket *dptr,
-                                        include_ctx_t *ctx, 
-                                        apr_size_t tagStart,
-                                        apr_size_t len)
-{
-    /* We want to split the bucket at the '<'. */
-    ctx->state = PARSE_DIRECTIVE;
-    ctx->tag_length = 0;
-    ctx->parse_pos = 0;
-
-    /* If tagStart indexes the end of the bucket, then tag_start_bucket
-     * should be the next bucket
-     */
-    if (tagStart < len) {
-        ctx->tag_start_bucket = dptr;
-        ctx->tag_start_index = tagStart;
-    }
-    else {
-        ctx->tag_start_bucket = APR_BUCKET_NEXT(dptr);
-        ctx->tag_start_index = 0;
-    }
-
-    if (ctx->head_start_index > 0) {
-        apr_bucket *tmp_bkt;
-
-        /* Split the bucket with the start of the tag in it */
-        apr_bucket_split(ctx->head_start_bucket, ctx->head_start_index);
-        tmp_bkt = APR_BUCKET_NEXT(ctx->head_start_bucket);
-        /* If it was a one bucket match */
-        if ((tagStart < len) && (dptr == ctx->head_start_bucket)) {
-            ctx->tag_start_bucket = tmp_bkt;
-            ctx->tag_start_index = tagStart - ctx->head_start_index;
-        }
-        ctx->head_start_bucket = tmp_bkt;
-        ctx->head_start_index = 0;
-    }
-    return ctx->head_start_bucket;
-}
-
-/* This function returns either a pointer to the split bucket containing the
- * first byte of the BEGINNING_SEQUENCE (after finding a complete match) or it
- * returns NULL if no match found.
- */
-static apr_bucket *find_start_sequence(apr_bucket *dptr, include_ctx_t *ctx,
-                                       apr_bucket_brigade *bb, int *do_cleanup)
-{
-    apr_size_t len;
-    const char *c;
-    const char *buf;
-    const char *str = ctx->start_seq ;
-    apr_size_t slen = ctx->start_seq_len;
-    apr_size_t pos;
-
-    *do_cleanup = 0;
-
-    do {
-        apr_status_t rv = 0;
-        int read_done = 0;
-
-        if (APR_BUCKET_IS_EOS(dptr)) {
-            break;
-        }
-
-#if 0
-        /* XXX the bucket flush support is commented out for now
-         * because it was causing a segfault */
-        if (APR_BUCKET_IS_FLUSH(dptr)) {
-            apr_bucket *old = dptr; 
-            dptr = APR_BUCKET_NEXT(old);
-            APR_BUCKET_REMOVE(old);
-            ctx->output_now = 1;
-            ctx->output_flush = 1;
-        }
-        else
-#endif /* 0 */
-        if (ctx->bytes_parsed >= BYTE_COUNT_THRESHOLD) {
-            ctx->output_now = 1;
-        }
-        else if (ctx->bytes_parsed > 0) {
-            rv = apr_bucket_read(dptr, &buf, &len, APR_NONBLOCK_READ);
-            read_done = 1;
-            if (APR_STATUS_IS_EAGAIN(rv)) {
-                ctx->output_now = 1;
-            }
-        }
-
-        if (ctx->output_now) {
-            apr_bucket *start_bucket;
-            if (ctx->head_start_index > 0) {
-                start_bucket = ctx->head_start_bucket;
-                apr_bucket_split(start_bucket, ctx->head_start_index);
-                start_bucket = APR_BUCKET_NEXT(start_bucket);
-                ctx->head_start_index = 0;
-                ctx->head_start_bucket = start_bucket;
-                ctx->parse_pos = 0;
-                ctx->state = PRE_HEAD;
-            }
-            else {
-                start_bucket = dptr;
-            }
-            return start_bucket;
-        }
-
-        if (!read_done) {
-            rv = apr_bucket_read(dptr, &buf, &len, APR_BLOCK_READ);
-        }
-        if (!APR_STATUS_IS_SUCCESS(rv)) {
-            ctx->status = rv;
-            return NULL;
-        }
-
-        if (len == 0) { /* end of pipe? */
-            break;
-        }
-
-        /* Set our buffer to use. */
-        c = buf;
-
-        /* The last bucket had a left over partial match that we need to
-         * complete. 
-         */
-        if (ctx->state == PARSE_HEAD)
-        {
-            apr_size_t tmpLen;
-            tmpLen = (len < (slen - 1)) ? len : (slen - 1);
-
-            while (c < buf + tmpLen && *c == str[ctx->parse_pos])
-            {
-                c++; 
-                ctx->parse_pos++;
-            }
-
-            if (str[ctx->parse_pos] == '\0')
-            {
-                ctx->bytes_parsed += c - buf;
-                return found_start_sequence(dptr, ctx, c - buf, len);
-            }
-            else if (c == buf + tmpLen) {
-                dptr = APR_BUCKET_NEXT(dptr);
-                continue;
-            }
-
-            /* False alarm... 
-             */
-            APR_BRIGADE_PREPEND(bb, ctx->ssi_tag_brigade);
-
-            /* We know we are at the beginning of this bucket so
-             *   we can just prepend the saved bytes from the
-             *   ssi_tag_brigade (which empties the ssi_tag_brigade)
-             *   and continue processing.
-             * We do not need to set do_cleanup beacuse the
-             *   prepend takes care of that.
-             */
-            ctx->state = PRE_HEAD;
-            ctx->head_start_bucket = NULL;
-            ctx->head_start_index = 0;
-        }
-
-        if (len)
-        {
-            pos = bndm(str, slen, c, len, ctx->start_seq_pat);
-            if (pos != len)
-            {
-                ctx->head_start_bucket = dptr;
-                ctx->head_start_index = pos;
-                ctx->bytes_parsed += pos + slen;
-                return found_start_sequence(dptr, ctx, pos + slen, len);
-            }
-        }
-        
-        /* Consider the case where we have <!-- at the end of the bucket. */
-        if (len > slen) {
-            ctx->bytes_parsed += (len - slen);
-            c = buf + len - slen;
-        }
-        else {
-            c = buf;
-        }
-        ctx->parse_pos = 0;
-
-        while (c < buf + len)
-        {
-            if (*c == str[ctx->parse_pos]) {
-                if (ctx->state == PRE_HEAD) {
-                    ctx->state = PARSE_HEAD;
-                    ctx->head_start_bucket = dptr;
-                    ctx->head_start_index = c - buf;
-                }
-                ctx->parse_pos++;
-                c++;
-                ctx->bytes_parsed++;
-            }
-            else if (ctx->parse_pos != 0) 
-            {
-                /* DO NOT INCREMENT c IN THIS BLOCK!
-                 * Don't increment bytes_parsed either.
-                 * This block is just to reset the indexes and
-                 *   pointers related to parsing the tag start_sequence.
-                 * The value c needs to be checked again to handle
-                 *   the case where we find "<<!--#". We are now
-                 *   looking at the second "<" and need to restart
-                 *   the start_sequence checking from parse_pos = 0.
-                 * do_cleanup causes the stored bytes in ssi_tag_brigade
-                 *   to be forwarded on and cleaned up. We may not be
-                 *   able to just prepend the ssi_tag_brigade because
-                 *   we may have advanced too far before we noticed this
-                 *   case, so just flag it and clean it up later.
-                 */
-                *do_cleanup = 1;
-                ctx->parse_pos = 0;
-                ctx->state = PRE_HEAD;
-                ctx->head_start_bucket = NULL;
-                ctx->head_start_index = 0;
-            }
-            else {
-               c++;
-               ctx->bytes_parsed++;
-            }
-        }
-        dptr = APR_BUCKET_NEXT(dptr);
-    } while (dptr != APR_BRIGADE_SENTINEL(bb));
-          
-  
-    return NULL;
-}
-
-static apr_bucket *find_end_sequence(apr_bucket *dptr, include_ctx_t *ctx, 
-                                     apr_bucket_brigade *bb)
-{
-    apr_size_t len;
-    const char *c;
-    const char *buf;
-    const char *str = ctx->end_seq;
-    const char *start;
-
-    do {
-        apr_status_t rv = 0;
-        int read_done = 0;
-
-        if (APR_BUCKET_IS_EOS(dptr)) {
-            break;
-        }
-#if 0
-        /* XXX the bucket flush support is commented out for now
-         * because it was causing a segfault */
-        if (APR_BUCKET_IS_FLUSH(dptr)) {
-            apr_bucket *old = dptr; 
-            dptr = APR_BUCKET_NEXT(old);
-            APR_BUCKET_REMOVE(old);
-            ctx->output_now = 1;
-            ctx->output_flush = 1;
-        }
-        else
-#endif /* 0 */
-        if (ctx->bytes_parsed >= BYTE_COUNT_THRESHOLD) {
-            ctx->output_now = 1;
-        }
-        else if (ctx->bytes_parsed > 0) {
-            rv = apr_bucket_read(dptr, &buf, &len, APR_NONBLOCK_READ);
-            read_done = 1;
-            if (APR_STATUS_IS_EAGAIN(rv)) {
-                ctx->output_now = 1;
-            }
-        }
-
-        if (ctx->output_now) {
-            if (ctx->state == PARSE_DIRECTIVE) {
-                /* gonna start over parsing the directive next time through */
-                ctx->directive_length = 0;
-                ctx->tag_length       = 0;
-            }
-            return dptr;
-        }
-
-        if (!read_done) {
-            rv = apr_bucket_read(dptr, &buf, &len, APR_BLOCK_READ);
-        }
-        if (!APR_STATUS_IS_SUCCESS(rv)) {
-            ctx->status = rv;
-            return NULL;
-        }
-
-        if (len == 0) { /* end of pipe? */
-            break;
-        }
-        if (dptr == ctx->tag_start_bucket) {
-            c = buf + ctx->tag_start_index;
-        }
-        else {
-            c = buf;
-        }
-        start = c;
-        while (c < buf + len) {
-            if (*c == str[ctx->parse_pos]) {
-                if (ctx->state != PARSE_TAIL) {
-                    ctx->state             = PARSE_TAIL;
-                    ctx->tail_start_bucket = dptr;
-                    ctx->tail_start_index  = c - buf;
-                }
-                ctx->parse_pos++;
-                if (str[ctx->parse_pos] == '\0') {
-                        apr_bucket *tmp_buck = dptr;
-
-                        /* We want to split the bucket at the '>'. The
-                         * end of the END_SEQUENCE is in the current bucket.
-                         * The beginning might be in a previous bucket.
-                         */
-                        c++;
-                        ctx->bytes_parsed += (c - start);
-                        ctx->state = PARSED;
-                        apr_bucket_split(dptr, c - buf);
-                        tmp_buck = APR_BUCKET_NEXT(dptr);
-                        return (tmp_buck);
-                    }           
-            }
-            else {
-                if (ctx->state == PARSE_DIRECTIVE) {
-                    if (ctx->tag_length == 0) {
-                        if (!apr_isspace(*c)) {
-                            const char *tmp = c;
-                            ctx->tag_start_bucket = dptr;
-                            ctx->tag_start_index  = c - buf;
-                            do {
-                                c++;
-                            } while ((c < buf + len) && !apr_isspace(*c) &&
-                                     *c != *str);
-                            ctx->tag_length = ctx->directive_length = c - tmp;
-                            continue;
-                        }
-                    }
-                    else {
-                        if (!apr_isspace(*c)) {
-                            ctx->directive_length++;
-                        }
-                        else {
-                            ctx->state = PARSE_TAG;
-                        }
-                        ctx->tag_length++;
-                    }
-                }
-                else if (ctx->state == PARSE_TAG) {
-                    const char *tmp = c;
-                    do {
-                        c++;
-                    } while ((c < buf + len) && (*c != *str));
-                    ctx->tag_length += (c - tmp);
-                    continue;
-                }
-                else {
-                    if (ctx->parse_pos != 0) {
-                        /* The reason for this, is that we need to make sure 
-                         * that we catch cases like --->.  This makes the 
-                         * second check after the original check fails.
-                         * If parse_pos was already 0 then we already checked 
-                         * this.
-                         */
-                         ctx->tag_length += ctx->parse_pos;
-
-                         if (*c == str[0]) {
-                             ctx->state = PARSE_TAIL;
-                             ctx->tail_start_bucket = dptr;
-                             ctx->tail_start_index = c - buf;
-                             ctx->parse_pos = 1;
-                         }
-                         else {
-                             ctx->tag_length++;
-                             if (ctx->tag_length > ctx->directive_length) {
-                                 ctx->state = PARSE_TAG;
-                             }
-                             else {
-                                 ctx->state = PARSE_DIRECTIVE;
-                                 ctx->directive_length += ctx->parse_pos;
-                             }
-                             ctx->tail_start_bucket = NULL;
-                             ctx->tail_start_index = 0;
-                             ctx->parse_pos = 0;
-                         }
-                    }
-                }
-            }
-            c++;
-        }
-        ctx->bytes_parsed += (c - start);
-        dptr = APR_BUCKET_NEXT(dptr);
-    } while (dptr != APR_BRIGADE_SENTINEL(bb));
-    return NULL;
-}
-
-/* This function culls through the buckets that have been set aside in the 
- * ssi_tag_brigade and copies just the directive part of the SSI tag (none
- * of the start and end delimiter bytes are copied).
- */
-static apr_status_t get_combined_directive (include_ctx_t *ctx,
-                                            request_rec *r,
-                                            apr_bucket_brigade *bb,
-                                            char *tmp_buf, 
-                                            apr_size_t tmp_buf_size)
-{
-    int        done = 0;
-    apr_bucket *dptr;
-    const char *tmp_from;
-    apr_size_t tmp_from_len;
-
-    /* If the tag length is longer than the tmp buffer, allocate space. */
-    if (ctx->tag_length > tmp_buf_size-1) {
-        if ((ctx->combined_tag = apr_pcalloc(r->pool, 
-             ctx->tag_length + 1)) == NULL) {
-            return (APR_ENOMEM);
-        }
-    }     /* Else, just use the temp buffer. */
-    else {
-        ctx->combined_tag = tmp_buf;
-    }
-
-    /* Prime the pump. Start at the beginning of the tag... */
-    dptr = ctx->tag_start_bucket;
-    /* Read the bucket... */
-    apr_bucket_read (dptr, &tmp_from, &tmp_from_len, 0);
-
-    /* Adjust the pointer to start at the tag within the bucket... */
-    if (dptr == ctx->tail_start_bucket) {
-        tmp_from_len -= (tmp_from_len - ctx->tail_start_index);
-    }
-    tmp_from          = &tmp_from[ctx->tag_start_index];
-    tmp_from_len     -= ctx->tag_start_index;
-    ctx->curr_tag_pos = ctx->combined_tag;
-
-    /* Loop through the buckets from the tag_start_bucket until before
-     * the tail_start_bucket copying the contents into the buffer.
-     */
-    do {
-        memcpy (ctx->curr_tag_pos, tmp_from, tmp_from_len);
-        ctx->curr_tag_pos += tmp_from_len;
-
-        if (dptr == ctx->tail_start_bucket) {
-            done = 1;
-        }
-        else {
-            dptr = APR_BUCKET_NEXT (dptr);
-            apr_bucket_read (dptr, &tmp_from, &tmp_from_len, 0);
-            /* Adjust the count to stop at the beginning of the tail. */
-            if (dptr == ctx->tail_start_bucket) {
-                tmp_from_len -= (tmp_from_len - ctx->tail_start_index);
-            }
-        }
-    } while ((!done) &&
-             (ctx->curr_tag_pos < ctx->combined_tag + ctx->tag_length));
-
-    ctx->combined_tag[ctx->tag_length] = '\0';
-    ctx->curr_tag_pos = ctx->combined_tag;
-
-    return (APR_SUCCESS);
-}
-
 /*
  * decodes a string containing html entities or numeric character references.
  * 's' is overwritten with the decoded string.
@@ -888,106 +493,34 @@
 static void ap_ssi_get_tag_and_value(include_ctx_t *ctx, char **tag,
                                      char **tag_val, int dodecode)
 {
-    char *c = ctx->curr_tag_pos;
-    int   shift_val = 0; 
-    char  term = '\0';
-
     *tag_val = NULL;
-    if (ctx->curr_tag_pos > ctx->combined_tag + ctx->tag_length) {
+    if (ctx->curr_tag_pos >= ctx->combined_tag + ctx->tag_length) {
         *tag = NULL;
         return;
     }
-    SKIP_TAG_WHITESPACE(c);
-    *tag = c;             /* First non-whitespace character (could be NULL). */
-
-    while (apr_islower(*c)) {
-        c++;  /* Optimization for the common case where the tag */
-    }         /* is already lowercase */
 
-    while ((*c != '=') && (!apr_isspace(*c)) && (*c != '\0')) {
-        *c = apr_tolower(*c);    /* find end of tag, lowercasing as we go... */
-        c++;
+    *tag = ctx->curr_tag_pos;
+    if (!**tag) {
+        *tag = NULL;
+        /* finitio */
+        ctx->curr_tag_pos = ctx->combined_tag + ctx->tag_length;
+        return;
     }
 
-    if ((*c == '\0') || (**tag == '=')) {
-        if ((**tag == '\0') || (**tag == '=')) {
-            *tag = NULL;
-        }
-        ctx->curr_tag_pos = c;
-        return;                      /* We have found the end of the buffer. */
-    }                       /* We might have a tag, but definitely no value. */
-
-    if (*c == '=') {
-        *c++ = '\0'; /* Overwrite the '=' with a terminating byte after tag. */
-    }
-    else {                               /* Try skipping WS to find the '='. */
-        *c++ = '\0';                                 /* Terminate the tag... */
-        SKIP_TAG_WHITESPACE(c);
-        
-        /* There needs to be an equal sign if there's a value. */
-        if (*c != '=') {
-            ctx->curr_tag_pos = c;
-            return; /* There apparently was no value. */
-        }
-        else {
-            c++; /* Skip the equals sign. */
-        }
+    *tag_val = ap_strchr(*tag, '=');
+    if (!*tag_val) {
+        ctx->curr_tag_pos = ctx->combined_tag + ctx->tag_length;
+        return;
     }
 
-    SKIP_TAG_WHITESPACE(c);
-    if (*c == '"' || *c == '\'' || *c == '`') { 
-        /* Allow quoted values for space inclusion. 
-         * NOTE: This does not pass the quotes on return.
-         */
-        term = *c++;
-    }
-    
-    *tag_val = c;
-    if (!term) {
-        while (!apr_isspace(*c) && (*c != '\0')) {
-            c++;
-        }
+    /* if it starts with '=' there was no tag name, just a value */
+    if (*tag_val == *tag) {
+        *tag = NULL;
     }
-    else {
-        while ((*c != term) && (*c != '\0') && (*c != '\\')) {
-            /* Quickly scan past the string until we reach
-             * either the end of the tag or a backslash.  If
-             * we find a backslash, we have to switch to the
-             * more complicated parser loop that follows.
-             */
-            c++;
-        }
-        if (*c == '\\') {
-            do {
-                /* Accept \" (or ' or `) as valid quotation of string. 
-                 */
-                if (*c == '\\') {  
-                    /* Overwrite the "\" during the embedded 
-                     * escape sequence of '"'. "\'" or '`'. 
-                     * Shift bytes from here to next delimiter.     
-                     */
-                    c++;
-                    if (*c == term) {
-                        shift_val++;
-                    }
-                    if (shift_val > 0) {
-                        *(c-shift_val) = *c;
-                    }
-                    if (*c == '\0') {
-                        break;
-                    }
-                }
 
-                c++;
-                if (shift_val > 0) {
-                    *(c-shift_val) = *c;
-                }
-            } while ((*c != term) && (*c != '\0'));
-        }
-    }
-    
-    *(c-shift_val) = '\0'; /* Overwrites delimiter (term or WS) with NULL. */
-    ctx->curr_tag_pos = ++c;
+    *(*tag_val)++ = '\0';
+    ctx->curr_tag_pos = *tag_val + strlen(*tag_val) + 1; /* skip \0 byte */
+
     if (dodecode) {
         decodehtml(*tag_val);
     }
@@ -1126,7 +659,7 @@
                     char *new_out;
                     do {
                         new_out_size *= 2;
-                    } while (new_out_size < current_length + l);
+                    } while (new_out_size < current_length + l + 1); /* +1 for NUL */
                     if (new_out_size > length) {
                         new_out_size = length;
                     }
@@ -1352,6 +885,7 @@
                             "unknown parameter \"%s\" to tag include in %s",
                             tag, r->filename);
                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
+                return 1;
             }
         }
     }
@@ -1430,6 +964,7 @@
                            "tag echo in %s", tag_val, r->filename);
                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, 
                                         *inserted_head);
+                    return 1;
                 }
             }
             else {
@@ -1437,6 +972,7 @@
                             "unknown parameter \"%s\" in tag echo of %s",
                             tag, r->filename);
                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
+                return 1;
             }
 
         }
@@ -1512,6 +1048,7 @@
                               "unknown parameter \"%s\" to tag config in %s",
                               tag, r->filename);
                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
+                return 1;
             }
         }
     }
@@ -1661,6 +1198,7 @@
                 else {
                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, 
                                         *inserted_head);
+                    return 1;
                 }
             }
         }
@@ -1710,6 +1248,7 @@
                 else {
                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, 
                                         *inserted_head);
+                    return 1;
                 }
             }
         }
@@ -1839,7 +1378,7 @@
     token->value = apr_palloc(r->pool, strlen(string) + 2); /* 2 for ch plus
                                                                trailing null */
     if (!qs) {
-        token->value[next++] = ch;
+        --string;
     }
 
     /* 
@@ -2069,6 +1608,7 @@
             }
             else {
                 new->left = current->right;
+                new->left->parent = new;
                 current->right = new;
                 new->parent = current;
             }
@@ -2175,6 +1715,7 @@
             }
             else {
                 new->left = current->right;
+                new->left->parent = new;
                 current->right = new;
                 new->parent = current;
             }
@@ -2638,6 +2179,7 @@
                             "unknown parameter \"%s\" to tag if in %s", tag, 
                             r->filename);
                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
+                return 1;
             }
 
         }
@@ -2674,7 +2216,7 @@
                                   r->filename);
                     CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, 
                                         *inserted_head);
-                    return (1);
+                    return 1;
                 }
                 expr_ret = parse_expr(r, ctx, expr, &was_error, 
                                       &was_unmatched, debug_buf);
@@ -2721,6 +2263,7 @@
                                "unknown parameter \"%s\" to tag if in %s", tag, 
                                r->filename);
                 CREATE_ERROR_BUCKET(ctx, tmp_buck, head_ptr, *inserted_head);
+                return 1;
             }
         }
     }
@@ -2910,368 +2453,1032 @@
 
 /* -------------------------- The main function --------------------------- */
 
-static apr_status_t send_parsed_content(apr_bucket_brigade **bb, 
-                                        request_rec *r, ap_filter_t *f)
+/*
+ * returns the index position of the first byte of start_seq (or the len of
+ * the buffer as non-match)
+ */
+static apr_size_t find_start_sequence(ssi_ctx_t *ctx, const char *data,
+                                      apr_size_t len)
 {
-    include_ctx_t *ctx = f->ctx;
-    apr_bucket *dptr = APR_BRIGADE_FIRST(*bb);
-    apr_bucket *tmp_dptr;
-    apr_bucket_brigade *tag_and_after;
-    apr_status_t rv = APR_SUCCESS;
+    apr_size_t slen = ctx->ctx->start_seq_len;
+    apr_size_t index;
+    const char *p, *ep;
 
-    if (r->args) {               /* add QUERY stuff to env cause it ain't yet */
-        char *arg_copy = apr_pstrdup(r->pool, r->args);
-
-        apr_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
-        ap_unescape_url(arg_copy);
-        apr_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
-                  ap_escape_shell_cmd(r->pool, arg_copy));
+    if (len < slen) {
+        p = data; /* try partial match at the end of the buffer (below) */
     }
+    else {
+        /* try fast bndm search over the buffer
+         * (hopefully the whole start sequence can be found in this buffer)
+         */
+        index = bndm(ctx->ctx->start_seq, ctx->ctx->start_seq_len, data, len,
+                     ctx->ctx->start_seq_pat);
 
-    while (dptr != APR_BRIGADE_SENTINEL(*bb) && !APR_BUCKET_IS_EOS(dptr)) {
-        /* State to check for the STARTING_SEQUENCE. */
-        if ((ctx->state == PRE_HEAD) || (ctx->state == PARSE_HEAD)) {
-            int do_cleanup = 0;
-            apr_size_t cleanup_bytes = ctx->parse_pos;
-
-            tmp_dptr = find_start_sequence(dptr, ctx, *bb, &do_cleanup);
-            if (!APR_STATUS_IS_SUCCESS(ctx->status)) {
-                return ctx->status;
-            }
-
-            /* The few bytes stored in the ssi_tag_brigade turned out not to
-             * be a tag after all. This can only happen if the starting
-             * tag actually spans brigades. This should be very rare.
+        /* wow, found it. ready. */
+        if (index < len) {
+            ctx->state = PARSE_DIRECTIVE;
+            return index;
+        }
+        else {
+            /* ok, the pattern can't be found as whole in the buffer,
+             * check the end for a partial match
              */
-            if ((do_cleanup) && (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade))) {
-                apr_bucket *tmp_bkt;
+            p = data + len - slen + 1;
+        }
+    }
 
-                tmp_bkt = apr_bucket_immortal_create(ctx->start_seq,
-                                                  cleanup_bytes,
-                                                  r->connection->bucket_alloc);
-                APR_BRIGADE_INSERT_HEAD(*bb, tmp_bkt);
-                apr_brigade_cleanup(ctx->ssi_tag_brigade);
-            }
+    ep = data + len;
+    do {
+        while (p < ep && *p != *ctx->ctx->start_seq) {
+            ++p;
+        }
 
-            /* If I am inside a conditional (if, elif, else) that is false
-             *   then I need to throw away anything contained in it.
-             */
-            if ((!(ctx->flags & FLAG_PRINTING)) && (tmp_dptr != NULL) &&
-                (dptr != APR_BRIGADE_SENTINEL(*bb))) {
-                while ((dptr != APR_BRIGADE_SENTINEL(*bb)) &&
-                       (dptr != tmp_dptr)) {
-                    apr_bucket *free_bucket = dptr;
+        index = p - data;
 
-                    dptr = APR_BUCKET_NEXT (dptr);
-                    apr_bucket_delete(free_bucket);
-                }
-            }
+        /* found a possible start_seq start */
+        if (p < ep) {
+            apr_size_t pos = 1;
 
-            /* Adjust the current bucket position based on what was found... */
-            if ((tmp_dptr != NULL) && (ctx->state == PARSE_DIRECTIVE)) {
-                if (ctx->tag_start_bucket != NULL) {
-                    dptr = ctx->tag_start_bucket;
-                }
-                else {
-                    dptr = APR_BRIGADE_SENTINEL(*bb);
-                }
+            ++p;
+            while (p < ep && *p == ctx->ctx->start_seq[pos]) {
+                ++p;
+                ++pos;
             }
-            else if ((tmp_dptr != NULL) &&
-                     (ctx->output_now ||
-                      (ctx->bytes_parsed >= BYTE_COUNT_THRESHOLD))) {
-                /* Send the large chunk of pre-tag bytes...  */
-                tag_and_after = apr_brigade_split(*bb, tmp_dptr);
-                if (ctx->output_flush) {
-                    APR_BRIGADE_INSERT_TAIL(*bb, apr_bucket_flush_create((*bb)->bucket_alloc));
-                }
 
-                rv = ap_pass_brigade(f->next, *bb);
-                if (rv != APR_SUCCESS) {
-                    return rv;
-                }
-                *bb  = tag_and_after;
-                dptr = tmp_dptr;
-                ctx->output_flush = 0;
-                ctx->bytes_parsed = 0;
-                ctx->output_now = 0;
-            }
-            else if (tmp_dptr == NULL) { 
-                /* There was no possible SSI tag in the
-                 * remainder of this brigade... */
-                dptr = APR_BRIGADE_SENTINEL(*bb);  
+            /* partial match found. Store the info for the next round */
+            if (p == ep) {
+                ctx->state = PARSE_HEAD;
+                ctx->ctx->parse_pos = pos;
+                return index;
             }
         }
 
-        /* State to check for the ENDING_SEQUENCE. */
-        if (((ctx->state == PARSE_DIRECTIVE) ||
-             (ctx->state == PARSE_TAG)       ||
-             (ctx->state == PARSE_TAIL))       &&
-            (dptr != APR_BRIGADE_SENTINEL(*bb))) {
-            tmp_dptr = find_end_sequence(dptr, ctx, *bb);
-            if (!APR_STATUS_IS_SUCCESS(ctx->status)) {
-                return ctx->status;
-            }
+        /* we must try all combinations; consider (e.g.) SSIStartTag "--->"
+         * and a string data of "--.-" and the end of the buffer
+         */
+        p = data + index + 1;
+    } while (p < ep);
 
-            if (tmp_dptr != NULL) {
-                dptr = tmp_dptr;  /* Adjust bucket pos... */
-                
-                /* If some of the tag has already been set aside then set
-                 * aside remainder of tag. Now the full tag is in 
-                 * ssi_tag_brigade.
-                 * If none has yet been set aside, then leave it all where it 
-                 * is.
-                 * In any event after this the entire set of tag buckets will 
-                 * be in one place or another.
-                 */
-                if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
-                    tag_and_after = apr_brigade_split(*bb, dptr);
-                    APR_BRIGADE_CONCAT(ctx->ssi_tag_brigade, *bb);
-                    *bb = tag_and_after;
-                }
-                else if (ctx->output_now ||
-                         (ctx->bytes_parsed >= BYTE_COUNT_THRESHOLD)) {
-                    SPLIT_AND_PASS_PRETAG_BUCKETS(*bb, ctx, f->next, rv);
-                    if (rv != APR_SUCCESS) {
-                        return rv;
-                    }
-                    ctx->output_flush = 0;
-                    ctx->output_now = 0;
-                }
-            }
-            else {
-                /* remainder of this brigade...    */
-                dptr = APR_BRIGADE_SENTINEL(*bb);  
-            }
-        }
+    /* no match */
+    return len;
+}
 
-        /* State to processed the directive... */
-        if (ctx->state == PARSED) {
-            apr_bucket    *content_head = NULL, *tmp_bkt;
-            apr_size_t    tmp_i;
-            char          tmp_buf[TMP_BUF_SIZE];
-            int (*handle_func)(include_ctx_t *, apr_bucket_brigade **,
-                               request_rec *, ap_filter_t *, apr_bucket *,
-                               apr_bucket **);
+/*
+ * returns the first byte *after* the partial (or final) match.
+ *
+ * If we had to trick with the start_seq start, 'release' returns the
+ * number of chars of the start_seq which appeared not to be part of a
+ * full tag and may have to be passed down the filter chain.
+ */
+static apr_size_t find_partial_start_sequence(ssi_ctx_t *ctx,
+                                              const char *data,
+                                              apr_size_t len,
+                                              apr_size_t *release)
+{
+    apr_size_t pos, spos = 0;
+    apr_size_t slen = ctx->ctx->start_seq_len;
+    const char *p, *ep;
+
+    pos = ctx->ctx->parse_pos;
+    ep = data + len;
+    *release = 0;
 
-            /* By now the full tag (all buckets) should either be set aside into
-             *  ssi_tag_brigade or contained within the current bb. All tag
-             *  processing from here on can assume that.
-             */
+    do {
+        p = data;
 
-            /* At this point, everything between ctx->head_start_bucket and
-             * ctx->tail_start_bucket is an SSI
-             * directive, we just have to deal with it now.
-             */
-            if (get_combined_directive(ctx, r, *bb, tmp_buf,
-                                        TMP_BUF_SIZE) != APR_SUCCESS) {
-                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
-                            "mod_include: error copying directive in %s",
-                            r->filename);
-                CREATE_ERROR_BUCKET(ctx, tmp_bkt, dptr, content_head);
+        while (p < ep && pos < slen && *p == ctx->ctx->start_seq[pos]) {
+            ++p;
+            ++pos;
+        }
 
-                /* DO CLEANUP HERE!!!!! */
-                tmp_dptr = ctx->head_start_bucket;
-                if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
-                    apr_brigade_cleanup(ctx->ssi_tag_brigade);
-                }
-                else {
-                    do {
-                        tmp_bkt  = tmp_dptr;
-                        tmp_dptr = APR_BUCKET_NEXT (tmp_dptr);
-                        apr_bucket_delete(tmp_bkt);
-                    } while ((tmp_dptr != dptr) &&
-                             (tmp_dptr != APR_BRIGADE_SENTINEL(*bb)));
+        /* full match */
+        if (pos == slen) {
+            ctx->state = PARSE_DIRECTIVE;
+            return (p - data);
+        }
+
+        /* the whole buffer is a partial match */
+        if (p == ep) {
+            ctx->ctx->parse_pos = pos;
+            return (p - data);
+        }
+
+        /* No match so far, but again:
+         * We must try all combinations, since the start_seq is a random
+         * user supplied string
+         *
+         * So: look if the first char of start_seq appears somewhere within
+         * the current partial match. If it does, try to start a match that
+         * begins with this offset. (This can happen, if a strange
+         * start_seq like "---->" spans buffers)
+         */
+        if (spos < ctx->ctx->parse_pos) {
+            do {
+                ++spos;
+                ++*release;
+                p = ctx->ctx->start_seq + spos;
+                pos = ctx->ctx->parse_pos - spos;
+
+                while (pos && *p != *ctx->ctx->start_seq) {
+                    ++p;
+                    ++spos;
+                    ++*release;
+                    --pos;
                 }
 
-                return APR_SUCCESS;
-            }
+                /* if a matching beginning char was found, try to match the
+                 * remainder of the old buffer.
+                 */
+                if (pos > 1) {
+                    apr_size_t t = 1;
 
-            /* Can't destroy the tag buckets until I'm done processing
-             * because the combined_tag might just be pointing to
-             * the contents of a single bucket!
-             */
+                    ++p;
+                    while (t < pos && *p == ctx->ctx->start_seq[t]) {
+                        ++p;
+                        ++t;
+                    }
 
-            /* Retrieve the handler function to be called for this directive 
-             * from the functions registered in the hash table.
-             * Need to lower case the directive for proper matching. Also need 
-             * to have it NULL terminated for proper hash matching.
-             */
-            for (tmp_i = 0; tmp_i < ctx->directive_length; tmp_i++) {
-                ctx->combined_tag[tmp_i] = 
-                                          apr_tolower(ctx->combined_tag[tmp_i]);
-            }
-            ctx->combined_tag[ctx->directive_length] = '\0';
-            ctx->curr_tag_pos = &ctx->combined_tag[ctx->directive_length+1];
-
-            handle_func = 
-                (include_handler_fn_t *)apr_hash_get(include_hash, 
-                                                     ctx->combined_tag, 
-                                                     ctx->directive_length);
-            if (handle_func != NULL) {
-                rv = (*handle_func)(ctx, bb, r, f, dptr, &content_head);
-                if ((rv != 0) && (rv != 1)) {
-                    return (rv);
+                    if (t == pos) {
+                        /* yeah, another partial match found in the *old*
+                         * buffer, now test the *current* buffer for
+                         * continuing match
+                         */
+                        break;
+                    }
                 }
+            } while (pos > 1);
+
+            if (pos) {
+                continue;
             }
-            else {
-                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
-                              "unknown directive \"%s\" in parsed doc %s",
-                              ctx->combined_tag, r->filename);
-                CREATE_ERROR_BUCKET(ctx, tmp_bkt, dptr, content_head);
-            }
-
-            /* This chunk of code starts at the first bucket in the chain
-             * of tag buckets (assuming that by this point the bucket for
-             * the STARTING_SEQUENCE has been split) and loops through to
-             * the end of the tag buckets freeing them all.
-             *
-             * Remember that some part of this may have been set aside
-             * into the ssi_tag_brigade and the remainder (possibly as
-             * little as one byte) will be in the current brigade.
-             *
-             * The value of dptr should have been set during the
-             * PARSE_TAIL state to the first bucket after the
-             * ENDING_SEQUENCE.
-             *
-             * The value of content_head may have been set during processing
-             * of the directive. If so, the content was inserted in front
-             * of the dptr bucket. The inserted buckets should not be thrown
-             * away here, but they should also not be parsed later.
+        }
+
+        break;
+    } while (1); /* work hard to find a match ;-) */
+
+    /* no match at all, release all (wrongly) matched chars so far */
+    *release = ctx->ctx->parse_pos;
+    ctx->state = PARSE_PRE_HEAD;
+    return 0;
+}
+
+/*
+ * returns the position after the directive
+ */
+static apr_size_t find_directive(ssi_ctx_t *ctx, const char *data,
+                                 apr_size_t len, char ***store,
+                                 apr_size_t **store_len)
+{
+    const char *p = data;
+    const char *ep = data + len;
+    apr_size_t pos;
+
+    switch (ctx->state) {
+    case PARSE_DIRECTIVE:
+        while (p < ep && !apr_isspace(*p)) {
+            /* we have to consider the case of missing space between directive
+             * and end_seq (be somewhat lenient), e.g. <!--#printenv-->
              */
-            if (content_head == NULL) {
-                content_head = dptr;
+            if (*p == *ctx->ctx->end_seq) {
+                ctx->state = PARSE_DIRECTIVE_TAIL;
+                ctx->ctx->parse_pos = 1;
+                ++p;
+                return (p - data);
+            }
+            ++p;
+        }
+
+        if (p < ep) { /* found delimiter whitespace */
+            ctx->state = PARSE_DIRECTIVE_POSTNAME;
+            *store = &ctx->directive;
+            *store_len = &ctx->ctx->directive_length;
+        }
+
+        break;
+
+    case PARSE_DIRECTIVE_TAIL:
+        pos = ctx->ctx->parse_pos;
+
+        while (p < ep && pos < ctx->end_seq_len &&
+               *p == ctx->ctx->end_seq[pos]) {
+            ++p;
+            ++pos;
+        }
+
+        /* full match, we're done */
+        if (pos == ctx->end_seq_len) {
+            ctx->state = PARSE_DIRECTIVE_POSTTAIL;
+            *store = &ctx->directive;
+            *store_len = &ctx->ctx->directive_length;
+            break;
+        }
+
+        /* partial match, the buffer is too small to match fully */
+        if (p == ep) {
+            ctx->ctx->parse_pos = pos;
+            break;
+        }
+
+        /* no match. continue normal parsing */
+        ctx->state = PARSE_DIRECTIVE;
+        return 0;
+
+    case PARSE_DIRECTIVE_POSTTAIL:
+        ctx->state = PARSE_EXECUTE;
+        ctx->ctx->directive_length -= ctx->end_seq_len;
+        /* continue immediately with the next state */
+
+    case PARSE_DIRECTIVE_POSTNAME:
+        if (PARSE_DIRECTIVE_POSTNAME == ctx->state) {
+            ctx->state = PARSE_PRE_ARG;
+        }
+        ctx->argc = 0;
+        ctx->argv = NULL;
+
+        if (!ctx->ctx->directive_length) {
+            ctx->error = 1;
+            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, "missing directive "
+                          "name in parsed document %s", ctx->r->filename);
+        }
+        else {
+            char *sp = ctx->directive;
+            char *sep = ctx->directive + ctx->ctx->directive_length;
+
+            /* normalize directive name */
+            for (; sp < sep; ++sp) {
+                *sp = apr_tolower(*sp);
             }
-            tmp_dptr = ctx->head_start_bucket;
-            if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
-                apr_brigade_cleanup(ctx->ssi_tag_brigade);
+        }
+
+        return 0;
+
+    default:
+        /* get a rid of a gcc warning about unhandled enumerations */
+        break;
+    }
+
+    return (p - data);
+}
+
+/*
+ * find out whether the next token is (a possible) end_seq or an argument
+ */
+static apr_size_t find_arg_or_tail(ssi_ctx_t *ctx, const char *data,
+                                   apr_size_t len)
+{
+    const char *p = data;
+    const char *ep = data + len;
+
+    /* skip leading WS */
+    while (p < ep && apr_isspace(*p)) {
+        ++p;
+    }
+
+    /* buffer doesn't consist of whitespaces only */
+    if (p < ep) {
+        ctx->state = (*p == *ctx->ctx->end_seq) ? PARSE_TAIL : PARSE_ARG;
+    }
+
+    return (p - data);
+}
+
+/*
+ * test the stream for end_seq. If it doesn't match at all, it must be an
+ * argument
+ */
+static apr_size_t find_tail(ssi_ctx_t *ctx, const char *data,
+                            apr_size_t len)
+{
+    const char *p = data;
+    const char *ep = data + len;
+    apr_size_t pos = ctx->ctx->parse_pos;
+
+    if (PARSE_TAIL == ctx->state) {
+        ctx->state = PARSE_TAIL_SEQ;
+        pos = ctx->ctx->parse_pos = 0;
+    }
+
+    while (p < ep && pos < ctx->end_seq_len && *p == ctx->ctx->end_seq[pos]) {
+        ++p;
+        ++pos;
+    }
+
+    /* bingo, full match */
+    if (pos == ctx->end_seq_len) {
+        ctx->state = PARSE_EXECUTE;
+        return (p - data);
+    }
+
+    /* partial match, the buffer is too small to match fully */
+    if (p == ep) {
+        ctx->ctx->parse_pos = pos;
+        return (p - data);
+    }
+
+    /* no match. It must be an argument string then */
+    ctx->state = PARSE_ARG;
+    return 0;
+}
+
+/*
+ * extract name=value from the buffer
+ * A pcre-pattern could look (similar to):
+ * name\s*(?:=\s*(["'`]?)value\1(?>\s*))?
+ */
+static apr_size_t find_argument(ssi_ctx_t *ctx, const char *data,
+                                apr_size_t len, char ***store,
+                                apr_size_t **store_len)
+{
+    const char *p = data;
+    const char *ep = data + len;
+
+    switch (ctx->state) {
+    case PARSE_ARG:
+        /*
+         * create argument structure and append it to the current list
+         */
+        ctx->current_arg = apr_palloc(ctx->dpool,
+                                      sizeof(*ctx->current_arg));
+        ctx->current_arg->next = NULL;
+
+        ++(ctx->argc);
+        if (!ctx->argv) {
+            ctx->argv = ctx->current_arg;
+        }
+        else {
+            ssi_arg_item_t *newarg = ctx->argv;
+
+            while (newarg->next) {
+                newarg = newarg->next;
             }
-            else {
-                do {
-                    tmp_bkt  = tmp_dptr;
-                    tmp_dptr = APR_BUCKET_NEXT (tmp_dptr);
-                    apr_bucket_delete(tmp_bkt);
-                } while ((tmp_dptr != content_head) &&
-                         (tmp_dptr != APR_BRIGADE_SENTINEL(*bb)));
+            newarg->next = ctx->current_arg;
+        }
+
+        /* check whether it's a valid one. If it begins with a quote, we
+         * can safely assume, someone forgot the name of the argument
+         */
+        switch (*p) {
+        case '"': case '\'': case '`':
+            *store = NULL;
+
+            ctx->state = PARSE_ARG_VAL;
+            ctx->quote = *p++;
+            ctx->current_arg->name = NULL;
+            ctx->current_arg->name_len = 0;
+            ctx->error = 1;
+
+            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, "missing argument "
+                          "name for value to tag %s in %s",
+                          apr_pstrmemdup(ctx->r->pool, ctx->directive,
+                                         ctx->ctx->directive_length),
+                                         ctx->r->filename);
+
+            return (p - data);
+
+        default:
+            ctx->state = PARSE_ARG_NAME;
+        }
+        /* continue immediately with next state */
+
+    case PARSE_ARG_NAME:
+        while (p < ep && !apr_isspace(*p) && *p != '=') {
+            ++p;
+        }
+
+        if (p < ep) {
+            ctx->state = PARSE_ARG_POSTNAME;
+            *store = &ctx->current_arg->name;
+            *store_len = &ctx->current_arg->name_len;
+            return (p - data);
+        }
+        break;
+
+    case PARSE_ARG_POSTNAME:
+        ctx->current_arg->name = apr_pstrmemdup(ctx->dpool,
+                                                ctx->current_arg->name,
+                                                ctx->current_arg->name_len);
+        if (!ctx->current_arg->name_len) {
+            ctx->error = 1;
+            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, ctx->r, "missing argument "
+                          "name for value to tag %s in %s",
+                          apr_pstrmemdup(ctx->r->pool, ctx->directive,
+                                         ctx->ctx->directive_length),
+                                         ctx->r->filename);
+        }
+        else {
+            char *sp = ctx->current_arg->name;
+
+            /* normalize the name */
+            while (*sp) {
+                *sp = apr_tolower(*sp);
+                ++sp;
+            }
+        }
+
+        ctx->state = PARSE_ARG_EQ;
+        /* continue with next state immediately */
+
+    case PARSE_ARG_EQ:
+        *store = NULL;
+
+        while (p < ep && apr_isspace(*p)) {
+            ++p;
+        }
+
+        if (p < ep) {
+            if (*p == '=') {
+                ctx->state = PARSE_ARG_PREVAL;
+                ++p;
             }
-            if (ctx->combined_tag == tmp_buf) {
-                ctx->combined_tag = NULL;
+            else { /* no value */
+                ctx->current_arg->value = NULL;
+                ctx->state = PARSE_PRE_ARG;
             }
 
-            /* Don't reset the flags or the nesting level!!! */
-            ctx->parse_pos         = 0;
-            ctx->head_start_bucket = NULL;
-            ctx->head_start_index  = 0;
-            ctx->tag_start_bucket  = NULL;
-            ctx->tag_start_index   = 0;
-            ctx->tail_start_bucket = NULL;
-            ctx->tail_start_index  = 0;
-            ctx->curr_tag_pos      = NULL;
-            ctx->tag_length        = 0;
-            ctx->directive_length  = 0;
+            return (p - data);
+        }
+        break;
+
+    case PARSE_ARG_PREVAL:
+        *store = NULL;
+
+        while (p < ep && apr_isspace(*p)) {
+            ++p;
+        }
 
-            if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
-                apr_brigade_cleanup(ctx->ssi_tag_brigade);
+        /* buffer doesn't consist of whitespaces only */
+        if (p < ep) {
+            ctx->state = PARSE_ARG_VAL;
+            switch (*p) {
+            case '"': case '\'': case '`':
+                ctx->quote = *p++;
+                break;
+            default:
+                ctx->quote = '\0';
+                break;
             }
 
-            ctx->state     = PRE_HEAD;
+            return (p - data);
         }
-    }
+        break;
 
-    /* We have nothing more to send, stop now. */
-    if (dptr != APR_BRIGADE_SENTINEL(*bb) &&
-        APR_BUCKET_IS_EOS(dptr)) {
-        /* We might have something saved that we never completed, but send
-         * down unparsed.  This allows for <!-- at the end of files to be
-         * sent correctly. */
-        if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
-            APR_BRIGADE_CONCAT(ctx->ssi_tag_brigade, *bb);
-            return ap_pass_brigade(f->next, ctx->ssi_tag_brigade);
+    case PARSE_ARG_VAL_ESC:
+        if (*p == ctx->quote) {
+            ++p;
+        }
+        ctx->state = PARSE_ARG_VAL;
+        /* continue with next state immediately */
+
+    case PARSE_ARG_VAL:
+        for (; p < ep; ++p) {
+            if (ctx->quote && *p == '\\') {
+                ++p;
+                if (p == ep) {
+                    ctx->state = PARSE_ARG_VAL_ESC;
+                    break;
+                }
+
+                if (*p != ctx->quote) {
+                    --p;
+                }
+            }
+            else if (ctx->quote && *p == ctx->quote) {
+                ++p;
+                *store = &ctx->current_arg->value;
+                *store_len = &ctx->current_arg->value_len;
+                ctx->state = PARSE_ARG_POSTVAL;
+                break;
+            }
+            else if (!ctx->quote && apr_isspace(*p)) {
+                ++p;
+                *store = &ctx->current_arg->value;
+                *store_len = &ctx->current_arg->value_len;
+                ctx->state = PARSE_ARG_POSTVAL;
+                break;
+            }
         }
-        return ap_pass_brigade(f->next, *bb);
-    }
 
-    /* If I am in the middle of parsing an SSI tag then I need to set aside
-     *   the pertinent trailing buckets and pass on the initial part of the
-     *   brigade. The pertinent parts of the next brigades will be added to
-     *   these set aside buckets to form the whole tag and will be processed
-     *   once the whole tag has been found.
-     */
-    if (ctx->state == PRE_HEAD) {
-        /* Inside a false conditional (if, elif, else), so toss it all... */
-        if ((dptr != APR_BRIGADE_SENTINEL(*bb)) &&
-            (!(ctx->flags & FLAG_PRINTING))) {
-            apr_bucket *free_bucket;
-            do {
-                free_bucket = dptr;
-                dptr = APR_BUCKET_NEXT (dptr);
-                apr_bucket_delete(free_bucket);
-            } while (dptr != APR_BRIGADE_SENTINEL(*bb));
-        }
-        else { 
-            /* Otherwise pass it along...
-             * No SSI tags in this brigade... */
-            rv = ap_pass_brigade(f->next, *bb);  
-            if (rv != APR_SUCCESS) {
-                return rv;
+        return (p - data);
+
+    case PARSE_ARG_POSTVAL:
+        /*
+         * The value is still the raw input string. Finally clean it up.
+         */
+        --(ctx->current_arg->value_len);
+
+        /* strip quote escaping \ from the string */
+        if (ctx->quote) {
+            apr_size_t shift = 0;
+            char *sp;
+
+            sp = ctx->current_arg->value;
+            ep = ctx->current_arg->value + ctx->current_arg->value_len;
+            while (sp < ep && *sp != '\\') {
+                ++sp;
             }
-            ctx->bytes_parsed = 0;
+            for (; sp < ep; ++sp) {
+                if (*sp == '\\' && sp[1] == ctx->quote) {
+                    ++sp;
+                    ++shift;
+                }
+                if (shift) {
+                    *(sp-shift) = *sp;
+                }
+            }
+
+            ctx->current_arg->value_len -= shift;
         }
+
+        ctx->current_arg->value[ctx->current_arg->value_len] = '\0';
+        ctx->state = PARSE_PRE_ARG;
+
+        return 0;
+
+    default:
+        /* get a rid of a gcc warning about unhandled enumerations */
+        break;
     }
-    else if (ctx->state == PARSED) {         /* Invalid internal condition... */
-        apr_bucket *content_head = NULL, *tmp_bkt;
-        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
-                      "Invalid mod_include state during file %s", r->filename);
-        CREATE_ERROR_BUCKET(ctx, tmp_bkt, APR_BRIGADE_FIRST(*bb), content_head);
+
+    return len; /* partial match of something */
+}
+
+/*
+ * This is the main loop over the current bucket brigade.
+ */
+static apr_status_t send_parsed_content(ap_filter_t *f, apr_bucket_brigade *bb)
+{
+    ssi_ctx_t *ctx = f->ctx;
+    request_rec *r = f->r;
+    apr_bucket *b = APR_BRIGADE_FIRST(bb);
+    apr_bucket_brigade *pass_bb;
+    apr_status_t rv = APR_SUCCESS;
+    char *magic; /* magic pointer for sentinel use */
+
+    /* fast exit */
+    if (APR_BRIGADE_EMPTY(bb)) {
+        return APR_SUCCESS;
     }
-    else {                    /* Entire brigade is middle chunk of SSI tag... */
-        if (!APR_BRIGADE_EMPTY(ctx->ssi_tag_brigade)) {
-            APR_BRIGADE_CONCAT(ctx->ssi_tag_brigade, *bb);
-        }
-        else {                  /* End of brigade contains part of SSI tag... */
-            apr_bucket *last;
-            if (ctx->head_start_index > 0) {
-                apr_bucket_split(ctx->head_start_bucket, ctx->head_start_index);
-                ctx->head_start_bucket = 
-                                        APR_BUCKET_NEXT(ctx->head_start_bucket);
-                ctx->head_start_index = 0;
-            }
-                           /* Set aside tag, pass pre-tag... */
-            tag_and_after = apr_brigade_split(*bb, ctx->head_start_bucket);
-            rv = ap_pass_brigade(f->next, *bb);
-            if (rv != APR_SUCCESS) {
+
+    /* we may crash, since already cleaned up; hand over the responsibility
+     * to the next filter;-)
+     */
+    if (ctx->seen_eos) {
+        return ap_pass_brigade(f->next, bb);
+    }
+
+    /* All stuff passed along has to be put into that brigade */
+    pass_bb = apr_brigade_create(ctx->ctx->pool, f->c->bucket_alloc);
+    ctx->ctx->bytes_parsed = 0;
+    ctx->ctx->output_now = 0;
+    ctx->error = 0;
+
+    /* loop over the current bucket brigade */
+    while (b != APR_BRIGADE_SENTINEL(bb)) {
+        const char *data = NULL;
+        apr_size_t len, index, release;
+        apr_bucket *newb = NULL;
+        char **store = &magic;
+        apr_size_t *store_len;
+
+        /* handle meta buckets before reading any data */
+        if (APR_BUCKET_IS_METADATA(b)) {
+            newb = APR_BUCKET_NEXT(b);
+
+            APR_BUCKET_REMOVE(b);
+
+            if (APR_BUCKET_IS_EOS(b)) {
+                ctx->seen_eos = 1;
+
+                /* Hit end of stream, time for cleanup ... But wait!
+                 * Perhaps we're not ready yet. We may have to loop one or
+                 * two times again to finish our work. In that case, we
+                 * just re-insert the EOS bucket to allow for an extra loop.
+                 *
+                 * PARSE_EXECUTE means, we've hit a directive just before the
+                 *    EOS, which is now waiting for execution.
+                 *
+                 * PARSE_DIRECTIVE_POSTTAIL means, we've hit a directive with
+                 *    no argument and no space between directive and end_seq
+                 *    just before the EOS. (consider <!--#printenv--> as last
+                 *    or only string within the stream). This state, however,
+                 *    just cleans up and turns itself to PARSE_EXECUTE, which
+                 *    will be passed through within the next (and actually
+                 *    last) round.
+                 */
+                if (PARSE_EXECUTE            == ctx->state ||
+                    PARSE_DIRECTIVE_POSTTAIL == ctx->state) {
+                    APR_BUCKET_INSERT_BEFORE(newb, b);
+                }
+                else {
+                    break; /* END OF STREAM */
+                }
+            }
+            else {
+                APR_BRIGADE_INSERT_TAIL(pass_bb, b);
+
+                if (APR_BUCKET_IS_FLUSH(b)) {
+                    ctx->ctx->output_now = 1;
+                }
+
+                b = newb;
+                continue;
+            }
+        }
+
+        /* enough is enough ... */
+        if (ctx->ctx->output_now ||
+            ctx->ctx->bytes_parsed > AP_MIN_BYTES_TO_WRITE) {
+
+            if (!APR_BRIGADE_EMPTY(pass_bb)) {
+                rv = ap_pass_brigade(f->next, pass_bb);
+                if (!APR_STATUS_IS_SUCCESS(rv)) {
+                    apr_brigade_destroy(pass_bb);
+                    return rv;
+                }
+            }
+
+            ctx->ctx->output_now = 0;
+            ctx->ctx->bytes_parsed = 0;
+        }
+
+        /* read the current bucket data */
+        len = 0;
+        if (!ctx->seen_eos) {
+            if (ctx->ctx->bytes_parsed > 0) {
+                rv = apr_bucket_read(b, &data, &len, APR_NONBLOCK_READ);
+                if (APR_STATUS_IS_EAGAIN(rv)) {
+                    ctx->ctx->output_now = 1;
+                    continue;
+                }
+            }
+
+            if (!len || !APR_STATUS_IS_SUCCESS(rv)) {
+                rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
+            }
+
+            if (!APR_STATUS_IS_SUCCESS(rv)) {
+                apr_brigade_destroy(pass_bb);
                 return rv;
             }
-            
-            /* Set aside the partial tag
-             * Exception: if there's an EOS at the end of this brigade,
-             * the tag will never be completed, so send an error and EOS
-             */
-            last = APR_BRIGADE_LAST(tag_and_after);
-            if (APR_BUCKET_IS_EOS(last)) {
-                /* Remove everything before the EOS (i.e., the partial tag)
-                 * and replace it with an error msg */
-                apr_bucket *b;
-                apr_bucket *err_bucket = NULL;
-                for (b = APR_BRIGADE_FIRST(tag_and_after);
-                     !APR_BUCKET_IS_EOS(b);
-                     b = APR_BRIGADE_FIRST(tag_and_after)) {
+
+            ctx->ctx->bytes_parsed += len;
+        }
+
+        /* zero length bucket, fetch next one */
+        if (!len && !ctx->seen_eos) {
+            b = APR_BUCKET_NEXT(b);
+            continue;
+        }
+
+        /*
+         * it's actually a data containing bucket, start/continue parsing
+         */
+
+        switch (ctx->state) {
+        /* no current tag; search for start sequence */
+        case PARSE_PRE_HEAD:
+            index = find_start_sequence(ctx, data, len);
+
+            if (index < len) {
+                apr_bucket_split(b, index);
+            }
+
+            newb = APR_BUCKET_NEXT(b);
+            if (ctx->ctx->flags & FLAG_PRINTING) {
+                APR_BUCKET_REMOVE(b);
+                APR_BRIGADE_INSERT_TAIL(pass_bb, b);
+            }
+            else {
+                apr_bucket_delete(b);
+            }
+
+            if (index < len) {
+                /* now delete the start_seq stuff from the remaining bucket */
+                if (PARSE_DIRECTIVE == ctx->state) { /* full match */
+                    apr_bucket_split(newb, ctx->ctx->start_seq_len);
+                    ctx->ctx->output_now = 1; /* pass pre-tag stuff */
+                }
+
+                b = APR_BUCKET_NEXT(newb);
+                apr_bucket_delete(newb);
+            }
+            else {
+                b = newb;
+            }
+
+            break;
+
+        /* we're currently looking for the end of the start sequence */
+        case PARSE_HEAD:
+            index = find_partial_start_sequence(ctx, data, len, &release);
+
+            /* check if we mismatched earlier and have to release some chars */
+            if (release && (ctx->ctx->flags & FLAG_PRINTING)) {
+                char *to_release = apr_palloc(ctx->ctx->pool, release);
+
+                memcpy(to_release, ctx->ctx->start_seq, release);
+                newb = apr_bucket_pool_create(to_release, release,
+                                              ctx->ctx->pool,
+                                              f->c->bucket_alloc);
+                APR_BRIGADE_INSERT_TAIL(pass_bb, newb);
+            }
+
+            if (index) { /* any match */
+                /* now delete the start_seq stuff from the remaining bucket */
+                if (PARSE_DIRECTIVE == ctx->state) { /* final match */
+                    apr_bucket_split(b, index);
+                    ctx->ctx->output_now = 1; /* pass pre-tag stuff */
+                }
+                newb = APR_BUCKET_NEXT(b);
+                apr_bucket_delete(b);
+                b = newb;
+            }
+
+            break;
+
+        /* we're currently grabbing the directive name */
+        case PARSE_DIRECTIVE:
+        case PARSE_DIRECTIVE_POSTNAME:
+        case PARSE_DIRECTIVE_TAIL:
+        case PARSE_DIRECTIVE_POSTTAIL:
+            index = find_directive(ctx, data, len, &store, &store_len);
+
+            if (index) {
+                apr_bucket_split(b, index);
+                newb = APR_BUCKET_NEXT(b);
+            }
+
+            if (store) {
+                if (index) {
                     APR_BUCKET_REMOVE(b);
-                    apr_bucket_destroy(b);
+                    APR_BRIGADE_INSERT_TAIL(ctx->tmp_bb, b);
+                    b = newb;
+                }
+
+                /* time for cleanup? */
+                if (store != &magic) {
+                    apr_brigade_pflatten(ctx->tmp_bb, store, store_len,
+                                         ctx->dpool);
+                    apr_brigade_cleanup(ctx->tmp_bb);
+                }
+            }
+            else if (index) {
+                apr_bucket_delete(b);
+                b = newb;
+            }
+
+            break;
+
+        /* skip WS and find out what comes next (arg or end_seq) */
+        case PARSE_PRE_ARG:
+            index = find_arg_or_tail(ctx, data, len);
+
+            if (index) { /* skipped whitespaces */
+                if (index < len) {
+                    apr_bucket_split(b, index);
+                }
+                newb = APR_BUCKET_NEXT(b);
+                apr_bucket_delete(b);
+                b = newb;
+            }
+
+            break;
+
+        /* currently parsing name[=val] */
+        case PARSE_ARG:
+        case PARSE_ARG_NAME:
+        case PARSE_ARG_POSTNAME:
+        case PARSE_ARG_EQ:
+        case PARSE_ARG_PREVAL:
+        case PARSE_ARG_VAL:
+        case PARSE_ARG_VAL_ESC:
+        case PARSE_ARG_POSTVAL:
+            index = find_argument(ctx, data, len, &store, &store_len);
+
+            if (index) {
+                apr_bucket_split(b, index);
+                newb = APR_BUCKET_NEXT(b);
+            }
+
+            if (store) {
+                if (index) {
+                    APR_BUCKET_REMOVE(b);
+                    APR_BRIGADE_INSERT_TAIL(ctx->tmp_bb, b);
+                    b = newb;
+                }
+
+                /* time for cleanup? */
+                if (store != &magic) {
+                    apr_brigade_pflatten(ctx->tmp_bb, store, store_len,
+                                         ctx->dpool);
+                    apr_brigade_cleanup(ctx->tmp_bb);
+                }
+            }
+            else if (index) {
+                apr_bucket_delete(b);
+                b = newb;
+            }
+
+            break;
+
+        /* try to match end_seq at current pos. */
+        case PARSE_TAIL:
+        case PARSE_TAIL_SEQ:
+            index = find_tail(ctx, data, len);
+
+            switch (ctx->state) {
+            case PARSE_EXECUTE:  /* full match */
+                apr_bucket_split(b, index);
+                newb = APR_BUCKET_NEXT(b);
+                apr_bucket_delete(b);
+                b = newb;
+                break;
+
+            case PARSE_ARG:      /* no match */
+                /* PARSE_ARG must reparse at the beginning */
+                APR_BRIGADE_PREPEND(bb, ctx->tmp_bb);
+                b = APR_BRIGADE_FIRST(bb);
+                break;
+
+            default:             /* partial match */
+                newb = APR_BUCKET_NEXT(b);
+                APR_BUCKET_REMOVE(b);
+                APR_BRIGADE_INSERT_TAIL(ctx->tmp_bb, b);
+                b = newb;
+                break;
+            }
+
+            break;
+
+        /* now execute the parsed directive, cleanup the space and
+         * start again with PARSE_PRE_HEAD
+         */
+        case PARSE_EXECUTE:
+            /* if there was an error, it was already logged; just stop here */
+            if (ctx->error) {
+                if (ctx->ctx->flags & FLAG_PRINTING) {
+                    SSI_CREATE_ERROR_BUCKET(ctx->ctx, f, pass_bb);
+                    ctx->error = 0;
                 }
-                CREATE_ERROR_BUCKET(ctx, err_bucket, b, err_bucket);
-                rv = ap_pass_brigade(f->next, tag_and_after);
             }
             else {
-                ap_save_brigade(f, &ctx->ssi_tag_brigade,
-                                &tag_and_after, r->pool);
+                include_handler_fn_t *handle_func;
+
+                handle_func =
+                    (include_handler_fn_t *) apr_hash_get(include_hash,
+                                                    ctx->directive,
+                                                    ctx->ctx->directive_length);
+                if (handle_func) {
+                    apr_bucket *dummy;
+                    char *tag;
+                    apr_size_t tag_len = 0;
+                    ssi_arg_item_t *carg = ctx->argv;
+
+                    /* legacy wrapper code */
+                    while (carg) {
+                        /* +1 \0 byte (either after tag or value)
+                         * +1 =  byte (before value)
+                         */
+                        tag_len += (carg->name  ? carg->name_len      : 0) +
+                                   (carg->value ? carg->value_len + 1 : 0) + 1;
+                        carg = carg->next;
+                    }
+
+                    tag = ctx->ctx->combined_tag = ctx->ctx->curr_tag_pos =
+                        apr_palloc(ctx->dpool, tag_len);
+
+                    carg = ctx->argv;
+                    while (carg) {
+                        if (carg->name) {
+                            memcpy(tag, carg->name, carg->name_len);
+                            tag += carg->name_len;
+                        }
+                        if (carg->value) {
+                            *tag++ = '=';
+                            memcpy(tag, carg->value, carg->value_len);
+                            tag += carg->value_len;
+                        }
+                        *tag++ = '\0';
+                        carg = carg->next;
+                    }
+                    ctx->ctx->tag_length = tag_len;
+
+                    /* create dummy buckets for backards compat */
+                    ctx->ctx->head_start_bucket =
+                        apr_bucket_pool_create(apr_pmemdup(ctx->ctx->pool,
+                                                           ctx->ctx->start_seq,
+                                                       ctx->ctx->start_seq_len),
+                                               ctx->ctx->start_seq_len,
+                                               ctx->ctx->pool,
+                                               f->c->bucket_alloc);
+                    APR_BRIGADE_INSERT_TAIL(ctx->ctx->ssi_tag_brigade,
+                                            ctx->ctx->head_start_bucket);
+                    ctx->ctx->tag_start_bucket =
+                        apr_bucket_pool_create(apr_pmemdup(ctx->ctx->pool,
+                                                         ctx->ctx->combined_tag,
+                                                         ctx->ctx->tag_length),
+                                               ctx->ctx->tag_length,
+                                               ctx->ctx->pool,
+                                               f->c->bucket_alloc);
+                    APR_BRIGADE_INSERT_TAIL(ctx->ctx->ssi_tag_brigade,
+                                            ctx->ctx->tag_start_bucket);
+                    ctx->ctx->tail_start_bucket =
+                        apr_bucket_pool_create(apr_pmemdup(ctx->ctx->pool,
+                                                           ctx->ctx->end_seq,
+                                                           ctx->end_seq_len),
+                                               ctx->end_seq_len,
+                                               ctx->ctx->pool,
+                                               f->c->bucket_alloc);
+                    APR_BRIGADE_INSERT_TAIL(ctx->ctx->ssi_tag_brigade,
+                                            ctx->ctx->tail_start_bucket);
+
+                    rv = handle_func(ctx->ctx, &bb, r, f, b, &dummy);
+
+                    apr_brigade_cleanup(ctx->ctx->ssi_tag_brigade);
+
+                    if (rv != 0 && rv != 1 && rv != -1) {
+                        apr_brigade_destroy(pass_bb);
+                        return rv;
+                    }
+
+                    if (dummy) {
+                        apr_bucket_brigade *remain;
+
+                        remain = apr_brigade_split(bb, b);
+                        APR_BRIGADE_CONCAT(pass_bb, bb);
+                        bb = remain;
+                    }
+                }
+                else {
+                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                                  "unknown directive \"%s\" in parsed doc %s",
+                                  apr_pstrmemdup(r->pool, ctx->directive,
+                                                 ctx->ctx->directive_length),
+                                                 r->filename);
+                    if (ctx->ctx->flags & FLAG_PRINTING) {
+                        SSI_CREATE_ERROR_BUCKET(ctx->ctx, f, pass_bb);
+                    }
+                }
             }
-            if (rv != APR_SUCCESS) {
-                return rv;
+
+            /* cleanup */
+            apr_pool_clear(ctx->dpool);
+            apr_brigade_cleanup(ctx->tmp_bb);
+
+            /* Oooof. Done here, start next round */
+            ctx->state = PARSE_PRE_HEAD;
+            break;
+        }
+
+    } /* while (brigade) */
+
+    /* End of stream. Final cleanup */
+    if (ctx->seen_eos) {
+        if (PARSE_HEAD == ctx->state) {
+            if (ctx->ctx->flags & FLAG_PRINTING) {
+                char *to_release = apr_palloc(ctx->ctx->pool,
+                                              ctx->ctx->parse_pos);
+
+                memcpy(to_release, ctx->ctx->start_seq, ctx->ctx->parse_pos);
+                APR_BRIGADE_INSERT_TAIL(pass_bb,
+                                        apr_bucket_pool_create(to_release,
+                                        ctx->ctx->parse_pos, ctx->ctx->pool,
+                                        f->c->bucket_alloc));
             }
-            ctx->bytes_parsed = 0;
         }
+        else if (PARSE_PRE_HEAD != ctx->state) {
+            ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                          "SSI directive was not properly finished at the end "
+                          "of parsed document %s", r->filename);
+            if (ctx->ctx->flags & FLAG_PRINTING) {
+                SSI_CREATE_ERROR_BUCKET(ctx->ctx, f, pass_bb);
+            }
+        }
+
+        if (!(ctx->ctx->flags & FLAG_PRINTING)) {
+            ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
+                          "missing closing endif directive in parsed document"
+                          " %s", r->filename);
+        }
+
+        /* cleanup our temporary memory */
+        apr_brigade_destroy(ctx->tmp_bb);
+        apr_pool_destroy(ctx->dpool);
+
+        /* don't forget to finally insert the EOS bucket */
+        APR_BRIGADE_INSERT_TAIL(pass_bb, b);
     }
-    return APR_SUCCESS;
+
+    /* if something's left over, pass it along */
+    if (!APR_BRIGADE_EMPTY(pass_bb)) {
+        rv = ap_pass_brigade(f->next, pass_bb);
+    }
+    else {
+        rv = APR_SUCCESS;
+    }
+
+    apr_brigade_destroy(pass_bb);
+    return rv;
 }
 
 static void *create_includes_dir_config(apr_pool_t *p, char *dummy)
@@ -3337,14 +3544,20 @@
         || !(f->r->finfo.protection & APR_GEXECUTE)) {
         f->r->no_local_copy = 1;
     }
-    
+
+    /* Don't allow ETag headers to be generated - see RFC2616 - 13.3.4.
+     * We don't know if we are going to be including a file or executing
+     * a program - in either case a strong ETag header will likely be invalid.
+     */
+    apr_table_setn(f->r->notes, "no-etag", "");
+
     return OK;
 }
 
 static apr_status_t includes_filter(ap_filter_t *f, apr_bucket_brigade *b)
 {
     request_rec *r = f->r;
-    include_ctx_t *ctx = f->ctx;
+    ssi_ctx_t *ctx = f->ctx;
     request_rec *parent;
     include_dir_config *conf = 
                    (include_dir_config *)ap_get_module_config(r->per_dir_config,
@@ -3354,30 +3567,55 @@
                                                               &include_module);
 
     if (!(ap_allow_options(r) & OPT_INCLUDES)) {
+        ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
+                      "mod_include: Options +Includes (or IncludesNoExec) "
+                      "wasn't set, INCLUDES filter removed");
+        ap_remove_output_filter(f);
         return ap_pass_brigade(f->next, b);
     }
 
     if (!f->ctx) {
-        f->ctx = ctx = apr_pcalloc(f->c->pool, sizeof(*ctx));
-        ctx->state = PRE_HEAD;
-        ctx->flags = (FLAG_PRINTING | FLAG_COND_TRUE);
-        if (ap_allow_options(r) & OPT_INCNOEXEC) {
-            ctx->flags |= FLAG_NO_EXEC;
-        }
-        ctx->ssi_tag_brigade = apr_brigade_create(f->c->pool,
-                                                  f->c->bucket_alloc);
-        ctx->status = APR_SUCCESS;
-
-        ctx->error_str = conf->default_error_msg;
-        ctx->time_str = conf->default_time_fmt;
-        ctx->pool = f->c->pool;
-        ctx->start_seq_pat = &sconf->start_seq_pat;
-        ctx->start_seq  = sconf->default_start_tag;
-        ctx->start_seq_len = sconf->start_tag_len;
-        ctx->end_seq = sconf->default_end_tag;
+        /* create context for this filter */
+        f->ctx = ctx = apr_palloc(f->c->pool, sizeof(*ctx));
+        ctx->ctx = apr_pcalloc(f->c->pool, sizeof(*ctx->ctx));
+        ctx->ctx->pool = f->r->pool;
+        apr_pool_create(&ctx->dpool, ctx->ctx->pool);
+
+        /* configuration data */
+        ctx->end_seq_len = strlen(sconf->default_end_tag);
+        ctx->r = f->r;
+
+        /* runtime data */
+        ctx->tmp_bb = apr_brigade_create(ctx->ctx->pool, f->c->bucket_alloc);
+        ctx->seen_eos = 0;
+        ctx->state = PARSE_PRE_HEAD;
+        ctx->ctx->flags = (FLAG_PRINTING | FLAG_COND_TRUE);
+        if (ap_allow_options(f->r) & OPT_INCNOEXEC) {
+            ctx->ctx->flags |= FLAG_NO_EXEC;
+        }
+        ctx->ctx->if_nesting_level = 0;
+        ctx->ctx->re_string = NULL;
+        ctx->ctx->error_str_override = NULL;
+        ctx->ctx->time_str_override = NULL;
+
+        ctx->ctx->error_str = conf->default_error_msg;
+        ctx->ctx->time_str = conf->default_time_fmt;
+        ctx->ctx->start_seq_pat = &sconf->start_seq_pat;
+        ctx->ctx->start_seq  = sconf->default_start_tag;
+        ctx->ctx->start_seq_len = sconf->start_tag_len;
+        ctx->ctx->end_seq = sconf->default_end_tag;
+
+        /* legacy compat stuff */
+        ctx->ctx->state = PARSED; /* dummy */
+        ctx->ctx->ssi_tag_brigade = apr_brigade_create(f->c->pool,
+                                                       f->c->bucket_alloc);
+        ctx->ctx->status = APR_SUCCESS;
+        ctx->ctx->head_start_index = 0;
+        ctx->ctx->tag_start_index = 0;
+        ctx->ctx->tail_start_index = 0;
     }
     else {
-        ctx->bytes_parsed = 0;
+        ctx->ctx->bytes_parsed = 0;
     }
 
     if ((parent = ap_get_module_config(r->request_config, &include_module))) {
@@ -3407,14 +3645,13 @@
      */
     apr_table_unset(f->r->headers_out, "Content-Length");
 
-    /* Always unset the ETag/Last-Modified fields - see RFC2616 - 13.3.4.
+    /* Always unset the Last-Modified field - see RFC2616 - 13.3.4.
      * We don't know if we are going to be including a file or executing
      * a program which may change the Last-Modified header or make the 
      * content completely dynamic.  Therefore, we can't support these
      * headers.
      * Exception: XBitHack full means we *should* set the Last-Modified field.
      */
-    apr_table_unset(f->r->headers_out, "ETag");
 
     /* Assure the platform supports Group protections */
     if ((*conf->xbithack == xbithack_full)
@@ -3427,7 +3664,17 @@
         apr_table_unset(f->r->headers_out, "Last-Modified");
     }
 
-    return send_parsed_content(&b, r, f);
+    /* add QUERY stuff to env cause it ain't yet */
+    if (r->args) {
+        char *arg_copy = apr_pstrdup(r->pool, r->args);
+
+        apr_table_setn(r->subprocess_env, "QUERY_STRING", r->args);
+        ap_unescape_url(arg_copy);
+        apr_table_setn(r->subprocess_env, "QUERY_STRING_UNESCAPED",
+                  ap_escape_shell_cmd(r->pool, arg_copy));
+    }
+
+    return send_parsed_content(f, b);
 }
 
 static void ap_register_include_handler(char *tag, include_handler_fn_t *func)
Index: modules/filters/mod_include.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/filters/mod_include.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/filters/mod_include.h	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/filters/mod_include.h	29 Dec 2005 18:41:55 -0000	1.2
@@ -131,7 +131,17 @@
  * ssi_tag_brigade: The temporary brigade used by this filter to set aside
  *                  the buckets containing parts of the ssi tag and headers.
  */
-typedef enum {PRE_HEAD, PARSE_HEAD, PARSE_DIRECTIVE, PARSE_TAG, PARSE_TAIL, PARSED} states;
+
+/* I keep this stuff here, because of binary compat. It probably doesn't care,
+ * but who knows ...?
+ */
+#ifdef MOD_INCLUDE_REDESIGN
+typedef enum {PRE_HEAD, BLOW_PARSE_HEAD, BLOW_PARSE_DIRECTIVE, PARSE_TAG,
+              BLOW_PARSE_TAIL, PARSED} states;
+#else
+typedef enum {PRE_HEAD, PARSE_HEAD, PARSE_DIRECTIVE, PARSE_TAG, PARSE_TAIL,
+              PARSED} states;
+#endif
 
 /** forward referenced as it needs to be held on the context */
 typedef struct bndm_t bndm_t;
Index: modules/generators/mod_autoindex.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/generators/mod_autoindex.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/generators/mod_autoindex.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/generators/mod_autoindex.c	6 Sep 2004 12:23:20 -0000	1.2
@@ -2113,8 +2113,16 @@
     fullpath = apr_palloc(r->pool, APR_PATH_MAX);
     dirpathlen = strlen(name);
     memcpy(fullpath, name, dirpathlen);
-    while (apr_dir_read(&dirent, APR_FINFO_MIN | APR_FINFO_NAME,
-                        thedir) == APR_SUCCESS) {
+
+    do {
+        status = apr_dir_read(&dirent, APR_FINFO_MIN | APR_FINFO_NAME, thedir);
+        if (APR_STATUS_IS_INCOMPLETE(status)) {
+            continue; /* ignore un-stat()able files */
+        }
+        else if (status != APR_SUCCESS) {
+            break;
+        }
+
         /* We want to explode symlinks here. */
         if (dirent.filetype == APR_LNK) {
             const char *savename;
@@ -2140,7 +2148,8 @@
             head = p;
             num_ent++;
         }
-    }
+    } while (1);
+
     if (num_ent > 0) {
         ar = (struct ent **) apr_palloc(r->pool,
                                         num_ent * sizeof(struct ent *));
Index: modules/generators/mod_cgid.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/generators/mod_cgid.c,v
retrieving revision 1.1.1.1
retrieving revision 1.9
diff -u -u -r1.1.1.1 -r1.9
--- modules/generators/mod_cgid.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/generators/mod_cgid.c	22 Jun 2005 21:20:02 -0000	1.9
@@ -117,6 +117,7 @@
 
 module AP_MODULE_DECLARE_DATA cgid_module; 
 
+static int cgid_start(apr_pool_t *p, server_rec *main_server, apr_proc_t *procnew);
 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *main_server); 
 static int handle_exec(include_ctx_t *ctx, apr_bucket_brigade **bb, request_rec *r,
                        ap_filter_t *f, apr_bucket *head_ptr, apr_bucket **inserted_head);
@@ -125,10 +126,13 @@
 static APR_OPTIONAL_FN_TYPE(ap_ssi_get_tag_and_value) *cgid_pfn_gtv;
 static APR_OPTIONAL_FN_TYPE(ap_ssi_parse_string) *cgid_pfn_ps;
 
-static apr_pool_t *pcgi; 
+static apr_pool_t *pcgi = NULL; 
 static int total_modules = 0;
 static pid_t daemon_pid;
 static int daemon_should_exit = 0;
+static server_rec *root_server = NULL;
+static apr_pool_t *root_pool = NULL;
+static pid_t parent_pid;
 
 /* Read and discard the data in the brigade produced by a CGI script */
 static void discard_script_output(apr_bucket_brigade *bb);
@@ -194,6 +198,9 @@
                             * to find the script pid when it is time for that
                             * process to be cleaned up
                             */
+    pid_t ppid;            /* sanity check for config problems leading to
+                            * wrong cgid socket use
+                            */
     int core_module_index;
     int have_suexec;
     int suexec_module_index;
@@ -267,27 +274,34 @@
 #if APR_HAS_OTHER_CHILD
 static void cgid_maint(int reason, void *data, apr_wait_t status)
 {
-    pid_t *sd = data;
+    apr_proc_t *proc = data;
 
     switch (reason) {
         case APR_OC_REASON_DEATH:
+            apr_proc_other_child_unregister(data);
+            /* If apache is not terminating or restarting,
+             * restart the cgid daemon
+             */
+            if (!ap_graceful_stop_signalled()) {
+                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
+                              "cgid daemon process died, restarting");
+               cgid_start(root_pool, root_server, proc);
+            }
+            break;
         case APR_OC_REASON_RESTART:
             /* don't do anything; server is stopping or restarting */
             apr_proc_other_child_unregister(data);
             break;
         case APR_OC_REASON_LOST:
-            /* it would be better to restart just the cgid child
-             * process but for now we'll gracefully restart the entire 
-             * server by sending AP_SIG_GRACEFUL to ourself, the httpd 
-             * parent process
-             */
-            kill(getpid(), AP_SIG_GRACEFUL);
+            /* Restart the child cgid daemon process */
+            apr_proc_other_child_unregister(data);
+            cgid_start(root_pool, root_server, proc);
             break;
         case APR_OC_REASON_UNREGISTER:
             /* we get here when pcgi is cleaned up; pcgi gets cleaned
              * up when pconf gets cleaned up
              */
-            kill(*sd, SIGHUP); /* send signal to daemon telling it to die */
+            kill(proc->pid, SIGHUP); /* send signal to daemon telling it to die */
             break;
     }
 }
@@ -464,6 +478,7 @@
     apr_status_t stat;
 
     req.req_type = req_type;
+    req.ppid = parent_pid;
     req.conn_id = r->connection->id;
     req.core_module_index = core_module.module_index;
     if (suexec_mod) {
@@ -618,7 +633,7 @@
 
     memset(&unix_addr, 0, sizeof(unix_addr));
     unix_addr.sun_family = AF_UNIX;
-    strcpy(unix_addr.sun_path, sconf->sockname);
+    apr_cpystrn(unix_addr.sun_path, sconf->sockname, sizeof unix_addr.sun_path);
 
     omask = umask(0077); /* so that only Apache can use socket */
     rc = bind(sd, (struct sockaddr *)&unix_addr, sizeof(unix_addr));
@@ -688,6 +703,14 @@
             continue;
         }
 
+        if (cgid_req.ppid != parent_pid) {
+            ap_log_error(APLOG_MARK, APLOG_CRIT, 0, main_server,
+                         "CGI request received from wrong server instance; "
+                         "see ScriptSock directive");
+            close(sd2);
+            continue;
+        }
+
         if (cgid_req.req_type == GETPID_REQ) {
             pid_t pid;
 
@@ -769,7 +792,26 @@
                              apr_filename_of_pathname(r->filename));
             }
             else {
-                apr_hash_set(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id), 
+                /* We don't want to leak storage for the key, so only allocate
+                 * a key if the key doesn't exist yet in the hash; there are
+                 * only a limited number of possible keys (one for each
+                 * possible thread in the server), so we can allocate a copy
+                 * of the key the first time a thread has a cgid request.
+                 * Note that apr_hash_set() only uses the storage passed in
+                 * for the key if it is adding the key to the hash for the
+                 * first time; new key storage isn't needed for replacing the
+                 * existing value of a key.
+                 */
+                void *key;
+                
+                if (apr_hash_get(script_hash, &cgid_req.conn_id, sizeof(cgid_req.conn_id))) {
+                    key = &cgid_req.conn_id;
+                }
+                else {
+                    key = apr_pcalloc(pcgi, sizeof(cgid_req.conn_id));
+                    memcpy(key, &cgid_req.conn_id, sizeof(cgid_req.conn_id));
+                }
+                apr_hash_set(script_hash, key, sizeof(cgid_req.conn_id),
                              (void *)procnew->pid);
             }
         }
@@ -777,20 +819,52 @@
     return -1; 
 } 
 
+static int cgid_start(apr_pool_t *p, server_rec *main_server,
+                      apr_proc_t *procnew)
+{
+
+    daemon_should_exit = 0; /* clear setting from previous generation */
+    if ((daemon_pid = fork()) < 0) {
+        ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server,
+                     "mod_cgid: Couldn't spawn cgid daemon process");
+        return DECLINED;
+    }
+    else if (daemon_pid == 0) {
+        if (pcgi == NULL) {
+            apr_pool_create(&pcgi, p);
+        }
+        cgid_server(main_server);
+        exit(-1);
+    }
+    procnew->pid = daemon_pid;
+    procnew->err = procnew->in = procnew->out = NULL;
+    apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
+#if APR_HAS_OTHER_CHILD
+    apr_proc_other_child_register(procnew, cgid_maint, procnew, NULL, p);
+#endif
+    return OK;
+}
+
 static int cgid_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, 
-                      server_rec *main_server) 
+                     server_rec *main_server) 
 { 
-    apr_proc_t *procnew;
-    void *data;
+    apr_proc_t *procnew = NULL;
     int first_time = 0;
     const char *userdata_key = "cgid_init";
     module **m;
+    int ret = OK;
+
+    root_server = main_server;
+    root_pool = p;
 
-    apr_pool_userdata_get(&data, userdata_key, main_server->process->pool);
-    if (!data) {
+    apr_pool_userdata_get((void **)&procnew, userdata_key, main_server->process->pool);
+    if (!procnew) {
         first_time = 1;
-        apr_pool_userdata_set((const void *)1, userdata_key,
-                         apr_pool_cleanup_null, main_server->process->pool);
+        procnew = apr_pcalloc(main_server->process->pool, sizeof(*procnew));
+        procnew->pid = -1;
+        procnew->err = procnew->in = procnew->out = NULL;
+        apr_pool_userdata_set((const void *)procnew, userdata_key,
+                     apr_pool_cleanup_null, main_server->process->pool);
     }
 
     if (!first_time) {
@@ -798,25 +872,11 @@
         for (m = ap_preloaded_modules; *m != NULL; m++)
             total_modules++;
 
-        daemon_should_exit = 0; /* clear setting from previous generation */
-        if ((daemon_pid = fork()) < 0) {
-            ap_log_error(APLOG_MARK, APLOG_ERR, errno, main_server, 
-                         "mod_cgid: Couldn't spawn cgid daemon process"); 
-            return DECLINED;
+        parent_pid = getpid();
+        ret = cgid_start(p, main_server, procnew);
+        if (ret != OK ) {
+            return ret;
         }
-        else if (daemon_pid == 0) {
-            apr_pool_create(&pcgi, p); 
-            cgid_server(main_server);
-            exit(-1);
-        } 
-        procnew = apr_pcalloc(p, sizeof(*procnew));
-        procnew->pid = daemon_pid;
-        procnew->err = procnew->in = procnew->out = NULL;
-        apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
-#if APR_HAS_OTHER_CHILD
-        apr_proc_other_child_register(procnew, cgid_maint, &procnew->pid, NULL, p);
-#endif
-
         cgid_pfn_reg_with_ssi = APR_RETRIEVE_OPTIONAL_FN(ap_register_include_handler);
         cgid_pfn_gtv          = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_get_tag_and_value);
         cgid_pfn_ps           = APR_RETRIEVE_OPTIONAL_FN(ap_ssi_parse_string);
@@ -828,7 +888,7 @@
             cgid_pfn_reg_with_ssi("exec", handle_exec);
         }
     }
-    return OK;
+    return ret;
 } 
 
 static void *create_cgid_config(apr_pool_t *p, server_rec *s) 
@@ -1066,7 +1126,7 @@
 
     memset(&unix_addr, 0, sizeof(unix_addr));
     unix_addr.sun_family = AF_UNIX;
-    strcpy(unix_addr.sun_path, conf->sockname);
+    apr_cpystrn(unix_addr.sun_path, conf->sockname, sizeof unix_addr.sun_path);
 
     connect_tries = 0;
     sliding_timer = 100000; /* 100 milliseconds */
@@ -1142,7 +1202,17 @@
     apr_interval_time_t total = 0;
 
     do {
+#ifdef _AIX
+        /* On AIX, for processes like mod_cgid's script children where
+         * SIGCHLD is ignored, kill(pid,0) returns success for up to
+         * one second after the script child exits, based on when a
+         * daemon runs to clean up unnecessary process table entries.
+         * getpgid() can report the proper info (-1/ESRCH) immediately.
+         */
+        if (getpgid(pid) < 0) {
+#else
         if (kill(pid, 0) < 0) {
+#endif
             return APR_SUCCESS;
         }
         apr_sleep(interval);
@@ -1192,6 +1262,7 @@
     /* we got a socket, and there is already a cleanup registered for it */
 
     req.req_type = GETPID_REQ;
+    req.ppid = parent_pid;
     req.conn_id = info->r->connection->id;
 
     stat = sock_write(sd, &req, sizeof(req));
@@ -1314,7 +1385,7 @@
      * Note that this does not register a cleanup for the socket.  We did
      * that explicitly right after we created the socket.
      */
-    apr_os_pipe_put(&tempsock, &sd, r->pool);
+    ihs_os_pipe_put_ex(&tempsock, &sd, IHS_FILE_NO_BUCKET_CLOSE_AT_EOF, r->pool);
 
     if ((argv0 = strrchr(r->filename, '/')) != NULL) 
         argv0++; 
@@ -1447,24 +1518,12 @@
             return HTTP_MOVED_TEMPORARILY; 
         } 
 
-        /* Passing our socket down the filter chain in a pipe bucket
-         * gives up the responsibility of closing the socket, so
-         * get rid of the cleanup.
-         */
-        apr_pool_cleanup_kill(r->pool, (void *)sd, close_unix_socket);
-
         ap_pass_brigade(r->output_filters, bb);
     } 
 
     if (nph) {
         struct ap_filter_t *cur;
         
-        /* Passing our socket down the filter chain in a pipe bucket
-         * gives up the responsibility of closing the socket, so
-         * get rid of the cleanup.
-         */
-        apr_pool_cleanup_kill(r->pool, (void *)sd, close_unix_socket);
-
         /* get rid of all filters up through protocol...  since we
          * haven't parsed off the headers, there is no way they can
          * work
@@ -1646,7 +1705,7 @@
      * Note that this does not register a cleanup for the socket.  We did
      * that explicitly right after we created the socket.
      */
-    apr_os_pipe_put(&tempsock, &sd, r->pool);
+    ihs_os_pipe_put_ex(&tempsock, &sd, IHS_FILE_NO_BUCKET_CLOSE_AT_EOF, r->pool);
 
     if ((retval = ap_setup_client_block(r, REQUEST_CHUNKED_ERROR))) 
         return retval; 
@@ -1684,12 +1743,6 @@
     } 
 
     if (!r->header_only) { 
-        /* Passing our socket down the filter chain in a pipe bucket
-         * gives up the responsibility of closing the socket, so
-         * get rid of the cleanup.
-         */
-        apr_pool_cleanup_kill(r->pool, (void *)sd, close_unix_socket);
-
         bcgi = apr_brigade_create(r->pool, r->connection->bucket_alloc);
         b    = apr_bucket_pipe_create(tempsock, r->connection->bucket_alloc);
         APR_BRIGADE_INSERT_TAIL(bcgi, b);
Index: modules/generators/mod_status.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/generators/mod_status.c,v
retrieving revision 1.1.1.1
retrieving revision 1.9
diff -u -u -r1.1.1.1 -r1.9
--- modules/generators/mod_status.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/generators/mod_status.c	6 Oct 2005 15:51:21 -0000	1.9
@@ -107,11 +107,13 @@
 #include <time.h>
 #include "scoreboard.h"
 #include "http_log.h"
+#include "mod_status.h"
 #if APR_HAVE_UNISTD_H
 #include <unistd.h>
 #endif
 #define APR_WANT_STRFUNC
 #include "apr_want.h"
+#include "apr_strings.h"
 
 #ifdef NEXT
 #if (NX_CURRENT_COMPILER_RELEASE == 410)
@@ -141,6 +143,20 @@
 
 int server_limit, thread_limit;
 
+#ifdef HAVE_TIMES
+/* ugh... need to know if we're running with a pthread implementation
+ * such as linuxthreads that treats individual threads as distinct
+ * processes; that affects how we add up CPU time in a process
+ */
+static pid_t child_pid;
+#endif
+
+/* Implement 'ap_run_status_hook'. */
+APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(ap, STATUS, int, status_hook,
+                                    (request_rec *r, int flags),
+                                    (r, flags),
+                                    OK, DECLINED)
+
 /*
  * command-related code. This is here to prevent use of ExtendedStatus
  * without status_module included.
@@ -217,6 +233,8 @@
 #define STAT_OPT_REFRESH  0
 #define STAT_OPT_NOTABLE  1
 #define STAT_OPT_AUTO     2
+#define STAT_OPT_MODULE   3
+#define STAT_OPT_MODULE_STATE 4
 
 struct stat_opt {
     int id;
@@ -229,10 +247,14 @@
     {STAT_OPT_REFRESH, "refresh", "Refresh"},
     {STAT_OPT_NOTABLE, "notable", NULL},
     {STAT_OPT_AUTO, "auto", NULL},
+    {STAT_OPT_MODULE, "showmodule", NULL},
+    {STAT_OPT_MODULE_STATE, "showmodulestate", NULL},
     {STAT_OPT_END, NULL, NULL}
 };
 
 static char status_flags[SERVER_NUM_STATUS];
+static const char *modnames[256];
+static const char *statenames[256];
 
 static int status_handler(request_rec *r)
 {
@@ -249,9 +271,11 @@
     long req_time;
 #ifdef HAVE_TIMES
     float tick;
+    int times_per_thread = getpid() != child_pid;
 #endif
     int short_report;
     int no_table_report;
+    int show_module, show_module_state;
     worker_score *ws_record;
     process_score *ps_record;
     char *stat_buffer;
@@ -278,6 +302,8 @@
     kbcount = 0;
     short_report = 0;
     no_table_report = 0;
+    show_module = 0;
+    show_module_state = 0;
 
     pid_buffer = apr_palloc(r->pool, server_limit * sizeof(pid_t));
     stat_buffer = apr_palloc(r->pool, server_limit * thread_limit * sizeof(char));
@@ -323,6 +349,13 @@
                 case STAT_OPT_NOTABLE:
                     no_table_report = 1;
                     break;
+                case STAT_OPT_MODULE:
+                    show_module = 1;
+                    break;
+                case STAT_OPT_MODULE_STATE:
+                    show_module = 1;
+                    show_module_state = 1;
+                    break;
                 case STAT_OPT_AUTO:
                     ap_set_content_type(r, "text/plain");
                     short_report = 1;
@@ -335,6 +368,11 @@
     }
 
     for (i = 0; i < server_limit; ++i) {
+#ifdef HAVE_TIMES
+        clock_t proc_tu = 0, proc_ts = 0, proc_tcu = 0, proc_tcs = 0;
+        clock_t tmp_tu, tmp_ts, tmp_tcu, tmp_tcs;
+#endif
+        
         ps_record = ap_get_scoreboard_process(i);
         for (j = 0; j < thread_limit; ++j) {
             int indx = (i * thread_limit) + j;
@@ -363,10 +401,28 @@
 
                 if (lres != 0 || (res != SERVER_READY && res != SERVER_DEAD)) {
 #ifdef HAVE_TIMES
-                    tu += ws_record->times.tms_utime;
-                    ts += ws_record->times.tms_stime;
-                    tcu += ws_record->times.tms_cutime;
-                    tcs += ws_record->times.tms_cstime;
+                    tmp_tu = ws_record->times.tms_utime;
+                    tmp_ts = ws_record->times.tms_stime;
+                    tmp_tcu = ws_record->times.tms_cutime;
+                    tmp_tcs = ws_record->times.tms_cstime;
+
+                    if (times_per_thread) {
+                        proc_tu += tmp_tu;
+                        proc_ts += tmp_ts;
+                        proc_tcu += tmp_tcu;
+                        proc_tcs += proc_tcs;
+                    }
+                    else {
+                        if (tmp_tu > proc_tu ||
+                            tmp_ts > proc_ts ||
+                            tmp_tcu > proc_tcu ||
+                            tmp_tcs > proc_tcs) {
+                            proc_tu = tmp_tu;
+                            proc_ts = tmp_ts;
+                            proc_tcu = tmp_tcu;
+                            proc_tcs = proc_tcs;
+                        }
+                    }
 #endif /* HAVE_TIMES */
 
                     count += lres;
@@ -379,7 +435,12 @@
                 }
             }
         }
-
+#ifdef HAVE_TIMES
+        tu += proc_tu;
+        ts += proc_ts;
+        tcu += proc_tcu;
+        tcs += proc_tcs;
+#endif
         pid_buffer[i] = ps_record->pid;
     }
 
@@ -543,17 +604,25 @@
     if (ap_extended_status && !short_report) {
         if (no_table_report)
             ap_rputs("<hr /><h2>Server Details</h2>\n\n", r);
-        else
+        else {
             ap_rputs("\n\n<table border=\"0\"><tr>"
                      "<th>Srv</th><th>PID</th><th>Acc</th>"
-                     "<th>M</th>"
+                     "<th>M</th>", r);
+            if (show_module)
+                ap_rputs("<th>Module</th>", r);
+            if (show_module_state)
+                ap_rputs("<th>State</th>", r);
+            ap_rputs(
 #ifdef HAVE_TIMES
                      "<th>CPU\n</th>"
 #endif
                      "<th>SS</th><th>Req</th>"
-                     "<th>Conn</th><th>Child</th><th>Slot</th>"
-                     "<th>Client</th><th>VHost</th>"
+                     "<th>Conn</th><th>Child</th><th>Slot</th>", r);
+            if (show_module_state)
+                ap_rputs("<th>Module Info</th>", r);
+            ap_rputs("<th>Client</th><th>VHost</th>"
                      "<th>Request</th></tr>\n\n", r);
+        }
 
         for (i = 0; i < server_limit; ++i) {
             for (j = 0; j < thread_limit; ++j) {
@@ -635,7 +704,21 @@
                         ap_rputs("?STATE?", r);
                         break;
                     }
-                    
+
+                    if (show_module) {
+                        ap_rputs("] [", r);
+                        if (ws_record->short_module_index != 0) {
+                            ap_rputs(modnames[ws_record->short_module_index], r);
+                        }
+                        else {
+                            ap_rputs("_", r);
+                        }
+                    }
+                    if (show_module_state) {
+                        ap_rputs("] [", r);
+                        ap_rputs(statenames[ws_record->reserved2], r);
+                    }
+
                     ap_rprintf(r, "] "
 #ifdef HAVE_TIMES
                                "u%g s%g cu%g cs%g"
@@ -720,6 +803,21 @@
                         break;
                     }
                     
+                    if (show_module) {
+                        ap_rputs("</td><td>", r);
+                        if (ws_record->short_module_index != 0) {
+                            ap_rputs(modnames[ws_record->short_module_index], r);
+                        }
+                        else {
+                            ap_rputs("_", r);
+                        }
+                    }
+
+                    if (show_module_state) {
+                        ap_rputs("</td><td>", r);
+                        ap_rputs(statenames[ws_record->reserved2], r);
+                    }
+
                     ap_rprintf(r,
                                "\n</td>"
 #ifdef HAVE_TIMES
@@ -739,6 +837,13 @@
                     ap_rprintf(r, "</td><td>%-1.1f</td><td>%-2.2f</td><td>%-2.2f\n",
                                (float)conn_bytes / KBYTE, (float) my_bytes / MBYTE,
                                (float)bytes / MBYTE);
+
+                    if (show_module_state) {
+                        ap_rprintf(r,
+                                   "</td><td>%s",
+                                   ws_record->reserved3[0] ?
+                                   ws_record->reserved3 : "");
+                    }
                     
                     if (ws_record->status == SERVER_BUSY_READ)
                         ap_rprintf(r,
@@ -764,6 +869,7 @@
 <tr><th>PID</th><td>OS process ID</td></tr>\n \
 <tr><th>Acc</th><td>Number of accesses this connection / this child / this slot</td></tr>\n \
 <tr><th>M</th><td>Mode of operation</td></tr>\n"
+"<tr><th>Module</th><td>Module active</td></tr>\n"
 
 #ifdef HAVE_TIMES
 "<tr><th>CPU</th><td>CPU usage, number of seconds</td></tr>\n"
@@ -786,6 +892,16 @@
         }
     }
 
+    {
+        /* Run extension hooks to insert extra content. */
+        int flags = 
+            (short_report ? AP_STATUS_SHORT : 0) | 
+            (no_table_report ? AP_STATUS_NOTABLE : 0) |
+            (ap_extended_status ? AP_STATUS_EXTENDED : 0);
+        
+        ap_run_status_hook(r, flags);
+    }
+
     if (!short_report) {
         ap_rputs(ap_psignature("<hr />\n",r), r);
         ap_rputs("</body></html>\n", r);
@@ -798,6 +914,9 @@
 static int status_init(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp,
                        server_rec *s)
 {
+    module *modp;
+    int i;
+    
     status_flags[SERVER_DEAD] = '.';  /* We don't want to assume these are in */
     status_flags[SERVER_READY] = '_'; /* any particular order in scoreboard.h */
     status_flags[SERVER_STARTING] = 'S';
@@ -811,13 +930,90 @@
     status_flags[SERVER_IDLE_KILL] = 'I';
     ap_mpm_query(AP_MPMQ_HARD_LIMIT_THREADS, &thread_limit);
     ap_mpm_query(AP_MPMQ_HARD_LIMIT_DAEMONS, &server_limit);
+
+    /* map module index in scoreboard to module name */
+    for (i = 0; i < 256; i++) {
+        modnames[i] = "unknown";
+    }
+
+    for (modp = ap_top_module; modp; modp = modp->next) {
+        if (modp->module_index < 255) {
+            modnames[modp->module_index] = modp->name;
+        }
+    }
+
+    modnames[0] = ""; /* value of 0 in scoreboard means "not in non-core module";
+                       * 0 does not mean "core.c", even though that internal
+                       * module has index 0
+                       */
+    modnames[255] = "unknown"; /* any module with index >= 255 will have 255
+                                * stored in scoreboard, which indicates that
+                                * we don't know what module it is; unthinkable
+                                * to have that many modules loaded
+                                */
+
+    /* map module-specific state in scoreboard to mnemonic */
+    statenames[MODSTATUS_UNKNOWN]   = "_";
+    statenames[MODSTATUS_DNS_QUERY] = "DQ";
+    statenames[MODSTATUS_CONNECT]   = "CN";
+    statenames[MODSTATUS_SENDREQ]   = "SR";
+    statenames[MODSTATUS_SENDBODY]  = "SB";
+    statenames[MODSTATUS_WAITRSP]   = "WR";
+    statenames[MODSTATUS_READRSP]   = "RR";
+    statenames[MODSTATUS_READBODY]  = "RB";
+    for (i = 0; i < 256; i++) {
+        if (!statenames[i]) {
+            statenames[i] = apr_psprintf(p, "%d", i);
+        }
+    }
     return OK;
 }
 
+#ifdef HAVE_TIMES
+static void status_child_init(apr_pool_t *p, server_rec *s)
+{
+    child_pid = getpid();
+}
+#endif
+
+static void ihs_save_module_status(conn_rec *c, unsigned char st, char *info)
+{
+    struct ap_sb_handle_t { /* copied from scoreboard.c */
+        int child_num;
+        int thread_num;
+    };
+
+    if (ap_extended_status) {
+        worker_score *ws;
+        struct ap_sb_handle_t *sbh;
+
+        sbh = c->sbh;
+        ws = &ap_scoreboard_image->servers[sbh->child_num][sbh->thread_num];
+        ws->reserved2 = st;
+        if (info) {
+            apr_cpystrn(ws->reserved3, info, sizeof(ws->reserved3));
+        }
+        else {
+            ws->reserved3[0] = '\0';
+        }
+    }
+}
+
 static void register_hooks(apr_pool_t *p)
 {
     ap_hook_handler(status_handler, NULL, NULL, APR_HOOK_MIDDLE);
     ap_hook_post_config(status_init, NULL, NULL, APR_HOOK_MIDDLE);
+#ifdef HAVE_TIMES
+    ap_hook_child_init(status_child_init, NULL, NULL, APR_HOOK_MIDDLE);
+#endif
+    if (!memcmp(IHS_VERSION, "6.1", 3)) {
+        /* Note: Until WebSphere 6.1 testing of this optional function
+         * with WebSphere plug-in is complete, we have to keep it out
+         * of the service stream.  When testing is complete, it goes
+         * in all releases.
+         */
+        APR_REGISTER_OPTIONAL_FN(ihs_save_module_status);
+    }
 }
 
 module AP_MODULE_DECLARE_DATA status_module =
Index: modules/http/http_protocol.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/http/http_protocol.c,v
retrieving revision 1.1.1.1
retrieving revision 1.10
diff -u -u -r1.1.1.1 -r1.10
--- modules/http/http_protocol.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/http/http_protocol.c	23 Feb 2006 21:10:05 -0000	1.10
@@ -182,6 +182,11 @@
     "510 Not Extended"
 };
 
+APR_HOOK_STRUCT(
+    APR_HOOK_LINK(insert_error_filter)
+)
+
+AP_IMPLEMENT_HOOK_VOID(insert_error_filter, (request_rec *r), (r))
 
 /* The index of the first bit field that is used to index into a limit
  * bitmask. M_INVALID + 1 to METHOD_NUMBER_LAST.
@@ -1196,7 +1201,34 @@
         t_elt++;
     } while (t_elt < t_end);
 
+#if APR_CHARSET_EBCDIC
+    {
+        apr_size_t len;
+        char *tmp = apr_pstrcatv(r->pool, vec, vec_next - vec, &len);
+        ap_xlate_proto_to_ascii(tmp, len);
+        apr_brigade_write(h->bb, NULL, NULL, tmp, len);
+    }
+#else
     return apr_brigade_writev(h->bb, NULL, NULL, vec, vec_next - vec);
+#endif
+}
+
+/* Confirm that the status line is well-formed and matches r->status.
+ * Otherwise, a filter may have negated the status line set by a
+ * handler.
+ * Zap r->status_line if bad.
+ */
+static void validate_status_line(request_rec *r)
+{
+    char *end;
+
+    if (r->status_line
+        && (strlen(r->status_line) <= 4
+            || apr_strtoi64(r->status_line, &end, 10) != r->status
+            || *end != ' '
+            || (end - 3) != r->status_line)) {
+        r->status_line = NULL;
+    }
 }
 
 /*
@@ -1213,6 +1245,8 @@
         return;
     }
 
+    validate_status_line(r);
+
     if (!r->status_line) {
         r->status_line = status_lines[ap_index_of_response(r->status)];
     }
@@ -1279,10 +1313,13 @@
     h.bb = bb;
     form_header_field(&h, "Date", date);
 
-    /* keep a previously set server header (possibly from proxy), otherwise
+    /* keep the set-by-proxy server header, otherwise
      * generate a new server header */
-    if ((server = apr_table_get(r->headers_out, "Server")) != NULL) {
-        form_header_field(&h, "Server", server);
+    if (r->proxyreq != PROXYREQ_NONE) {
+        server = apr_table_get(r->headers_out, "Server");
+        if (server) {
+            form_header_field(&h, "Server", server);
+        }
     }
     else {
         form_header_field(&h, "Server", ap_get_server_version());
@@ -1841,6 +1878,8 @@
     long chunksize = 0;
     size_t chunkbits = sizeof(long) * 8;
 
+    ap_xlate_proto_from_ascii(b, strlen(b));
+
     /* Skip leading zeros */
     while (*b == '0') {
         ++b;
@@ -2295,6 +2334,8 @@
 
     r->output_filters = r->proto_output_filters;
 
+    ap_run_insert_error_filter(r);
+
     /*
      * It's possible that the Location field might be in r->err_headers_out
      * instead of r->headers_out; use the latter if possible, else the
@@ -2341,7 +2382,19 @@
         r->content_languages = NULL;
         r->content_encoding = NULL;
         r->clength = 0;
-        ap_set_content_type(r, "text/html; charset=iso-8859-1");
+        
+        if (apr_table_get(r->subprocess_env,
+                          "suppress-error-charset") != NULL) {
+            core_request_config *request_conf =
+                ap_get_module_config(r->request_config, &core_module);
+            request_conf->suppress_charset = 1; /* avoid adding default
+                                                 * charset later
+                                                 */
+            ap_set_content_type(r, "text/html");
+        }
+        else {
+            ap_set_content_type(r, "text/html; charset=iso-8859-1");
+        }
 
         if ((status == HTTP_METHOD_NOT_ALLOWED)
             || (status == HTTP_NOT_IMPLEMENTED)) {
@@ -2433,7 +2486,7 @@
 
     ml = (ap_method_list_t *) apr_palloc(p, sizeof(ap_method_list_t));
     ml->method_mask = 0;
-    ml->method_list = apr_array_make(p, sizeof(char *), nelts);
+    ml->method_list = apr_array_make(p, nelts, sizeof(char *));
     return ml;
 }
 
@@ -2861,18 +2914,35 @@
 #define MIN_LENGTH(len1, len2) ((len1 > len2) ? len2 : len1)
     request_rec *r = f->r;
     conn_rec *c = r->connection;
-    byterange_ctx *ctx = f->ctx;
+    byterange_ctx *ctx;
     apr_bucket *e;
     apr_bucket_brigade *bsend;
     apr_off_t range_start;
     apr_off_t range_end;
     char *current;
-    apr_off_t bb_length;
     apr_off_t clength = 0;
     apr_status_t rv;
     int found = 0;
 
-    if (!ctx) {
+    /* Iterate through the brigade until reaching EOS or a bucket with
+     * unknown length. */
+    for (e = APR_BRIGADE_FIRST(bb);
+         (e != APR_BRIGADE_SENTINEL(bb) && !APR_BUCKET_IS_EOS(e)
+          && e->length != (apr_size_t)-1);
+         e = APR_BUCKET_NEXT(e)) {
+        clength += e->length;
+    }
+
+    /* Don't attempt to do byte range work if this brigade doesn't
+     * contain an EOS, or if any of the buckets has an unknown length;
+     * this avoids the cases where it is expensive to perform
+     * byteranging (i.e. may require arbitrary amounts of memory). */
+    if (!APR_BUCKET_IS_EOS(e) || clength <= 0) {
+        ap_remove_output_filter(f);
+        return ap_pass_brigade(f->next, bb);
+    }
+
+    {
         int num_ranges = ap_set_byterange(r);
 
         /* We have nothing to do, get out of the way. */
@@ -2881,7 +2951,7 @@
             return ap_pass_brigade(f->next, bb);
         }
 
-        ctx = f->ctx = apr_pcalloc(r->pool, sizeof(*ctx));
+        ctx = apr_pcalloc(r->pool, sizeof(*ctx));
         ctx->num_ranges = num_ranges;
         /* create a brigade in case we never call ap_save_brigade() */
         ctx->bb = apr_brigade_create(r->pool, c->bucket_alloc);
@@ -2907,29 +2977,6 @@
             ap_xlate_proto_to_ascii(ctx->bound_head, strlen(ctx->bound_head));
         }
     }
-
-    /* We can't actually deal with byte-ranges until we have the whole brigade
-     * because the byte-ranges can be in any order, and according to the RFC,
-     * we SHOULD return the data in the same order it was requested.
-     *
-     * XXX: We really need to dump all bytes prior to the start of the earliest
-     * range, and only slurp up to the end of the latest range.  By this we
-     * mean that we should peek-ahead at the lowest first byte of any range,
-     * and the highest last byte of any range.
-     */
-    if (!APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
-        ap_save_brigade(f, &ctx->bb, &bb, r->pool);
-        return APR_SUCCESS;
-    }
-
-    /* Prepend any earlier saved brigades. */
-    APR_BRIGADE_PREPEND(bb, ctx->bb);
-
-    /* It is possible that we won't have a content length yet, so we have to
-     * compute the length before we can actually do the byterange work.
-     */
-    apr_brigade_length(bb, 1, &bb_length);
-    clength = (apr_off_t)bb_length;
 
     /* this brigade holds what we will be sending */
     bsend = apr_brigade_create(r->pool, c->bucket_alloc);
Index: modules/http/http_request.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/http/http_request.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- modules/http/http_request.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/http/http_request.c	13 Apr 2006 20:26:37 -0000	1.4
@@ -86,6 +86,7 @@
 #include "util_charset.h"
 
 #include "mod_core.h"
+#include "scoreboard.h"
 
 #if APR_HAVE_STDARG_H
 #include <stdarg.h>
@@ -281,6 +282,8 @@
      * Use this hook with extreme care and only if you know what you are 
      * doing.
      */
+    if (ap_extended_status)
+        ap_time_process_request(r->connection->sbh, START_PREQUEST);
     access_status = ap_run_quick_handler(r, 0);  /* Not a look-up request */
     if (access_status == DECLINED) {
         access_status = ap_process_request_internal(r);
@@ -309,7 +312,10 @@
      * it's the application that's stalled.
      */
     check_pipeline_flush(r);
-    ap_run_log_transaction(r);
+    ap_update_child_status(r->connection->sbh, SERVER_BUSY_LOG, r);
+    ihs_run_log_transaction(r);
+    if (ap_extended_status)
+        ap_time_process_request(r->connection->sbh, STOP_PREQUEST);
 }
 
 static apr_table_t *rename_original_env(apr_pool_t *p, apr_table_t *t)
Index: modules/loggers/mod_log_config.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/loggers/mod_log_config.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- modules/loggers/mod_log_config.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/loggers/mod_log_config.c	1 Feb 2005 18:10:22 -0000	1.4
@@ -187,6 +187,7 @@
 #include "apr_lib.h"
 #include "apr_hash.h"
 #include "apr_optional.h"
+#include "apr_anylock.h"
 
 #define APR_WANT_STRFUNC
 #include "apr_want.h"
@@ -199,6 +200,7 @@
 #include "http_log.h"
 #include "http_protocol.h"
 #include "util_time.h"
+#include "ap_mpm.h"
 
 #if APR_HAVE_UNISTD_H
 #include <unistd.h>
@@ -211,8 +213,11 @@
 
 module AP_MODULE_DECLARE_DATA log_config_module;
 
+#ifndef APR_LARGEFILE
+#define APR_LARGEFILE 0
+#endif
 
-static int xfer_flags = (APR_WRITE | APR_APPEND | APR_CREATE);
+static int xfer_flags = (APR_WRITE | APR_APPEND | APR_CREATE | APR_LARGEFILE);
 static apr_fileperms_t xfer_perms = APR_OS_DEFAULT;
 static apr_hash_t *log_hash;
 static apr_status_t ap_default_log_writer(request_rec *r,
@@ -237,6 +242,7 @@
 static ap_log_writer *log_writer = ap_default_log_writer;
 static ap_log_writer_init *log_writer_init = ap_default_log_writer_init;
 static int buffered_logs = 0; /* default unbuffered */
+static apr_array_header_t *all_buffered_logs = NULL;
 
 /* POSIX.1 defines PIPE_BUF as the maximum number of bytes that is
  * guaranteed to be atomic when writing a pipe.  And PIPE_BUF >= 512
@@ -290,6 +296,7 @@
     apr_file_t *handle;
     apr_size_t outcnt;
     char outbuf[LOG_BUFSIZE];
+    apr_anylock_t mutex;
 } buffered_log;
 
 typedef struct {
@@ -418,7 +425,7 @@
 
 static const char *clf_log_bytes_sent(request_rec *r, char *a)
 {
-    if (!r->sent_bodyct) {
+    if (!r->sent_bodyct || !r->bytes_sent) {
         return "-";
     }
     else {
@@ -428,7 +435,7 @@
 
 static const char *log_bytes_sent(request_rec *r, char *a)
 {
-    if (!r->sent_bodyct) {
+    if (!r->sent_bodyct || !r->bytes_sent) {
         return "0";
     }
     else {
@@ -1080,8 +1087,10 @@
 static const char *set_buffered_logs_on(cmd_parms *parms, void *dummy, int flag)
 {
     buffered_logs = flag;
-    ap_log_set_writer_init(ap_buffered_log_writer_init);
-    ap_log_set_writer(ap_buffered_log_writer);
+    if (buffered_logs) {
+        ap_log_set_writer_init(ap_buffered_log_writer_init);
+        ap_log_set_writer(ap_buffered_log_writer);
+    }
     return NULL;
 }
 static const command_rec config_log_cmds[] =
@@ -1215,10 +1224,17 @@
 
 static int init_config_log(apr_pool_t *pc, apr_pool_t *p, apr_pool_t *pt, server_rec *s)
 {
-    /* First, do "physical" server, which gets default log fd and format
+    int res;
+
+    /* First init the buffered logs array, which is needed when opening the logs. */
+    if (buffered_logs) {
+        all_buffered_logs = apr_array_make(p, 5, sizeof(buffered_log *));
+    }
+
+    /* Next, do "physical" server, which gets default log fd and format
      * for the virtual servers, if they don't override...
      */
-    int res = open_multi_logs(s, p);
+    res = open_multi_logs(s, p);
 
     /* Then, virtual servers */
 
@@ -1231,9 +1247,41 @@
 
 static void init_child(apr_pool_t *p, server_rec *s)
 {
+    int mpm_threads;
+
+    ap_mpm_query(AP_MPMQ_MAX_THREADS, &mpm_threads);
+
     /* Now register the last buffer flush with the cleanup engine */
     if (buffered_logs) {
+        int i;
+        buffered_log **array = (buffered_log **)all_buffered_logs->elts;
+        
         apr_pool_cleanup_register(p, s, flush_all_logs, flush_all_logs);
+
+        for (i = 0; i < all_buffered_logs->nelts; i++) {
+            buffered_log *this = array[i];
+            
+#if APR_HAS_THREADS
+            if (mpm_threads > 1) {
+                apr_status_t rv;
+
+                this->mutex.type = apr_anylock_threadmutex;
+                rv = apr_thread_mutex_create(&this->mutex.lock.tm,
+                                             APR_THREAD_MUTEX_DEFAULT,
+                                             p);
+                if (rv != APR_SUCCESS) {
+                    ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s,
+                                 "could not initialize buffered log mutex, "
+                                 "transfer log may become corrupted");
+                    this->mutex.type = apr_anylock_none;
+                }
+            }
+            else
+#endif
+            {
+                this->mutex.type = apr_anylock_none;
+            }
+        }
     }
 }
 
@@ -1315,12 +1363,13 @@
                                         const char* name)
 {
     buffered_log *b;
-    b = apr_palloc(p, sizeof(buffered_log));
+    b = apr_pcalloc(p, sizeof(buffered_log));
     b->handle = ap_default_log_writer_init(p, s, name);
-    b->outcnt = 0;
     
-    if (b->handle)
+    if (b->handle) {
+        *(buffered_log **)apr_array_push(all_buffered_logs) = b;
         return b;
+    }
     else
         return NULL;
 }
@@ -1338,6 +1387,9 @@
     apr_status_t rv;
     buffered_log *buf = (buffered_log*)handle;
 
+    if ((rv = APR_ANYLOCK_LOCK(&buf->mutex)) != APR_SUCCESS) {
+        return rv;
+    }
 
     if (len + buf->outcnt > LOG_BUFSIZE) {
         flush_log(buf);
@@ -1362,6 +1414,8 @@
         buf->outcnt += len;
         rv = APR_SUCCESS;
     }
+
+    APR_ANYLOCK_UNLOCK(&buf->mutex);
     return rv;
 }
 
Index: modules/mappers/mod_alias.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/mappers/mod_alias.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/mappers/mod_alias.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/mappers/mod_alias.c	5 Mar 2004 17:56:28 -0000	1.2
@@ -328,7 +328,7 @@
                             int doesc, int *status)
 {
     alias_entry *entries = (alias_entry *) aliases->elts;
-    regmatch_t regm[10];
+    regmatch_t regm[AP_MAX_REG_MATCH];
     char *found = NULL;
     int i;
 
@@ -337,11 +337,10 @@
         int l;
 
         if (p->regexp) {
-            if (!ap_regexec(p->regexp, r->uri, p->regexp->re_nsub + 1, regm,
-                            0)) {
+            if (!ap_regexec(p->regexp, r->uri, AP_MAX_REG_MATCH, regm, 0)) {
                 if (p->real) {
                     found = ap_pregsub(r->pool, p->real, r->uri,
-                                    p->regexp->re_nsub + 1, regm);
+                                       AP_MAX_REG_MATCH, regm);
                     if (found && doesc) {
                         apr_uri_t uri;
                         apr_uri_parse(r->pool, found, &uri);
Index: modules/mappers/mod_imap.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/mappers/mod_imap.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/mappers/mod_imap.c	29 Jul 2003 20:19:21 -0000	1.1.1.1
+++ modules/mappers/mod_imap.c	12 Dec 2005 17:39:17 -0000	1.2
@@ -384,7 +384,7 @@
     if (!strcasecmp(value, "referer")) {
         referer = apr_table_get(r->headers_in, "Referer");
         if (referer && *referer) {
-	    return apr_pstrdup(r->pool, referer);
+            return ap_escape_html(r->pool, referer);
         }
         else {
 	    /* XXX:  This used to do *value = '\0'; ... which is totally bogus
Index: modules/mappers/mod_rewrite.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/mappers/mod_rewrite.c,v
retrieving revision 1.1.1.1
retrieving revision 1.6
diff -u -u -r1.1.1.1 -r1.6
--- modules/mappers/mod_rewrite.c	29 Jul 2003 20:19:22 -0000	1.1.1.1
+++ modules/mappers/mod_rewrite.c	3 May 2005 11:37:22 -0000	1.6
@@ -1445,9 +1445,17 @@
      *  remember the current filename before rewriting for later check
      *  to prevent deadlooping because of internal redirects
      *  on final URL/filename which can be equal to the inital one.
+     *  also, we'll restore original r->filename if we decline this
+     *  request
      */
     ofilename = r->filename;
 
+    if (r->filename == NULL) {
+        r->filename = apr_pstrdup(r->pool, r->uri);
+        rewritelog(r, 2, "init rewrite engine with requested uri %s",
+                   r->filename);
+    }
+
     /*
      *  now apply the rules ...
      */
@@ -1597,7 +1605,7 @@
              * use the following internal redirection stuff because
              * this would lead to a deadloop.
              */
-            if (strcmp(r->filename, ofilename) == 0) {
+            if (ofilename != NULL && strcmp(r->filename, ofilename) == 0) {
                 rewritelog(r, 1, "[per-dir %s] initial URL equal rewritten "
                            "URL: %s [IGNORING REWRITE]",
                            dconf->directory, r->filename);
@@ -1654,6 +1662,7 @@
     else {
         rewritelog(r, 1, "[per-dir %s] pass through %s",
                    dconf->directory, r->filename);
+        r->filename = ofilename;
         return DECLINED;
     }
 }
@@ -1902,10 +1911,9 @@
     const char *vary;
     char newuri[MAX_STRING_LEN];
     regex_t *regexp;
-    regmatch_t regmatch[MAX_NMATCH];
+    regmatch_t regmatch[AP_MAX_REG_MATCH];
     backrefinfo *briRR = NULL;
     backrefinfo *briRC = NULL;
-    int prefixstrip;
     int failed;
     apr_array_header_t *rewriteconds;
     rewritecond_entry *conds;
@@ -1936,14 +1944,12 @@
      *  the local part.  Additionally indicate this special
      *  threatment in the logfile.
      */
-    prefixstrip = 0;
-    if (perdir != NULL) {
+    if (perdir) {
         if (   strlen(uri) >= strlen(perdir)
             && strncmp(uri, perdir, strlen(perdir)) == 0) {
             rewritelog(r, 3, "[per-dir %s] strip per-dir prefix: %s -> %s",
                        perdir, uri, uri+strlen(perdir));
             uri = uri+strlen(perdir);
-            prefixstrip = 1;
         }
     }
 
@@ -1959,7 +1965,7 @@
         rewritelog(r, 3, "[per-dir %s] applying pattern '%s' to uri '%s'",
                    perdir, p->pattern, uri);
     }
-    rc = (ap_regexec(regexp, uri, regexp->re_nsub+1, regmatch, 0) == 0);
+    rc = (ap_regexec(regexp, uri, AP_MAX_REG_MATCH, regmatch, 0) == 0);
     if (! (( rc && !(p->flags & RULEFLAG_NOTMATCH)) ||
            (!rc &&  (p->flags & RULEFLAG_NOTMATCH))   ) ) {
         return 0;
@@ -2139,8 +2145,7 @@
      *   location, i.e. if it's not an absolute URL (!) path nor
      *   a fully qualified URL scheme.
      */
-    if (prefixstrip && *r->filename != '/'
-                    && !is_absolute_uri(r->filename)) {
+    if (perdir && *r->filename != '/' && !is_absolute_uri(r->filename)) {
         rewritelog(r, 3, "[per-dir %s] add per-dir prefix: %s -> %s%s",
                    perdir, r->filename, perdir, r->filename);
         r->filename = apr_pstrcat(r->pool, perdir, r->filename, NULL);
@@ -2255,7 +2260,7 @@
     char input[MAX_STRING_LEN];
     apr_finfo_t sb;
     request_rec *rsub;
-    regmatch_t regmatch[MAX_NMATCH];
+    regmatch_t regmatch[AP_MAX_REG_MATCH];
     int rc;
 
     /*
@@ -2360,8 +2365,7 @@
     }
     else {
         /* it is really a regexp pattern, so apply it */
-        rc = (ap_regexec(p->regexp, input,
-                         p->regexp->re_nsub+1, regmatch,0) == 0);
+        rc = (ap_regexec(p->regexp, input, AP_MAX_REG_MATCH, regmatch,0) == 0);
 
         /* if it isn't a negated pattern and really matched
            we update the passed-through regex subst info structure */
@@ -2520,7 +2524,7 @@
                 bri = briRC;
             }
             /* see ap_pregsub() in src/main/util.c */
-            if (bri && n <= bri->nsub
+            if (bri && n < AP_MAX_REG_MATCH
                 && bri->regmatch[n].rm_eo > bri->regmatch[n].rm_so) {
                 span = bri->regmatch[n].rm_eo - bri->regmatch[n].rm_so;
                 if (span > space) {
@@ -3118,7 +3122,7 @@
     char *curkey;
     char *curval;
 
-    rc = apr_file_open(&fp, file, APR_READ, APR_OS_DEFAULT, r->pool);
+    rc = apr_file_open(&fp, file, APR_READ|APR_BUFFERED, APR_OS_DEFAULT, r->pool);
     if (rc != APR_SUCCESS) {
        return NULL;
     }
@@ -4009,7 +4013,7 @@
             return NULL;
         }
     }
-    return apr_pstrdup(c->pool, ce->value);
+    return ce->value;
 }
 
 static int cache_tlb_hash(char *key)
Index: modules/mappers/mod_rewrite.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/mappers/mod_rewrite.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/mappers/mod_rewrite.h	29 Jul 2003 20:19:22 -0000	1.1.1.1
+++ modules/mappers/mod_rewrite.h	5 Mar 2004 17:56:28 -0000	1.2
@@ -210,8 +210,6 @@
 /*** max cookie size in rfc 2109 ***/
 #define MAX_COOKIE_LEN 4096
 
-#define MAX_NMATCH    10
-
 /* default maximum number of internal redirects */
 #define REWRITE_REDIRECT_LIMIT 10
 
@@ -333,7 +331,7 @@
 typedef struct backrefinfo {
     char *source;
     int nsub;
-    regmatch_t regmatch[10];
+    regmatch_t regmatch[AP_MAX_REG_MATCH];
 } backrefinfo;
 
 
Index: modules/mappers/mod_speling.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/mappers/mod_speling.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/mappers/mod_speling.c	29 Jul 2003 20:19:22 -0000	1.1.1.1
+++ modules/mappers/mod_speling.c	12 Jan 2006 20:13:26 -0000	1.2
@@ -264,6 +264,11 @@
         return DECLINED;
     }
 
+    /* This is not for a file - don't mess with it */
+    if (!r->filename) {
+        return DECLINED;
+    }
+
     /*
      * The request should end up looking like this:
      * r->uri: /correct-url/mispelling/more
Index: modules/mappers/mod_userdir.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/mappers/mod_userdir.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/mappers/mod_userdir.c	29 Jul 2003 20:19:22 -0000	1.1.1.1
+++ modules/mappers/mod_userdir.c	4 May 2005 13:46:55 -0000	1.2
@@ -372,7 +372,7 @@
         return NULL;
     }
 
-    if ((ugid = apr_palloc(r->pool, sizeof(ap_unix_identity_t *))) == NULL) {
+    if ((ugid = apr_palloc(r->pool, sizeof(*ugid))) == NULL) {
         return NULL;
     }
 
Index: modules/metadata/mod_expires.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/metadata/mod_expires.c,v
retrieving revision 1.1.1.1
retrieving revision 1.5
diff -u -u -r1.1.1.1 -r1.5
--- modules/metadata/mod_expires.c	29 Jul 2003 20:19:22 -0000	1.1.1.1
+++ modules/metadata/mod_expires.c	24 Sep 2004 14:25:38 -0000	1.5
@@ -205,6 +205,7 @@
 #include "http_config.h"
 #include "http_log.h"
 #include "http_request.h"
+#include "http_protocol.h"
 
 typedef struct {
     int active;
@@ -227,7 +228,7 @@
     expires_dir_config *new =
     (expires_dir_config *) apr_pcalloc(p, sizeof(expires_dir_config));
     new->active = ACTIVE_DONTCARE;
-    new->expiresdefault = "";
+    new->expiresdefault = NULL;
     new->expiresbytype = apr_table_make(p, 4);
     return (void *) new;
 }
@@ -404,7 +405,7 @@
         new->active = add->active;
     }
 
-    if (add->expiresdefault[0] != '\0') {
+    if (add->expiresdefault != NULL) {
         new->expiresdefault = add->expiresdefault;
     }
     else {
@@ -546,8 +547,12 @@
 }
 static void register_hooks(apr_pool_t *p)
 {
+    /* mod_expires needs to run *before* the cache save filter which is
+     * AP_FTYPE_CONTENT_SET-1.  Otherwise, our expires won't be honored.
+     */
     ap_register_output_filter("MOD_EXPIRES", expires_filter, NULL,
-                              AP_FTYPE_CONTENT_SET);
+                              AP_FTYPE_CONTENT_SET-2);
+    ap_hook_insert_error_filter(expires_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
     ap_hook_insert_filter(expires_insert_filter, NULL, NULL, APR_HOOK_MIDDLE);
 }
 
Index: modules/metadata/mod_headers.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/metadata/mod_headers.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- modules/metadata/mod_headers.c	29 Jul 2003 20:19:22 -0000	1.1.1.1
+++ modules/metadata/mod_headers.c	7 Sep 2004 21:06:45 -0000	1.3
@@ -119,6 +119,7 @@
 #include "http_request.h"
 #include "http_log.h"
 #include "util_filter.h"
+#include "http_protocol.h" /* ap_hook_insert_error_filter */
 
 /* format_tag_hash is initialized during pre-config */
 static apr_hash_t *format_tag_hash;
@@ -131,10 +132,12 @@
     hdr_echo = 'e'              /* echo headers from request to response */
 } hdr_actions;
 
-typedef enum {
-    hdr_in = 0,                 /* RequestHeader */
-    hdr_out = 1                 /* Header */
-} hdr_inout;
+/*
+ * magic cmd->info values
+ */
+static char hdr_in  = '0';  /* RequestHeader */
+static char hdr_out = '1';  /* Header onsuccess */
+static char hdr_err = '2';  /* Header always */
 
 /*
  * There is an array of struct format_tag per Header/RequestHeader 
@@ -169,6 +172,7 @@
 typedef struct {
     apr_array_header_t *fixup_in;
     apr_array_header_t *fixup_out;
+    apr_array_header_t *fixup_err;
 } headers_conf;
 
 module AP_MODULE_DECLARE_DATA headers_module;
@@ -201,29 +205,26 @@
 /*
  * Config routines
  */
-static void *create_headers_config(apr_pool_t *p, server_rec *s)
+static void *create_headers_config(apr_pool_t *p, char *dummy)
 {
-    headers_conf *conf = apr_pcalloc(p, sizeof(*conf));
+    headers_conf *conf = apr_palloc(p, sizeof(*conf));
 
     conf->fixup_in = apr_array_make(p, 2, sizeof(header_entry));
     conf->fixup_out = apr_array_make(p, 2, sizeof(header_entry));
+    conf->fixup_err = apr_array_make(p, 2, sizeof(header_entry));
 
     return conf;
 }
 
-static void *create_headers_dir_config(apr_pool_t *p, char *d)
-{
-    return create_headers_config(p, NULL);
-}
-
 static void *merge_headers_config(apr_pool_t *p, void *basev, void *overridesv)
 {
-    headers_conf *newconf = apr_pcalloc(p, sizeof(*newconf));
+    headers_conf *newconf = apr_palloc(p, sizeof(*newconf));
     headers_conf *base = basev;
     headers_conf *overrides = overridesv;
 
     newconf->fixup_in = apr_array_append(p, base->fixup_in, overrides->fixup_in);
     newconf->fixup_out = apr_array_append(p, base->fixup_out, overrides->fixup_out);
+    newconf->fixup_err = apr_array_append(p, base->fixup_err, overrides->fixup_err);
 
     return newconf;
 }
@@ -351,7 +352,7 @@
 }
 
 /* handle RequestHeader and Header directive */
-static const char *header_inout_cmd(hdr_inout inout, cmd_parms *cmd, void *indirconf,
+static const char *header_inout_cmd(cmd_parms *cmd, void *indirconf,
                               const char *action, const char *inhdr,
                               const char *value, const char* envclause)
 {
@@ -360,16 +361,12 @@
     char *colon;
     char *hdr = apr_pstrdup(cmd->pool, inhdr);
     header_entry *new;
-    server_rec *s = cmd->server;
-    headers_conf *serverconf = ap_get_module_config(s->module_config,
-                                                    &headers_module);
+    apr_array_header_t *fixup = (cmd->info == &hdr_in)
+        ? dirconf->fixup_in   : (cmd->info == &hdr_err)
+        ? dirconf->fixup_err
+        : dirconf->fixup_out;
 
-    if (cmd->path) {
-        new = (header_entry *) apr_array_push((hdr_in == inout) ? dirconf->fixup_in : dirconf->fixup_out);
-    }
-    else {
-        new = (header_entry *) apr_array_push((hdr_in == inout) ? serverconf->fixup_in : serverconf->fixup_out);
-    }
+    new = (header_entry *) apr_array_push(fixup);
 
     if (!strcasecmp(action, "set"))
         new->action = hdr_set;
@@ -392,7 +389,7 @@
         regex_t *regex;
         if (value)
             return "Header echo takes two arguments";
-        else if (inout != hdr_out)
+        else if (cmd->info == &hdr_in)
             return "Header echo only valid on Header directive";
         else {
             regex = ap_pregcomp(cmd->pool, hdr, REG_EXTENDED | REG_NOSUB);
@@ -407,9 +404,6 @@
 
     /* Handle the envclause on Header */
     if (envclause != NULL) {
-        if (inout != hdr_out) {
-            return "error: envclause (env=...) only valid on Header directive";
-        }
         if (strncasecmp(envclause, "env=", 4) != 0) {
             return "error: envclause should be in the form env=envar";
         }
@@ -429,7 +423,7 @@
     return parse_format_string(cmd->pool, new, value);
 }
 
-/* Handle Header directive */
+/* Handle all (xxx)Header directives */
 static const char *header_cmd(cmd_parms *cmd, void *indirconf,
                               const char *args)
 {
@@ -441,19 +435,25 @@
 
     s = apr_pstrdup(cmd->pool, args);
     action = ap_getword_conf(cmd->pool, &s);
+    if (cmd->info == &hdr_out) {
+        if (!strcasecmp(action, "always")) {
+            cmd->info = &hdr_err;
+            action = ap_getword_conf(cmd->pool, &s);
+        }
+        else if (!strcasecmp(action, "onsuccess")) {
+            action = ap_getword_conf(cmd->pool, &s);
+        }
+    }
     hdr = ap_getword_conf(cmd->pool, &s);
     val = *s ? ap_getword_conf(cmd->pool, &s) : NULL;
     envclause = *s ? ap_getword_conf(cmd->pool, &s) : NULL;
 
-    return header_inout_cmd(hdr_out, cmd, indirconf, action, hdr, val, envclause);
-}
+    if (*s) {
+        return apr_pstrcat(cmd->pool, cmd->cmd->name,
+                           " has too many arguments", NULL);
+    }
 
-/* handle RequestHeader directive */
-static const char *request_header_cmd(cmd_parms *cmd, void *indirconf,
-                              const char *action, const char *inhdr,
-                              const char *value)
-{
-    return header_inout_cmd(hdr_in, cmd, indirconf, action, inhdr, value, NULL);
+    return header_inout_cmd(cmd, indirconf, action, hdr, val, envclause);
 }
 
 /*
@@ -478,7 +478,7 @@
         else
             str = apr_pstrcat(r->pool, str, s, NULL);
     }
-    return str;
+    return str ? str : "";
 }
 
 static int echo_header(echo_do *v, const char *key, const char *val)
@@ -493,11 +493,10 @@
     return 1;
 }
 
-static void do_headers_fixup(request_rec *r, hdr_inout inout,
+static void do_headers_fixup(request_rec *r, apr_table_t *headers,
                              apr_array_header_t *fixup)
 {
     int i;
-    apr_table_t *headers = (hdr_in == inout) ? r->headers_in : r->headers_out;
 
     for (i = 0; i < fixup->nelts; ++i) {
         header_entry *hdr = &((header_entry *) (fixup->elts))[i];
@@ -543,21 +542,27 @@
 
 static void ap_headers_insert_output_filter(request_rec *r)
 {
-    headers_conf *serverconf = ap_get_module_config(r->server->module_config,
-                                                    &headers_module);
     headers_conf *dirconf = ap_get_module_config(r->per_dir_config,
                                                  &headers_module);
 
-    if (serverconf->fixup_out->nelts || dirconf->fixup_out->nelts) {
+    if (dirconf->fixup_out->nelts || dirconf->fixup_err->nelts) {
         ap_add_output_filter("FIXUP_HEADERS_OUT", NULL, r, r->connection);
     }
 }
 
+static void ap_headers_insert_error_filter(request_rec *r)
+{
+    headers_conf *dirconf = ap_get_module_config(r->per_dir_config,
+                                                 &headers_module);
+
+    if (dirconf->fixup_err->nelts) {
+        ap_add_output_filter("FIXUP_HEADERS_ERR", NULL, r, r->connection);
+    }
+}
+
 static apr_status_t ap_headers_output_filter(ap_filter_t *f,
                                              apr_bucket_brigade *in)
 {
-    headers_conf *serverconf = ap_get_module_config(f->r->server->module_config,
-                                                    &headers_module);
     headers_conf *dirconf = ap_get_module_config(f->r->per_dir_config,
                                                  &headers_module);
 
@@ -565,8 +570,27 @@
                  "headers: ap_headers_output_filter()");
 
     /* do the fixup */
-    do_headers_fixup(f->r, hdr_out, serverconf->fixup_out);
-    do_headers_fixup(f->r, hdr_out, dirconf->fixup_out);
+    do_headers_fixup(f->r, f->r->err_headers_out, dirconf->fixup_err);
+    do_headers_fixup(f->r, f->r->headers_out, dirconf->fixup_out);
+
+    /* remove ourselves from the filter chain */
+    ap_remove_output_filter(f);
+
+    /* send the data up the stack */
+    return ap_pass_brigade(f->next,in);
+}
+
+static apr_status_t ap_headers_error_filter(ap_filter_t *f,
+                                            apr_bucket_brigade *in)
+{
+    headers_conf *dirconf = ap_get_module_config(f->r->per_dir_config,
+                                                 &headers_module);
+
+    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, f->r->server,
+                 "headers: ap_headers_error_filter()");
+
+    /* do the fixup */
+    do_headers_fixup(f->r, f->r->err_headers_out, dirconf->fixup_err);
 
     /* remove ourselves from the filter chain */
     ap_remove_output_filter(f);
@@ -577,15 +601,12 @@
 
 static apr_status_t ap_headers_fixup(request_rec *r)
 {
-    headers_conf *serverconf = ap_get_module_config(r->server->module_config,
-                                                    &headers_module);
     headers_conf *dirconf = ap_get_module_config(r->per_dir_config,
                                                  &headers_module);
 
     /* do the fixup */
-    if (serverconf->fixup_in->nelts || dirconf->fixup_in->nelts) {
-        do_headers_fixup(r, hdr_in, serverconf->fixup_in);
-        do_headers_fixup(r, hdr_in, dirconf->fixup_in);
+    if (dirconf->fixup_in->nelts) {
+        do_headers_fixup(r, r->headers_in, dirconf->fixup_in);
     }
 
     return DECLINED;
@@ -593,9 +614,10 @@
                                         
 static const command_rec headers_cmds[] =
 {
-    AP_INIT_RAW_ARGS("Header", header_cmd, NULL, OR_FILEINFO,
-                   "an action, header and value followed by optional env clause"),
-    AP_INIT_TAKE23("RequestHeader", request_header_cmd, NULL, OR_FILEINFO,
+    AP_INIT_RAW_ARGS("Header", header_cmd, &hdr_out, OR_FILEINFO,
+                   "an optional condition, an action, header and value "
+                   "followed by optional env clause"),
+    AP_INIT_RAW_ARGS("RequestHeader", header_cmd, &hdr_in, OR_FILEINFO,
                    "an action, header and value"),
     {NULL}
 };
@@ -620,18 +642,21 @@
 {
     ap_hook_pre_config(header_pre_config,NULL,NULL,APR_HOOK_MIDDLE);
     ap_hook_insert_filter(ap_headers_insert_output_filter, NULL, NULL, APR_HOOK_LAST);
+    ap_hook_insert_error_filter(ap_headers_insert_error_filter, NULL, NULL, APR_HOOK_LAST);
     ap_hook_fixups(ap_headers_fixup, NULL, NULL, APR_HOOK_LAST);
     ap_register_output_filter("FIXUP_HEADERS_OUT", ap_headers_output_filter,
                               NULL, AP_FTYPE_CONTENT_SET);
+    ap_register_output_filter("FIXUP_HEADERS_ERR", ap_headers_error_filter,
+                              NULL, AP_FTYPE_CONTENT_SET);
 }
 
 module AP_MODULE_DECLARE_DATA headers_module =
 {
     STANDARD20_MODULE_STUFF,
-    create_headers_dir_config,  /* dir config creater */
+    create_headers_config,      /* dir config creater */
     merge_headers_config,       /* dir merger --- default is to override */
-    create_headers_config,      /* server config */
-    merge_headers_config,       /* merge server configs */
+    NULL,                       /* server config */
+    NULL,                       /* merge server configs */
     headers_cmds,               /* command apr_table_t */
-    register_hooks		/* register hooks */
+    register_hooks              /* register hooks */
 };
Index: modules/metadata/mod_mime_magic.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/metadata/mod_mime_magic.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- modules/metadata/mod_mime_magic.c	29 Jul 2003 20:19:22 -0000	1.1.1.1
+++ modules/metadata/mod_mime_magic.c	1 Oct 2005 01:22:05 -0000	1.3
@@ -989,11 +989,16 @@
     /* parse it */
     for (lineno = 1; apr_file_gets(line, BUFSIZ, f) == APR_SUCCESS; lineno++) {
 	int ws_offset;
+        char *last = line + strlen(line) - 1; /* guaranteed that len >= 1 */
 
-	/* delete newline */
-	if (line[0]) {
-	    line[strlen(line) - 1] = '\0';
-	}
+	/* delete newline and potential carriage return */
+        if (*last == '\n') {
+            *last = '\0';
+            --last;
+        }
+        if (last >= line && *last == '\r') {
+            *last = '\0';
+        }
 
 	/* skip leading whitespace */
 	ws_offset = 0;
Index: modules/metadata/mod_setenvif.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/metadata/mod_setenvif.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- modules/metadata/mod_setenvif.c	29 Jul 2003 20:19:22 -0000	1.1.1.1
+++ modules/metadata/mod_setenvif.c	10 Mar 2004 21:32:14 -0000	1.2
@@ -239,29 +239,39 @@
     int in_escape = 0;
 
     while (*src) {
-        if (in_escape) {
-            in_escape = 0;
-        }
-        else {
-            switch (*src) {
-            case '^':
-            case '.':
-            case '$':
-            case '|':
-            case '(':
-            case ')':
-            case '[':
-            case ']':
-            case '*':
-            case '+':
-            case '?':
-            case '{':
-            case '}':
+        switch (*src) {
+        case '^':
+        case '.':
+        case '$':
+        case '|':
+        case '(':
+        case ')':
+        case '[':
+        case ']':
+        case '*':
+        case '+':
+        case '?':
+        case '{':
+        case '}':
+            if (!in_escape) {
                 return NULL;
-            case '\\':
+            }
+            in_escape = 0;
+            break;
+        case '\\':
+            if (!in_escape) {
                 in_escape = 1;
                 escapes_found = 1;
             }
+            else {
+                in_escape = 0;
+            }
+            break;
+        default:
+            if (in_escape) {
+                return NULL;
+            }
+            break;
         }
         src++;
     }
Index: modules/proxy/proxy_ftp.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/proxy/proxy_ftp.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- modules/proxy/proxy_ftp.c	29 Jul 2003 20:19:22 -0000	1.1.1.1
+++ modules/proxy/proxy_ftp.c	1 Jun 2005 12:40:57 -0000	1.4
@@ -248,6 +248,9 @@
     else
         sport[0] = '\0';
 
+    if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
+        host = apr_pstrcat(p, "[", host, "]", NULL);
+    }
     r->filename = apr_pstrcat(p, "proxy:ftp://", (user != NULL) ? user : "",
                               (password != NULL) ? ":" : "",
                               (password != NULL) ? password : "",
@@ -319,6 +322,10 @@
     }    state;
 }      proxy_dir_ctx_t;
 
+/* fallback regex for ls -s1;  ($0..$2) == 3 */
+#define LS_REG_PATTERN "^ *([0-9]+) +([^ ]+)$"
+#define LS_REG_MATCH   3
+
 apr_status_t ap_proxy_send_dir_filter(ap_filter_t *f, apr_bucket_brigade *in)
 {
     request_rec *r = f->r;
@@ -462,10 +469,10 @@
         int eos = 0;
 
         regex_t *re = NULL;
-        regmatch_t re_result[3];
+        regmatch_t re_result[LS_REG_MATCH];
 
         /* Compile the output format of "ls -s1" as a fallback for non-unix ftp listings */
-        re = ap_pregcomp(p, "^ *([0-9]+) +([^ ]+)$", REG_EXTENDED);
+        re = ap_pregcomp(p, LS_REG_PATTERN, REG_EXTENDED);
 
         /* get a complete line */
         /* if the buffer overruns - throw data away */
@@ -581,7 +588,7 @@
             }
         }
         /* Try a fallback for listings in the format of "ls -s1" */
-        else if (0 == ap_regexec(re, ctx->buffer, 3, re_result, 0)) {
+        else if (0 == ap_regexec(re, ctx->buffer, LS_REG_MATCH, re_result, 0)) {
 
             filename = apr_pstrndup(p, &ctx->buffer[re_result[2].rm_so], re_result[2].rm_eo - re_result[2].rm_so);
 
@@ -1863,7 +1870,8 @@
             }
 
             /* try send what we read */
-            if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS) {
+            if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
+                || c->aborted) {
                 /* Ack! Phbtt! Die! User aborted! */
                 finish = TRUE;
             }
Index: modules/proxy/proxy_http.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/proxy/proxy_http.c,v
retrieving revision 1.1.1.1
retrieving revision 1.11
diff -u -u -r1.1.1.1 -r1.11
--- modules/proxy/proxy_http.c	29 Jul 2003 20:19:23 -0000	1.1.1.1
+++ modules/proxy/proxy_http.c	23 Jun 2005 20:57:15 -0000	1.11
@@ -114,8 +114,12 @@
      */
     port = def_port;
     err = ap_proxy_canon_netloc(r->pool, &url, NULL, NULL, &host, &port);
-    if (err)
+    if (err) {
+        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
+                      "error parsing URL %s: %s",
+                      url, err);
         return HTTP_BAD_REQUEST;
+    }
 
     /* now parse path/search args, according to rfc1738 */
     /* N.B. if this isn't a true proxy request, then the URL _path_
@@ -140,6 +144,9 @@
     else
         sport[0] = '\0';
 
+    if (ap_strchr_c(host, ':')) { /* if literal IPv6 address */
+        host = apr_pstrcat(r->pool, "[", host, "]", NULL);
+    }
     r->filename = apr_pstrcat(r->pool, "proxy:", scheme, "://", host, sport, 
             "/", path, (search) ? "?" : "", (search) ? search : "", NULL);
     return OK;
@@ -279,7 +286,7 @@
                                              proxy_conn_rec *backend,
                                              proxy_server_conf *conf,
                                              const char *proxyname) {
-    int failed=0, new=0;
+    int failed=0, new=0, rc;
     apr_socket_t *client_socket = NULL;
 
     /* We have determined who to connect to. Now make the connection, supporting
@@ -334,8 +341,8 @@
         /* put back old timeout */
         apr_socket_timeout_set(p_conn->sock, current_timeout);
         if ( APR_STATUS_IS_EOF(socket_status) ) {
-            ap_log_error(APLOG_MARK, APLOG_ERR, 0, NULL,
-                         "proxy: HTTP: previous connection is closed");
+            ap_log_error(APLOG_MARK, APLOG_INFO, 0, NULL,
+                         "proxy: previous connection is closed, creating a new connection.");
             new = 1;
         }
     }
@@ -406,11 +413,494 @@
                      p_conn->addr, p_conn->name);
 
         /* set up the connection filters */
-        ap_run_pre_connection(*origin, p_conn->sock);
+        rc = ap_run_pre_connection(*origin, p_conn->sock);
+        if (rc != OK && rc != DONE) {
+            (*origin)->aborted = 1;
+            apr_socket_close(p_conn->sock);
+            backend->connection = NULL;
+            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
+                         "proxy: HTTP: pre_connection setup failed (%d)",
+                         rc);
+            return rc;
+        }
     }
     return OK;
 }
 
+static void add_te_chunked(apr_pool_t *p,
+                           apr_bucket_alloc_t *bucket_alloc,
+                           apr_bucket_brigade *header_brigade)
+{
+    apr_bucket *e;
+    char *buf;
+    const char te_hdr[] = "Transfer-Encoding: chunked" CRLF;
+
+    buf = apr_pmemdup(p, te_hdr, sizeof(te_hdr)-1);
+    ap_xlate_proto_to_ascii(buf, sizeof(te_hdr)-1);
+
+    e = apr_bucket_pool_create(buf, sizeof(te_hdr)-1, p, bucket_alloc);
+    APR_BRIGADE_INSERT_TAIL(header_brigade, e);
+}
+
+static void add_cl(apr_pool_t *p,
+                   apr_bucket_alloc_t *bucket_alloc,
+                   apr_bucket_brigade *header_brigade,
+                   const char *cl_val)
+{
+    apr_bucket *e;
+    char *buf;
+
+    buf = apr_pstrcat(p, "Content-Length: ",
+                      cl_val,
+                      CRLF,
+                      NULL);
+    ap_xlate_proto_to_ascii(buf, strlen(buf));
+    e = apr_bucket_pool_create(buf, strlen(buf), p, bucket_alloc);
+    APR_BRIGADE_INSERT_TAIL(header_brigade, e);
+}
+
+#define ASCII_CRLF  "\015\012"
+#define ASCII_ZERO  "\060"
+
+static void terminate_headers(apr_bucket_alloc_t *bucket_alloc,
+                              apr_bucket_brigade *header_brigade)
+{
+    apr_bucket *e;
+
+    /* add empty line at the end of the headers */
+    e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
+    APR_BRIGADE_INSERT_TAIL(header_brigade, e);
+}
+
+static apr_status_t pass_brigade(apr_bucket_alloc_t *bucket_alloc,
+                                 request_rec *r, proxy_http_conn_t *p_conn,
+                                 conn_rec *origin, apr_bucket_brigade *b,
+                                 int flush)
+{
+    apr_status_t status;
+
+    if (flush) {
+        apr_bucket *e = apr_bucket_flush_create(bucket_alloc);
+        APR_BRIGADE_INSERT_TAIL(b, e);
+    }
+    status = ap_pass_brigade(origin->output_filters, b);
+    if (status != APR_SUCCESS) {
+        ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
+                     "proxy: pass request data failed to %pI (%s)",
+                     p_conn->addr, p_conn->name);
+        return status;
+    }
+    apr_brigade_cleanup(b);
+    return APR_SUCCESS;
+}
+
+static apr_status_t stream_reqbody_chunked(apr_pool_t *p,
+                                           request_rec *r,
+                                           proxy_http_conn_t *p_conn,
+                                           conn_rec *origin,
+                                           apr_bucket_brigade *header_brigade)
+{
+    int seen_eos = 0;
+    apr_size_t hdr_len;
+    apr_off_t bytes;
+    apr_status_t status;
+    apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
+    apr_bucket_brigade *b, *input_brigade;
+    apr_bucket *e;
+
+    input_brigade = apr_brigade_create(p, bucket_alloc);
+
+    do {
+        char chunk_hdr[20];  /* must be here due to transient bucket. */
+
+        status = ap_get_brigade(r->input_filters, input_brigade,
+                                AP_MODE_READBYTES, APR_BLOCK_READ,
+                                HUGE_STRING_LEN);
+
+        if (status != APR_SUCCESS) {
+            return status;
+        }
+
+        /* If this brigade contains EOS, either stop or remove it. */
+        if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
+            seen_eos = 1;
+
+            /* As a shortcut, if this brigade is simply an EOS bucket,
+             * don't send anything down the filter chain.
+             */
+            if (APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade))) {
+                break;
+            }
+
+            /* We can't pass this EOS to the output_filters. */
+            e = APR_BRIGADE_LAST(input_brigade);
+            apr_bucket_delete(e);
+        }
+
+        apr_brigade_length(input_brigade, 1, &bytes);
+
+        hdr_len = apr_snprintf(chunk_hdr, sizeof(chunk_hdr),
+                               "%" APR_UINT64_T_HEX_FMT CRLF, 
+                               (apr_uint64_t)bytes);
+        
+        ap_xlate_proto_to_ascii(chunk_hdr, hdr_len);
+        e = apr_bucket_transient_create(chunk_hdr, hdr_len,
+                                        bucket_alloc);
+        APR_BRIGADE_INSERT_HEAD(input_brigade, e);
+        
+        /*
+         * Append the end-of-chunk CRLF
+         */
+        e = apr_bucket_immortal_create(ASCII_CRLF, 2, bucket_alloc);
+        APR_BRIGADE_INSERT_TAIL(input_brigade, e);
+        
+        if (header_brigade) {
+            /* we never sent the header brigade, so go ahead and
+             * take care of that now
+             */
+            add_te_chunked(p, bucket_alloc, header_brigade);
+            terminate_headers(bucket_alloc, header_brigade);
+            b = header_brigade;
+            APR_BRIGADE_CONCAT(b, input_brigade);
+            header_brigade = NULL;
+        }
+        else {
+            b = input_brigade;
+        }
+        
+        status = pass_brigade(bucket_alloc, r, p_conn, origin, b, 0);
+        if (status != APR_SUCCESS) {
+            return status;
+        }
+    } while (!seen_eos);
+
+    if (header_brigade) {
+        /* we never sent the header brigade because there was no request body;
+         * send it now without T-E
+         */
+        terminate_headers(bucket_alloc, header_brigade);
+        b = header_brigade;
+    }
+    else {
+        if (!APR_BRIGADE_EMPTY(input_brigade)) {
+            /* input brigade still has an EOS which we can't pass to the output_filters. */
+            e = APR_BRIGADE_LAST(input_brigade);
+            AP_DEBUG_ASSERT(APR_BUCKET_IS_EOS(e));
+            apr_bucket_delete(e);
+        }
+        e = apr_bucket_immortal_create(ASCII_ZERO ASCII_CRLF
+                                       /* <trailers> */
+                                       ASCII_CRLF,
+                                       5, bucket_alloc);
+        APR_BRIGADE_INSERT_TAIL(input_brigade, e);
+        b = input_brigade;
+    }
+    
+    status = pass_brigade(bucket_alloc, r, p_conn, origin, b, 1);
+    return status;
+}
+
+static apr_status_t stream_reqbody_cl(apr_pool_t *p,
+                                      request_rec *r,
+                                      proxy_http_conn_t *p_conn,
+                                      conn_rec *origin,
+                                      apr_bucket_brigade *header_brigade,
+                                      const char *old_cl_val)
+{
+    int seen_eos = 0;
+    apr_status_t status;
+    apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
+    apr_bucket_brigade *b, *input_brigade;
+    apr_bucket *e;
+
+    input_brigade = apr_brigade_create(p, bucket_alloc);
+
+    do {
+        status = ap_get_brigade(r->input_filters, input_brigade,
+                                AP_MODE_READBYTES, APR_BLOCK_READ,
+                                HUGE_STRING_LEN);
+
+        if (status != APR_SUCCESS) {
+            return status;
+        }
+
+        /* If this brigade contains EOS, either stop or remove it. */
+        if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
+            seen_eos = 1;
+
+            /* As a shortcut, if this brigade is simply an EOS bucket,
+             * don't send anything down the filter chain.
+             */
+            if (APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade))) {
+                break;
+            }
+
+            /* We can't pass this EOS to the output_filters. */
+            e = APR_BRIGADE_LAST(input_brigade);
+            apr_bucket_delete(e);
+        }
+
+        if (header_brigade) {
+            /* we never sent the header brigade, so go ahead and
+             * take care of that now
+             */
+            add_cl(p, bucket_alloc, header_brigade, old_cl_val);
+            terminate_headers(bucket_alloc, header_brigade);
+            b = header_brigade;
+            APR_BRIGADE_CONCAT(b, input_brigade);
+            header_brigade = NULL;
+        }
+        else {
+            b = input_brigade;
+        }
+        
+        status = pass_brigade(bucket_alloc, r, p_conn, origin, b, 0);
+        if (status != APR_SUCCESS) {
+            return status;
+        }
+    } while (!seen_eos);
+
+    if (header_brigade) {
+        /* we never sent the header brigade since there was no request
+         * body; send it now, and only specify C-L if client specified
+         * C-L: 0
+         */
+        if (!strcmp(old_cl_val, "0")) {
+            add_cl(p, bucket_alloc, header_brigade, old_cl_val);
+        }
+        terminate_headers(bucket_alloc, header_brigade);
+        b = header_brigade;
+    }
+    else {
+        /* need to flush any pending data */
+        b = input_brigade; /* empty now; pass_brigade() will add flush */
+    }
+    status = pass_brigade(bucket_alloc, r, p_conn, origin, b, 1);
+    return status;
+}
+
+#define MAX_MEM_SPOOL 16384
+
+static apr_status_t spool_reqbody_cl(apr_pool_t *p,
+                                     request_rec *r,
+                                     proxy_http_conn_t *p_conn,
+                                     conn_rec *origin,
+                                     apr_bucket_brigade *header_brigade)
+{
+    int seen_eos = 0;
+    apr_status_t status;
+    apr_bucket_alloc_t *bucket_alloc = r->connection->bucket_alloc;
+    apr_bucket_brigade *body_brigade, *input_brigade;
+    apr_bucket *e;
+    apr_off_t bytes, bytes_spooled = 0, fsize = 0;
+    apr_file_t *tmpfile = NULL;
+
+    body_brigade = apr_brigade_create(p, bucket_alloc);
+    input_brigade = apr_brigade_create(p, bucket_alloc);
+
+    do {
+        status = ap_get_brigade(r->input_filters, input_brigade,
+                                AP_MODE_READBYTES, APR_BLOCK_READ,
+                                HUGE_STRING_LEN);
+
+        if (status != APR_SUCCESS) {
+            return status;
+        }
+
+        /* If this brigade contains EOS, either stop or remove it. */
+        if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(input_brigade))) {
+            seen_eos = 1;
+
+            /* As a shortcut, if this brigade is simply an EOS bucket,
+             * don't send anything down the filter chain.
+             */
+            if (APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(input_brigade))) {
+                break;
+            }
+
+            /* We can't pass this EOS to the output_filters. */
+            e = APR_BRIGADE_LAST(input_brigade);
+            apr_bucket_delete(e);
+        }
+
+        apr_brigade_length(input_brigade, 1, &bytes);
+
+        if (bytes_spooled + bytes > MAX_MEM_SPOOL) {
+            /* can't spool any more in memory; write latest brigade to disk */
+            if (tmpfile == NULL) {
+                const char *temp_dir;
+                char *template;
+
+                status = apr_temp_dir_get(&temp_dir, p);
+                if (status != APR_SUCCESS) {
+                    ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
+                                 "proxy: search for temporary directory failed");
+                    return status;
+                }
+                apr_filepath_merge(&template, temp_dir,
+                                   "modproxy.tmp.XXXXXX",
+                                   APR_FILEPATH_NATIVE, p);
+                status = apr_file_mktemp(&tmpfile, template, 0, p);
+                if (status != APR_SUCCESS) {
+                    ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
+                                 "proxy: creation of temporary file in directory %s failed",
+                                 temp_dir);
+                    return status;
+                }
+            }
+            for (e = APR_BRIGADE_FIRST(input_brigade);
+                 e != APR_BRIGADE_SENTINEL(input_brigade);
+                 e = APR_BUCKET_NEXT(e)) {
+                const char *data;
+                apr_size_t bytes_read, bytes_written;
+
+                apr_bucket_read(e, &data, &bytes_read, APR_BLOCK_READ);
+                status = apr_file_write_full(tmpfile, data, bytes_read, &bytes_written);
+                if (status != APR_SUCCESS) {
+                    const char *tmpfile_name;
+
+                    if (apr_file_name_get(&tmpfile_name, tmpfile) != APR_SUCCESS) {
+                        tmpfile_name = "(unknown)";
+                    }
+                    ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
+                                 "proxy: write to temporary file %s failed",
+                                 tmpfile_name);
+                    return status;
+                }
+                AP_DEBUG_ASSERT(bytes_read == bytes_written);
+                fsize += bytes_written;
+            }
+            apr_brigade_cleanup(input_brigade);
+        }
+        else {
+            APR_BRIGADE_CONCAT(body_brigade, input_brigade);
+        }
+        
+        bytes_spooled += bytes;
+
+    } while (!seen_eos);
+
+    if (bytes_spooled) {
+        add_cl(p, bucket_alloc, header_brigade, apr_off_t_toa(p, bytes_spooled));
+    }
+    terminate_headers(bucket_alloc, header_brigade);
+    APR_BRIGADE_CONCAT(header_brigade, body_brigade);
+    if (tmpfile) {
+        /* For platforms where the size of the file may be larger than
+         * that which can be stored in a single bucket (where the
+         * length field is an apr_size_t), split it into several
+         * buckets: */
+        if (sizeof(apr_off_t) > sizeof(apr_size_t)
+            && fsize > AP_MAX_SENDFILE) {
+            e = apr_bucket_file_create(tmpfile, 0, AP_MAX_SENDFILE, p,
+                                       bucket_alloc);
+            while (fsize > AP_MAX_SENDFILE) {
+                apr_bucket *ce;
+                apr_bucket_copy(e, &ce);
+                APR_BRIGADE_INSERT_TAIL(header_brigade, ce);
+                e->start += AP_MAX_SENDFILE;
+                fsize -= AP_MAX_SENDFILE;
+            }
+            e->length = (apr_size_t)fsize; /* Resize just the last bucket */
+        }
+        else {
+            e = apr_bucket_file_create(tmpfile, 0, (apr_size_t)fsize, p,
+                                       bucket_alloc);
+        }
+        APR_BRIGADE_INSERT_TAIL(header_brigade, e);
+    }
+    status = pass_brigade(bucket_alloc, r, p_conn, origin, header_brigade, 1);
+    return status;
+}
+
+static apr_status_t send_request_body(apr_pool_t *p,
+                                      request_rec *r,
+                                      proxy_http_conn_t *p_conn,
+                                      conn_rec *origin,
+                                      apr_bucket_brigade *header_brigade,
+                                      int force10)
+{
+    enum {RB_INIT, RB_STREAM_CL, RB_STREAM_CHUNKED, RB_SPOOL_CL} rb_method = RB_INIT;
+    const char *old_cl_val, *te_val;
+    int cl_zero; /* client sent "Content-Length: 0", which we forward on to server */
+    apr_status_t status;
+
+    /* send CL or use chunked encoding?
+     *
+     * . CL is the most friendly to the origin server since it is the
+     *   most widely supported
+     * . CL stinks if we don't know the length since we have to buffer
+     *   the data in memory or on disk until we get the entire data
+     *
+     * special cases to check for:
+     * . if we're using HTTP/1.0 to origin server, then we must send CL
+     * . if client sent C-L and there are no input resource filters, the
+     *   the body size can't change so we send the same CL and stream the
+     *   body
+     * . if client used chunked or proxy-sendchunks is set, we'll also
+     *   use chunked
+     *
+     * normal case:
+     *   we have to compute content length by reading the entire request
+     *   body; if request body is not small, we'll spool the remaining input
+     *   to a temporary file
+     *
+     * special envvars to override the normal decision:
+     * . proxy-sendchunks
+     *   use chunked encoding; not compatible with force-proxy-request-1.0
+     * . proxy-sendcl
+     *   spool the request body to compute C-L
+     * . proxy-sendunchangedcl
+     *   use C-L from client and spool the request body
+     */
+    old_cl_val = apr_table_get(r->headers_in, "Content-Length");
+    cl_zero = old_cl_val && !strcmp(old_cl_val, "0");
+
+    if (!force10
+        && !cl_zero
+        && apr_table_get(r->subprocess_env, "proxy-sendchunks")) {
+        rb_method = RB_STREAM_CHUNKED;
+    }
+    else if (!cl_zero
+             && apr_table_get(r->subprocess_env, "proxy-sendcl")) {
+        rb_method = RB_SPOOL_CL;
+    }
+    else {
+        if (old_cl_val &&
+            (r->input_filters == r->proto_input_filters
+             || cl_zero
+             || apr_table_get(r->subprocess_env, "proxy-sendunchangedcl"))) {
+            rb_method = RB_STREAM_CL;
+        }
+        else if (force10) {
+            rb_method = RB_SPOOL_CL;
+        }
+        else if ((te_val = apr_table_get(r->headers_in, "Transfer-Encoding"))
+                  && !strcasecmp(te_val, "chunked")) {
+            rb_method = RB_STREAM_CHUNKED;
+        }
+        else {
+            rb_method = RB_SPOOL_CL;
+        }
+    }
+
+    switch(rb_method) {
+    case RB_STREAM_CHUNKED:
+        status = stream_reqbody_chunked(p, r, p_conn, origin, header_brigade);
+        break;
+    case RB_STREAM_CL:
+        status = stream_reqbody_cl(p, r, p_conn, origin, header_brigade, old_cl_val);
+        break;
+    case RB_SPOOL_CL:
+        status = spool_reqbody_cl(p, r, p_conn, origin, header_brigade);
+        break;
+    default:
+        ap_assert(1 != 1);
+    }
+
+    return status;
+}
+
 static
 apr_status_t ap_proxy_http_request(apr_pool_t *p, request_rec *r,
                                    proxy_http_conn_t *p_conn, conn_rec *origin, 
@@ -423,8 +913,9 @@
     apr_bucket *e;
     const apr_array_header_t *headers_in_array;
     const apr_table_entry_t *headers_in;
-    int counter, seen_eos;
+    int counter;
     apr_status_t status;
+    int force10;
 
     /*
      * Send the HTTP/1.1 request to the remote server
@@ -451,8 +942,10 @@
 
     if ( apr_table_get(r->subprocess_env,"force-proxy-request-1.0")) {
         buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.0" CRLF, NULL);
+        force10 = 1;
     } else {
         buf = apr_pstrcat(p, r->method, " ", url, " HTTP/1.1" CRLF, NULL);
+        force10 = 0;
     }
     if ( apr_table_get(r->subprocess_env,"proxy-nokeepalive")) {
         apr_table_unset(r->headers_in, "Connection");
@@ -574,6 +1067,10 @@
             || !apr_strnatcasecmp(headers_in[counter].key, "Transfer-Encoding")
             || !apr_strnatcasecmp(headers_in[counter].key, "Upgrade")
 
+            /* We'll add appropriate Content-Length later, if appropriate.
+             */
+            || !apr_strnatcasecmp(headers_in[counter].key, "Content-Length")
+
         /* XXX: @@@ FIXME: "Proxy-Authorization" should *only* be 
          * suppressed if THIS server requested the authentication,
          * not when a frontend proxy requested it!
@@ -626,18 +1123,8 @@
         APR_BRIGADE_INSERT_TAIL(bb, e);
     }
 
-    /* add empty line at the end of the headers */
-#if APR_CHARSET_EBCDIC
-    e = apr_bucket_immortal_create("\015\012", 2, c->bucket_alloc);
-#else
-    e = apr_bucket_immortal_create(CRLF, sizeof(CRLF)-1, c->bucket_alloc);
-#endif
-    APR_BRIGADE_INSERT_TAIL(bb, e);
-    e = apr_bucket_flush_create(c->bucket_alloc);
-    APR_BRIGADE_INSERT_TAIL(bb, e);
-
-    status = ap_pass_brigade(origin->output_filters, bb);
-
+    /* send the request data, if any. */
+    status = send_request_body(p, r, p_conn, origin, bb, force10);
     if (status != APR_SUCCESS) {
         ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
                      "proxy: request failed to %pI (%s)",
@@ -645,43 +1132,6 @@
         return status;
     }
 
-    /* send the request data, if any. */
-    seen_eos = 0;
-    do {
-        status = ap_get_brigade(r->input_filters, bb, AP_MODE_READBYTES,
-                                APR_BLOCK_READ, HUGE_STRING_LEN);
-
-        if (status != APR_SUCCESS) {
-            return status;
-        }
-
-        /* If this brigade contain EOS, either stop or remove it. */
-        if (APR_BUCKET_IS_EOS(APR_BRIGADE_LAST(bb))) {
-            /* As a shortcut, if this brigade is simply an EOS bucket,
-             * don't send anything down the filter chain.
-             */
-            if (APR_BUCKET_IS_EOS(APR_BRIGADE_FIRST(bb))) {
-                break;
-            }
-
-            /* We can't pass this EOS to the output_filters. */
-            APR_BUCKET_REMOVE(APR_BRIGADE_LAST(bb));
-            seen_eos = 1;
-        }
-
-        e = apr_bucket_flush_create(c->bucket_alloc);
-        APR_BRIGADE_INSERT_TAIL(bb, e);
-
-        status = ap_pass_brigade(origin->output_filters, bb);
-        if (status != APR_SUCCESS) {
-            ap_log_error(APLOG_MARK, APLOG_ERR, status, r->server,
-                         "proxy: pass request data failed to %pI (%s)",
-                         p_conn->addr, p_conn->name);
-            return status;
-        }
-        apr_brigade_cleanup(bb);
-    } while (!seen_eos);
-
     return APR_SUCCESS;
 }
 
@@ -792,8 +1242,24 @@
                 return r->status;
 
             } else {
-                /* strip connection listed hop-by-hop headers from response */
                 const char *buf;
+
+                /* can't have both Content-Length and Transfer-Encoding */
+                if (apr_table_get(r->headers_out, "Transfer-Encoding")
+                    && apr_table_get(r->headers_out, "Content-Length")) {
+                    /* 2616 section 4.4, point 3: "if both Transfer-Encoding
+                     * and Content-Length are received, the latter MUST be
+                     * ignored"; so unset it here to prevent any confusion
+                     * later. */
+                    apr_table_unset(r->headers_out, "Content-Length");
+                    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
+                                 r->server,
+                                 "proxy: server %s returned Transfer-Encoding and Content-Length",
+                                 p_conn->name);
+                    p_conn->close += 1;
+                }
+                
+                /* strip connection listed hop-by-hop headers from response */
                 p_conn->close += ap_proxy_liststr(apr_table_get(r->headers_out,
                                                                 "Connection"),
                                                   "close");
@@ -958,7 +1424,8 @@
                     }
 
                     /* try send what we read */
-                    if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS) {
+                    if (ap_pass_brigade(r->output_filters, bb) != APR_SUCCESS
+                        || c->aborted) {
                         /* Ack! Phbtt! Die! User aborted! */
                         p_conn->close = 1;  /* this causes socket close below */
                         finish = TRUE;
@@ -992,7 +1459,13 @@
              */
             int status = r->status;
             r->status = HTTP_OK;
-            ap_discard_request_body(rp);
+            /* Discard body, if one is expected */
+            if ((status > 199) && /* not any 1xx response */
+                (status != HTTP_NO_CONTENT) && /* not 204 */
+                (status != HTTP_RESET_CONTENT) && /* not 205 */
+                (status != HTTP_NOT_MODIFIED)) { /* not 304 */
+               ap_discard_request_body(rp);
+           }
             return status;
         }
     } else 
Index: modules/proxy/proxy_util.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/modules/proxy/proxy_util.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- modules/proxy/proxy_util.c	29 Jul 2003 20:19:23 -0000	1.1.1.1
+++ modules/proxy/proxy_util.c	9 Jan 2006 18:48:06 -0000	1.4
@@ -240,9 +240,10 @@
      ap_proxy_canon_netloc(apr_pool_t *p, char **const urlp, char **userp,
 			char **passwordp, char **hostp, apr_port_t *port)
 {
-    int i;
-    char *strp, *host, *url = *urlp;
+    char *addr, *scope_id, *strp, *host, *url = *urlp;
     char *user = NULL, *password = NULL;
+    apr_port_t tmp_port;
+    apr_status_t rv;
 
     if (url[0] != '/' || url[1] != '/')
 	return "Malformed URL";
@@ -281,44 +282,21 @@
 	*passwordp = password;
     }
 
-    strp = strrchr(host, ':');
-    if (strp != NULL) {
-	*(strp++) = '\0';
-
-	for (i = 0; strp[i] != '\0'; i++)
-	    if (!apr_isdigit(strp[i]))
-		break;
-
-	/* if (i == 0) the no port was given; keep default */
-	if (strp[i] != '\0') {
-	    return "Bad port number in URL";
-	} else if (i > 0) {
-            int int_port = atoi(strp);
-
-	    if (int_port > 65535)
-		return "Port number in URL > 65535";
-
-	    *port = (apr_port_t)int_port;
-	}
-    }
-    ap_str_tolower(host);		/* DNS names are case-insensitive */
-    if (*host == '\0')
-	return "Missing host in URL";
-/* check hostname syntax */
-    for (i = 0; host[i] != '\0'; i++)
-	if (!apr_isdigit(host[i]) && host[i] != '.')
-	    break;
-    /* must be an IP address */
-    if (host[i] == '\0' && (apr_inet_addr(host) == -1))
-    {
-	return "Bad IP address in URL";
+    /* Parse the host string to separate host portion from optional port.
+     * Perform range checking on port.
+     */
+    rv = apr_parse_addr_port(&addr, &scope_id, &tmp_port, host, p);
+    if (rv != APR_SUCCESS || addr == NULL || scope_id != NULL) {
+        return "Invalid host/port";
+    }
+    if (tmp_port != 0) { /* only update caller's port if port was specified */
+        *port = tmp_port;
     }
 
-/*    if (strchr(host,'.') == NULL && domain != NULL)
-   host = pstrcat(p, host, domain, NULL);
- */
+    ap_str_tolower(addr); /* DNS names are case-insensitive */
+
     *urlp = url;
-    *hostp = host;
+    *hostp = addr;
 
     return NULL;
 }
@@ -771,7 +749,7 @@
 
 	if (bits != 32)		/* no warning for fully qualified IP address */
             ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
-	      "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld\n",
+	      "Warning: NetMask not supplied with IP-Addr; guessing: %s/%ld",
 		 inet_ntoa(This->addr), bits);
     }
 
@@ -779,11 +757,11 @@
 
     if (*addr == '\0' && (This->addr.s_addr & ~This->mask.s_addr) != 0) {
         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
-	    "Warning: NetMask and IP-Addr disagree in %s/%ld\n",
+	    "Warning: NetMask and IP-Addr disagree in %s/%ld",
 		inet_ntoa(This->addr), bits);
 	This->addr.s_addr &= This->mask.s_addr;
         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
-	    "         Set to %s/%ld\n",
+	    "         Set to %s/%ld",
 		inet_ntoa(This->addr), bits);
     }
 
@@ -1220,6 +1198,12 @@
             continue;
         }
         connected = 1;
+        /* To find out whether this is a proxy connection, a module
+         * can look up the "IHSPROXYCONNECTION" key on the connection
+         * pool.  This may change at any time.  It is only for
+         * internal use.
+         */
+        apr_pool_userdata_setn("1", "IHSPROXYCONNECTION", NULL, p);
     }
     return connected ? 0 : 1;
 }
Index: os/unix/unixd.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/os/unix/unixd.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- os/unix/unixd.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ os/unix/unixd.c	7 Mar 2004 12:35:47 -0000	1.4
@@ -184,6 +184,18 @@
                     (long) unixd_config.user_id);
 	return -1;
     }
+
+/* IHS is built on an older level of Linux as part of maintaining
+ * compatibility with a wide set of products.  A side-effect of
+ * using an older level is that PR_SET_DUMPABLE is not defined in
+ * the glibc header files.  Define it here so that the prctl()
+ * logic will be enabled.
+ */
+
+#if defined(__linux__) && !defined(PR_SET_DUMPABLE)
+#define PR_SET_DUMPABLE 4
+#endif
+
 #if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE) 
     /* this applies to Linux 2.4+ */
 #ifdef AP_MPM_WANT_SET_COREDUMPDIR
@@ -195,6 +207,8 @@
         }
     }
 #endif
+#elif defined(__linux__)
+#error IHS build problem -  prctl is not enabled
 #endif
 #endif
     return 0;
@@ -473,15 +487,6 @@
     if (status == APR_SUCCESS) { 
         *accepted = csd;
         apr_os_sock_get(&sockdes, csd);
-        if (sockdes >= FD_SETSIZE) {
-            ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
-                         "new file descriptor %d is too large; you probably need "
-                         "to rebuild Apache with a larger FD_SETSIZE "
-                         "(currently %d)",
-                         sockdes, FD_SETSIZE);
-            apr_socket_close(csd);
-            return APR_EINTR;
-        } 
 #ifdef TPF
         if (sockdes == 0) {                  /* 0 is invalid socket for TPF */
             return APR_EINTR;
@@ -554,6 +559,19 @@
 #endif
 #ifdef ENETUNREACH
         case ENETUNREACH:
+#endif
+        /* EAGAIN/EWOULDBLOCK can be returned on BSD-derived
+         * TCP stacks when the connection is aborted before
+         * we call connect, but only because our listener
+         * sockets are non-blocking (AP_NONBLOCK_WHEN_MULTI_LISTEN)
+         */
+#ifdef EAGAIN
+        case EAGAIN:
+#endif
+#ifdef EWOULDBLOCK
+#if !defined(EAGAIN) || EAGAIN != EWOULDBLOCK
+        case EWOULDBLOCK:
+#endif
 #endif
             break;
 #ifdef ENETDOWN
Index: server/Makefile.in
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/Makefile.in,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- server/Makefile.in	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/Makefile.in	8 Mar 2005 19:53:29 -0000	1.2
@@ -10,6 +10,7 @@
 LTLIBRARY_SOURCES = \
     test_char.h \
 	config.c log.c main.c vhost.c util.c \
+	ihs_hooks.c \
 	util_script.c util_md5.c util_cfgtree.c util_ebcdic.c util_time.c \
 	rfc1413.c connection.c listen.c \
 	mpm_common.c util_charset.c util_debug.c util_xml.c \
Index: server/config.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/config.c,v
retrieving revision 1.1.1.1
retrieving revision 1.5
diff -u -u -r1.1.1.1 -r1.5
--- server/config.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/config.c	8 Mar 2005 19:53:29 -0000	1.5
@@ -398,7 +398,7 @@
         r->handler = handler;
     }
 
-    result = ap_run_handler(r);
+    result = ihs_run_handler(r);
 
     r->handler = old_handler;
 
@@ -645,6 +645,7 @@
         ap_add_module(*m, process->pconf);
 
     apr_hook_sort_all();
+    ihs_save_hook_info();
 }
 
 AP_DECLARE(const char *) ap_find_module_name(module *m)
@@ -697,7 +698,7 @@
                               void *mconfig, const char *args)
 {
     char *w, *w2, *w3;
-    const char *errmsg;
+    const char *errmsg = NULL;
 
     if ((parms->override & cmd->req_override) == 0)
         return apr_pstrcat(parms->pool, cmd->name, " not allowed here", NULL);
@@ -797,11 +798,14 @@
 
     case ITERATE:
         while (*(w = ap_getword_conf(parms->pool, &args)) != '\0') {
-            if ((errmsg = cmd->AP_TAKE1(parms, mconfig, w)))
+
+            errmsg = cmd->AP_TAKE1(parms, mconfig, w);
+
+            if (errmsg && strcmp(errmsg, DECLINE_CMD) != 0)
                 return errmsg;
         }
 
-        return NULL;
+        return errmsg;
 
     case ITERATE2:
         w = ap_getword_conf(parms->pool, &args);
@@ -812,11 +816,14 @@
                                cmd->errmsg ? ", " : NULL, cmd->errmsg, NULL);
 
         while (*(w2 = ap_getword_conf(parms->pool, &args)) != '\0') {
-            if ((errmsg = cmd->AP_TAKE2(parms, mconfig, w, w2)))
+
+            errmsg = cmd->AP_TAKE2(parms, mconfig, w, w2);
+
+            if (errmsg && strcmp(errmsg, DECLINE_CMD) != 0)
                 return errmsg;
         }
 
-        return NULL;
+        return errmsg;
 
     case FLAG:
         w = ap_getword_conf(parms->pool, &args);
@@ -926,6 +933,9 @@
         if (*lastc == '>') {
             *lastc = '\0' ;
         }
+        if (cmd_name[0] == '<' && *args == '\0') {
+            args = ">";
+        }
     }
 
     newdir = apr_pcalloc(p, sizeof(ap_directive_t));
@@ -1422,8 +1432,9 @@
     errmsg = ap_build_config(&parms, p, ptemp, conftree);
     if (errmsg) {
         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
-                     "Syntax error in -C/-c directive:" APR_EOL_STR "%s",
-                     errmsg);
+                     "Syntax error in -C/-c directive:");
+        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL,
+                     "%s", errmsg);
         exit(1);
     }
 
Index: server/core.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/core.c,v
retrieving revision 1.1.1.1
retrieving revision 1.13
diff -u -u -r1.1.1.1 -r1.13
--- server/core.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/core.c	10 Apr 2006 19:39:58 -0000	1.13
@@ -721,16 +721,26 @@
 
 char *ap_response_code_string(request_rec *r, int error_index)
 {
-    core_dir_config *conf;
+    core_dir_config *dirconf;
+    core_request_config *reqconf;
 
-    conf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
-                                                   &core_module);
+    /* check for string registered via ap_custom_response() first */
+    reqconf = (core_request_config *)ap_get_module_config(r->request_config,
+                                                          &core_module);
+    if (reqconf->response_code_strings != NULL &&
+        reqconf->response_code_strings[error_index] != NULL) {
+        return reqconf->response_code_strings[error_index];
+    }
 
-    if (conf->response_code_strings == NULL) {
-        return NULL;
+    /* check for string specified via ErrorDocument */
+    dirconf = (core_dir_config *)ap_get_module_config(r->per_dir_config,
+                                                      &core_module);
+
+    if (dirconf->response_code_strings == NULL) {
+	return NULL;
     }
 
-    return conf->response_code_strings[error_index];
+    return dirconf->response_code_strings[error_index];
 }
 
 
@@ -1143,11 +1153,11 @@
 AP_DECLARE(void) ap_custom_response(request_rec *r, int status,
                                     const char *string)
 {
-    core_dir_config *conf =
-        ap_get_module_config(r->per_dir_config, &core_module);
+    core_request_config *conf =
+        ap_get_module_config(r->request_config, &core_module);
     int idx;
 
-    if(conf->response_code_strings == NULL) {
+    if (conf->response_code_strings == NULL) {
         conf->response_code_strings =
             apr_pcalloc(r->pool,
                         sizeof(*conf->response_code_strings) * RESPONSE_CODES);
@@ -2489,12 +2499,6 @@
                            "\" must be a non-negative integer", NULL);
     }
 
-    if (lim > DEFAULT_LIMIT_REQUEST_LINE) {
-        return apr_psprintf(cmd->temp_pool, "LimitRequestLine \"%s\" "
-                            "must not exceed the precompiled maximum of %d",
-                            arg, DEFAULT_LIMIT_REQUEST_LINE);
-    }
-
     cmd->server->limit_req_line = lim;
     return NULL;
 }
@@ -2513,16 +2517,10 @@
     lim = atoi(arg);
     if (lim < 0) {
         return apr_pstrcat(cmd->temp_pool, "LimitRequestFieldsize \"", arg,
-                          "\" must be a non-negative integer (0 = no limit)",
+                          "\" must be a non-negative integer",
                           NULL);
     }
 
-    if (lim > DEFAULT_LIMIT_REQUEST_FIELDSIZE) {
-        return apr_psprintf(cmd->temp_pool, "LimitRequestFieldsize \"%s\" "
-                           "must not exceed the precompiled maximum of %d",
-                            arg, DEFAULT_LIMIT_REQUEST_FIELDSIZE);
-    }
-
     cmd->server->limit_req_fieldsize = lim;
     return NULL;
 }
@@ -3023,8 +3021,8 @@
             *nbytes += bytes_sent;     /* track total bytes sent */
     }
 
-    /* Seek the file to 'offset' */
-    if (offset != 0 && rv == APR_SUCCESS) {
+    /* Seek the file to 'offset'. */
+    if (offset >= 0 && rv == APR_SUCCESS) {
         rv = apr_file_seek(fd, APR_SET, &offset);
     }
 
@@ -3285,6 +3283,14 @@
 AP_INIT_TAKE1("MaxMemFree", ap_mpm_set_max_mem_free, NULL, RSRC_CONF,
               "Maximum number of 1k blocks a particular childs allocator may hold."),
 #endif
+#ifdef AP_MPM_WANT_SET_STACKSIZE
+AP_INIT_TAKE1("ThreadStackSize", ap_mpm_set_thread_stacksize, NULL, RSRC_CONF,
+              "Size in bytes of stack used by threads handling client connections"),
+#endif
+#if AP_ENABLE_EXCEPTION_HOOK
+AP_INIT_TAKE1("EnableExceptionHook", ap_mpm_set_exception_hook, NULL, RSRC_CONF,
+              "Controls whether exception hook may be called after a crash"),
+#endif
 { NULL }
 };
 
@@ -3555,7 +3561,20 @@
         e = apr_bucket_eos_create(c->bucket_alloc);
         APR_BRIGADE_INSERT_TAIL(bb, e);
 
-        return ap_pass_brigade(r->output_filters, bb);
+        status = ap_pass_brigade(r->output_filters, bb);
+        if (status == APR_SUCCESS
+            || r->status != HTTP_OK
+            || c->aborted) {
+            return OK;
+        }
+        else {
+            /* no way to know what type of error occurred */
+            ap_log_rerror(APLOG_MARK, APLOG_INFO, status, r,
+                          "default_handler: ap_pass_brigade returned %i",
+                          status);
+            return HTTP_INTERNAL_SERVER_ERROR;
+        }
+
     }
     else {              /* unusual method (not GET or POST) */
         if (r->method_number == M_INVALID) {
@@ -3622,6 +3641,13 @@
     } while (!APR_BRIGADE_EMPTY(b) && (e != APR_BRIGADE_SENTINEL(b))); \
 } while (0)
 
+#ifdef _AIX
+static int avoid_xlc_issue(struct server_rec *s)
+{
+    return s->next == NULL;
+}
+#endif
+
 static int core_input_filter(ap_filter_t *f, apr_bucket_brigade *b,
                              ap_input_mode_t mode, apr_read_type_e block,
                              apr_off_t readbytes)
@@ -3661,6 +3687,10 @@
         return APR_EOF;
     }
 
+#ifdef _AIX
+    avoid_xlc_issue(f->c->base_server);
+#endif
+
     /* ### This is bad. */
     BRIGADE_NORMALIZE(ctx->b);
 
@@ -4094,9 +4124,9 @@
                         rv = apr_bucket_read(bucket, &buf, &len,
                                              APR_BLOCK_READ);
                         if (rv != APR_SUCCESS) {
-                            ap_log_error(APLOG_MARK, APLOG_ERR, rv,
-                                         c->base_server, "core_output_filter:"
-                                         " Error reading from bucket.");
+                            ap_log_cerror(APLOG_MARK, APLOG_ERR, rv,
+                                          c, "core_output_filter:"
+                                          " Error reading from bucket.");
                             return HTTP_INTERNAL_SERVER_ERROR;
                         }
                     }
@@ -4149,6 +4179,12 @@
                                                        sent                 */
                                      flags);   /* apr_sendfile flags        */
 
+                /* IBM: restore lost code to help Win9x */
+                if (APR_ENOTIMPL == rv) {
+                    rv = emulate_sendfile(net, fd, &hdtr, foffset, flen,
+                                          &bytes_sent);
+                }
+
                 if (logio_add_bytes_out && bytes_sent > 0)
                     logio_add_bytes_out(c, bytes_sent);
             }
@@ -4202,8 +4238,8 @@
         }
 
         if (rv != APR_SUCCESS) {
-            ap_log_error(APLOG_MARK, APLOG_INFO, rv, c->base_server,
-                         "core_output_filter: writing data to the network");
+            ap_log_cerror(APLOG_MARK, APLOG_INFO, rv, c,
+                          "core_output_filter: writing data to the network");
 
             if (more)
                 apr_brigade_destroy(more);
@@ -4378,6 +4414,7 @@
 static int core_pre_connection(conn_rec *c, void *csd)
 {
     core_net_rec *net = apr_palloc(c->pool, sizeof(*net));
+    apr_status_t rv;
 
 #ifdef AP_MPM_DISABLE_NAGLE_ACCEPTED_SOCK
     /* BillS says perhaps this should be moved to the MPMs. Some OSes
@@ -4385,7 +4422,21 @@
      * accept sockets which means this call only needs to be made
      * once on the listener
      */
-    ap_sock_disable_nagle(csd);
+    /* The Nagle algorithm says that we should delay sending partial
+     * packets in hopes of getting more data.  We don't want to do
+     * this; we are not telnet.  There are bad interactions between
+     * persistent connections and Nagle's algorithm that have very severe
+     * performance penalties.  (Failing to disable Nagle is not much of a
+     * problem with simple HTTP.)
+     */
+    rv = apr_socket_opt_set(csd, APR_TCP_NODELAY, 1);
+    if (rv != APR_SUCCESS && rv != APR_ENOTIMPL) {
+        /* expected cause is that the client disconnected already,
+         * hence the debug level
+         */
+        ap_log_cerror(APLOG_MARK, APLOG_DEBUG, rv, c,
+                      "apr_socket_opt_set(APR_TCP_NODELAY)");
+    }
 #endif
     net->c = c;
     net->in_ctx = NULL;
@@ -4414,6 +4465,7 @@
     ap_hook_translate_name(ap_core_translate,NULL,NULL,APR_HOOK_REALLY_LAST);
     ap_hook_map_to_storage(core_map_to_storage,NULL,NULL,APR_HOOK_REALLY_LAST);
     ap_hook_open_logs(ap_open_logs,NULL,NULL,APR_HOOK_REALLY_FIRST);
+    ap_hook_child_init(ap_logs_child_init,NULL,NULL,APR_HOOK_MIDDLE);
     ap_hook_handler(default_handler,NULL,NULL,APR_HOOK_REALLY_LAST);
     /* FIXME: I suspect we can eliminate the need for these do_nothings - Ben */
     ap_hook_type_checker(do_nothing,NULL,NULL,APR_HOOK_REALLY_LAST);
Index: server/listen.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/listen.c,v
retrieving revision 1.1.1.1
retrieving revision 1.6
diff -u -u -r1.1.1.1 -r1.6
--- server/listen.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/listen.c	19 Apr 2005 20:17:49 -0000	1.6
@@ -82,6 +82,7 @@
 static ap_listen_rec *old_listeners;
 static int ap_listenbacklog;
 static int send_buffer_size;
+static int receive_buffer_size;
 
 /* TODO: make_sock is just begging and screaming for APR abstraction */
 static apr_status_t make_sock(apr_pool_t *p, ap_listen_rec *server)
@@ -160,6 +161,17 @@
             /* not a fatal error */
         }
     }
+    if (receive_buffer_size) {
+        stat = apr_socket_opt_set(s, APR_SO_RCVBUF, receive_buffer_size);
+        if (stat != APR_SUCCESS && stat != APR_ENOTIMPL) {
+            ap_log_perror(APLOG_MARK, APLOG_WARNING, stat, p,
+                          "make_sock: failed to set ReceiveBufferSize for "
+                          "address %pI, using default",
+                          server->bind_addr);
+            strerror(errno);
+            /* not a fatal error */
+        }
+    }
 
 #if APR_TCP_NODELAY_INHERITED
     ap_sock_disable_nagle(s);
@@ -266,8 +278,8 @@
 #endif
 }
 
-
-static const char *alloc_listener(process_rec *process, char *addr, apr_port_t port)
+/* IBM: externalize for use by AFPA on Win32 */
+AP_DECLARE(const char *) ap_alloc_listener(process_rec *process, char *addr, apr_port_t port)
 {
     ap_listen_rec **walk;
     ap_listen_rec *new;
@@ -276,6 +288,15 @@
     apr_sockaddr_t *sa;
 
     if (!addr) { /* don't bind to specific interface */
+#ifdef WIN32
+#if APR_HAVE_IPV6
+       ap_log_perror(APLOG_MARK, APLOG_ERR, 0, process->pool,
+                    "Windows Listen directives should always specify an IPv4 or IPv6 address."
+                    " e.g. Listen 0.0.0.0:%hu, or Listen [::]:%hu. " 
+                    "See IHS readme or IHS IPv6 documentation for more details.", port, port);
+#endif
+#endif
+
         find_default_family(process->pool);
         switch(default_family) {
         case APR_INET:
@@ -372,6 +393,26 @@
     }
     old_listeners = NULL;
 
+#if AP_NONBLOCK_WHEN_MULTI_LISTEN
+    /* if multiple listening sockets, make them non-blocking so that
+     * if select()/poll() reports readability for a reset connection that
+     * is already forgotten about by the time we call accept, we won't
+     * be hung until another connection arrives on that port
+     */
+    if (ap_listeners && ap_listeners->next) {
+        for (lr = ap_listeners; lr; lr = lr->next) {
+            apr_status_t status;
+
+            status = apr_socket_opt_set(lr->sd, APR_SO_NONBLOCK, 1);
+            if (status != APR_SUCCESS) {
+                ap_log_perror(APLOG_MARK, APLOG_STARTUP|APLOG_ERR, status, pool,
+                              "ap_listen_open: unable to make socket non-blocking");
+                return -1;
+            }
+        }
+    }
+#endif /* AP_NONBLOCK_WHEN_MULTI_LISTEN */
+
     /* we come through here on both passes of the open logs phase
      * only register the cleanup once... otherwise we try to close
      * listening sockets twice when cleaning up prior to exec
@@ -440,7 +481,7 @@
         return "Port must be specified";
     }
 
-    return alloc_listener(cmd->server->process, host, port);
+    return ap_alloc_listener(cmd->server->process, host, port);
 }
 
 const char *ap_set_listenbacklog(cmd_parms *cmd, void *dummy, const char *arg)
@@ -476,5 +517,23 @@
     }
 
     send_buffer_size = s;
+    return NULL;
+}
+AP_DECLARE_NONSTD(const char *) ap_set_receive_buffer_size(cmd_parms *cmd,
+                                                           void *dummy,
+                                                           const char *arg)
+{
+    int s = atoi(arg);
+    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+
+    if (err != NULL) {
+        return err;
+    }
+
+    if (s < 512 && s != 0) {
+        return "ReceiveBufferSize must be >= 512 bytes, or 0 for system default.";
+    }
+
+    receive_buffer_size = s;
     return NULL;
 }
Index: server/log.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/log.c,v
retrieving revision 1.1.1.1
retrieving revision 1.8
diff -u -u -r1.1.1.1 -r1.8
--- server/log.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/log.c	15 Jun 2005 16:33:08 -0000	1.8
@@ -92,6 +92,16 @@
 #include "http_main.h"
 #include "util_time.h"
 
+#ifndef APR_LARGEFILE
+#define APR_LARGEFILE 0
+#endif
+
+#ifdef WIN32
+#define PIPED_LOGGER_CMDTYPE APR_PROGRAM_ENV
+#else
+#define PIPED_LOGGER_CMDTYPE APR_SHELLCMD_ENV
+#endif
+
 typedef struct {
     char    *t_name;
     int      t_val;
@@ -182,6 +192,68 @@
 
 static apr_file_t *stderr_log = NULL;
 
+/* track pipe handles to close in child process */
+typedef struct read_handle_t {
+    struct read_handle_t *next;
+    apr_file_t *handle;
+} read_handle_t;
+
+static read_handle_t *read_handles;
+
+/* clear_handle_list() is called when plog is cleared; at that
+ * point we need to forget about our old list of pipe read
+ * handles
+ */
+static apr_status_t clear_handle_list(void *v)
+{
+    read_handles = NULL;
+    return APR_SUCCESS;
+}
+
+/* remember to close this handle in the child process */
+static void close_handle_in_child(apr_pool_t *p, apr_file_t *f)
+{
+    read_handle_t *new_handle;
+
+    new_handle = apr_pcalloc(p, sizeof(read_handle_t));
+    new_handle->next = read_handles;
+    new_handle->handle = f;
+    read_handles = new_handle;
+}
+
+void ap_logs_child_init(apr_pool_t *p, server_rec *s)
+{
+    read_handle_t *cur = read_handles;
+
+    while (cur) {
+        apr_file_close(cur->handle);
+        cur = cur->next;
+    }
+}
+
+static apr_size_t do_escape_errorlog_item(char *dest, const char *source,
+                                               apr_size_t buflen)
+{
+	return ap_escape_errorlog_item(dest,source,buflen);
+}
+
+static apr_size_t (*escape_errorlog_item)(char *, const char *, apr_size_t)
+    = do_escape_errorlog_item;
+
+static apr_size_t no_escape_errorlog_item(char *dest, const char *source,
+                                               apr_size_t buflen)
+{
+    size_t len;
+
+    if (!source || !buflen) { /* be safe */
+        return 0;
+    }
+
+    len = strlen(source);
+    memcpy(dest, source, len + 1);
+    return len;
+}
+
 AP_DECLARE(void) ap_open_stderr_log(apr_pool_t *p)
 {
     apr_file_open_stderr(&stderr_log, p);
@@ -200,7 +272,7 @@
         return APR_EBADPATH;
     }
     if ((rc = apr_file_open(&stderr_file, filename,
-                            APR_APPEND | APR_READ | APR_WRITE | APR_CREATE,
+                            APR_APPEND | APR_WRITE | APR_CREATE | APR_LARGEFILE,
                             APR_OS_DEFAULT, p)) != APR_SUCCESS) {
         ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL,
                      "%s: could not open error log file %s.",
@@ -239,6 +311,8 @@
     apr_proc_t *procnew;
 
     if (((rc = apr_procattr_create(&procattr, p)) == APR_SUCCESS)
+        && ((rc = apr_procattr_cmdtype_set(procattr,
+                                           PIPED_LOGGER_CMDTYPE)) == APR_SUCCESS)
         && ((rc = apr_procattr_io_set(procattr,
                                       APR_FULL_BLOCK,
                                       APR_NO_PIPE,
@@ -257,6 +331,9 @@
         if (rc == APR_SUCCESS) {
             apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
             (*fpin) = procnew->in;
+            /* read handle to pipe not kept open, so no need to call
+             * close_handle_in_child()
+             */
         }
     }
 
@@ -313,7 +390,7 @@
             return DONE;
         }
         if ((rc = apr_file_open(&s->error_log, fname,
-                               APR_APPEND | APR_READ | APR_WRITE | APR_CREATE,
+                               APR_APPEND | APR_WRITE | APR_CREATE | APR_LARGEFILE,
                                APR_OS_DEFAULT, p)) != APR_SUCCESS) {
             ap_log_error(APLOG_MARK, APLOG_STARTUP, rc, NULL,
                          "%s: could not open error log file %s.",
@@ -333,6 +410,15 @@
     int replace_stderr;
     apr_file_t *errfile = NULL;
 
+    apr_pool_cleanup_register(p, NULL, clear_handle_list,
+                              apr_pool_cleanup_null);
+    if (getenv("IHS_ERROR_LOG_UNESCAPED")) {
+        escape_errorlog_item = no_escape_errorlog_item;
+    }
+    else {
+        escape_errorlog_item = do_escape_errorlog_item;
+    }
+
     if (open_error_log(s_main, p) != OK) {
         return DONE;
     }
@@ -398,15 +484,23 @@
 
 static void log_error_core(const char *file, int line, int level,
                            apr_status_t status, const server_rec *s,
+                           const conn_rec *c,
                            const request_rec *r, apr_pool_t *pool,
                            const char *fmt, va_list args)
 {
     char errstr[MAX_STRING_LEN];
+#ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
+    char scratch[MAX_STRING_LEN];
+#endif
     apr_size_t len, errstrlen;
     apr_file_t *logf = NULL;
     const char *referer;
     int level_and_mask = level & APLOG_LEVELMASK;
 
+    if (r && r->connection) {
+        c = r->connection;
+    }
+
     if (s == NULL) {
         /*
          * If we are doing stderr logging (startup), don't log messages that are
@@ -473,7 +567,7 @@
 
 #ifndef TPF
     if (file && level_and_mask == APLOG_DEBUG) {
-#if defined(_OSD_POSIX) || defined(WIN32)
+#if defined(_OSD_POSIX) || defined(WIN32) || defined(__MVS__)
         char tmp[256];
         char *e = strrchr(file, '/');
 #ifdef WIN32
@@ -502,14 +596,14 @@
     }
 #endif /* TPF */
 
-    if (r && r->connection) {
+    if (c) {
         /* XXX: TODO: add a method of selecting whether logged client
          * addresses are in dotted quad or resolved form... dotted
          * quad is the most secure, which is why I'm implementing it
          * first. -djg
          */
         len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
-                            "[client %s] ", r->connection->remote_ip);
+                            "[client %s] ", c->remote_ip);
     }
     if (status != 0) {
         if (status < APR_OS_START_EAIERR) {
@@ -536,12 +630,30 @@
             errstr[len] = '\0';
         }
     }
+
     errstrlen = len;
+#ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
+    if (apr_vsnprintf(scratch, MAX_STRING_LEN - len, fmt, args)) {
+        len += escape_errorlog_item(errstr + len, scratch,
+                                    MAX_STRING_LEN - len);
+    }
+#else
     len += apr_vsnprintf(errstr + len, MAX_STRING_LEN - len, fmt, args);
+#endif
 
-    if (r && (referer = apr_table_get(r->headers_in, "Referer"))) {
+    if (   r && (referer = apr_table_get(r->headers_in, "Referer"))
+#ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
+        && escape_errorlog_item(scratch, referer, MAX_STRING_LEN - len)
+#endif
+        ) {
         len += apr_snprintf(errstr + len, MAX_STRING_LEN - len,
-                            ", referer: %s", referer);
+                            ", referer: %s",
+#ifndef AP_UNSAFE_ERROR_LOG_UNESCAPED
+                            scratch
+#else
+                            referer
+#endif
+                            );
     }
 
     /* NULL if we are logging to syslog */
@@ -570,7 +682,7 @@
     va_list args;
 
     va_start(args, fmt);
-    log_error_core(file, line, level, status, s, NULL, NULL, fmt, args);
+    log_error_core(file, line, level, status, s, NULL, NULL, NULL, fmt, args);
     va_end(args);
 }
 
@@ -581,7 +693,7 @@
     va_list args;
 
     va_start(args, fmt);
-    log_error_core(file, line, level, status, NULL, NULL, p, fmt, args);
+    log_error_core(file, line, level, status, NULL, NULL, NULL, p, fmt, args);
     va_end(args);
 }
 
@@ -592,7 +704,8 @@
     va_list args;
 
     va_start(args, fmt);
-    log_error_core(file, line, level, status, r->server, r, NULL, fmt, args);
+    log_error_core(file, line, level, status, r->server, NULL, r, NULL, fmt,
+                   args);
 
     /*
      * IF APLOG_TOCLIENT is set,
@@ -613,6 +726,18 @@
     va_end(args);
 }
 
+AP_DECLARE(void) ap_log_cerror(const char *file, int line, int level,
+                               apr_status_t status, const conn_rec *c,
+                               const char *fmt, ...)
+{
+    va_list args;
+
+    va_start(args, fmt);
+    log_error_core(file, line, level, status, c->base_server, c, NULL, NULL,
+                   fmt, args);
+    va_end(args);
+}
+
 AP_DECLARE(void) ap_log_pid(apr_pool_t *p, const char *filename)
 {
     apr_file_t *pid_file = NULL;
@@ -743,6 +868,8 @@
     apr_status_t status;
 
     if (((status = apr_procattr_create(&procattr, pl->p)) != APR_SUCCESS) ||
+        ((status = apr_procattr_cmdtype_set(procattr,
+                                            PIPED_LOGGER_CMDTYPE)) != APR_SUCCESS) || 
         ((status = apr_procattr_child_in_set(procattr,
                                              ap_piped_log_read_fd(pl),
                                              ap_piped_log_write_fd(pl)))
@@ -772,6 +899,7 @@
             ap_piped_log_write_fd(pl) = procnew->in;
             apr_proc_other_child_register(procnew, piped_log_maintenance, pl,
                                           ap_piped_log_write_fd(pl), pl->p);
+            close_handle_in_child(pl->p, ap_piped_log_read_fd(pl));
         }
         else {
             char buf[120];
Index: server/main.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/main.c,v
retrieving revision 1.1.1.1
retrieving revision 1.7
diff -u -u -r1.1.1.1 -r1.7
--- server/main.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/main.c	31 Jan 2006 22:06:44 -0000	1.7
@@ -78,6 +78,8 @@
 #include "util_ebcdic.h"
 #include "ap_mpm.h"
 #include "mpm_common.h"
+#include "ihsbuild.h"
+#include "vulnlist.h"
 
 /* WARNING: Win32 binds http_main.c dynamically to the server. Please place
  *          extern functions and global data in another appropriate module.
@@ -90,6 +92,7 @@
 {
     printf("Server version: %s\n", ap_get_server_version());
     printf("Server built:   %s\n", ap_get_server_built());
+    printf("Build level:    %s\n", IHSBUILD_TAG);
     printf("Server's Module Magic Number: %u:%u\n",
            MODULE_MAGIC_NUMBER_MAJOR, MODULE_MAGIC_NUMBER_MINOR);
 
@@ -243,6 +246,9 @@
 #ifdef SERVER_CONFIG_FILE
     printf(" -D SERVER_CONFIG_FILE=\"" SERVER_CONFIG_FILE "\"\n");
 #endif
+
+    printf("Apache vulnerability fixes included:\n%s\n",
+           cve_fix_list);
 }
 
 static void destroy_and_exit_process(process_rec *process,
@@ -582,6 +588,7 @@
     ap_fixup_virtual_hosts(pconf, server_conf);
     ap_fini_vhost_config(pconf, server_conf);
     apr_hook_sort_all();
+    ihs_save_hook_info();
     if (configtestonly) {
         ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, "Syntax OK");
         destroy_and_exit_process(process, 0);
@@ -600,13 +607,13 @@
 
     if ( ap_run_open_logs(pconf, plog, ptemp, server_conf) != OK) {
         ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR,
-                     0, NULL, "Unable to open logs\n");
+                     0, NULL, "Unable to open logs");
         destroy_and_exit_process(process, 1);
     }
 
     if ( ap_run_post_config(pconf, plog, ptemp, server_conf) != OK) {
         ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR, 0,
-                     NULL, "Configuration Failed\n");
+                     NULL, "Configuration Failed");
         destroy_and_exit_process(process, 1);
     }
 
@@ -639,16 +646,17 @@
         ap_fixup_virtual_hosts(pconf, server_conf);
         ap_fini_vhost_config(pconf, server_conf);
         apr_hook_sort_all();
+        ihs_save_hook_info();
         apr_pool_clear(plog);
         if (ap_run_open_logs(pconf, plog, ptemp, server_conf) != OK) {
             ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR,
-                         0, NULL, "Unable to open logs\n");
+                         0, NULL, "Unable to open logs");
             destroy_and_exit_process(process, 1);
         }
 
         if (ap_run_post_config(pconf, plog, ptemp, server_conf) != OK) {
             ap_log_error(APLOG_MARK, APLOG_STARTUP |APLOG_ERR,
-                         0, NULL, "Configuration Failed\n");
+                         0, NULL, "Configuration Failed");
             destroy_and_exit_process(process, 1);
         }
 
Index: server/mpm_common.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/mpm_common.c,v
retrieving revision 1.1.1.1
retrieving revision 1.7
diff -u -u -r1.1.1.1 -r1.7
--- server/mpm_common.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/mpm_common.c	22 Feb 2005 18:37:08 -0000	1.7
@@ -99,105 +99,203 @@
 #endif
 
 #ifdef AP_MPM_WANT_RECLAIM_CHILD_PROCESSES
+
+typedef enum {DO_NOTHING, SEND_SIGTERM, SEND_SIGKILL, GIVEUP} action_t;
+
+typedef struct extra_process_t {
+    struct extra_process_t *next;
+    pid_t pid;
+} extra_process_t;
+
+static extra_process_t *extras;
+
+void ap_register_extra_mpm_process(pid_t pid)
+{
+    extra_process_t *p = (extra_process_t *)malloc(sizeof(extra_process_t));
+
+    p->next = extras;
+    p->pid = pid;
+    extras = p;
+}
+
+int ap_unregister_extra_mpm_process(pid_t pid)
+{
+    extra_process_t *cur = extras;
+    extra_process_t *prev = NULL;
+
+    while (cur && cur->pid != pid) {
+        prev = cur;
+        cur = cur->next;
+    }
+
+    if (cur) {
+        if (prev) {
+            prev->next = cur->next;
+        }
+        else {
+            extras = cur->next;
+        }
+        free(cur);
+        return 1; /* found */
+    }
+    else {
+        /* we don't know about any such process */
+        return 0;
+    }
+}
+
+static int reclaim_one_pid(pid_t pid, action_t action)
+{
+    apr_proc_t proc;
+    apr_status_t waitret;
+
+    proc.pid = pid;
+    waitret = apr_proc_wait(&proc, NULL, NULL, APR_NOWAIT);
+    if (waitret != APR_CHILD_NOTDONE) {
+        return 1;
+    }
+
+    switch(action) {
+    case DO_NOTHING:
+        break;
+        
+    case SEND_SIGTERM:
+        /* ok, now it's being annoying */
+        ap_log_error(APLOG_MARK, APLOG_WARNING,
+                     0, ap_server_conf,
+                     "child process %" APR_PID_T_FMT
+                     " still did not exit, "
+                     "sending a SIGTERM",
+                     pid);
+        kill(pid, SIGTERM);
+        break;
+        
+    case SEND_SIGKILL:
+        ap_log_error(APLOG_MARK, APLOG_ERR,
+                     0, ap_server_conf,
+                     "child process %" APR_PID_T_FMT
+                     " still did not exit, "
+                     "sending a SIGKILL",
+                     pid);
+#ifndef BEOS
+        kill(pid, SIGKILL);
+#else
+        /* sending a SIGKILL kills the entire team on BeOS, and as
+         * httpd thread is part of that team it removes any chance
+         * of ever doing a restart.  To counter this I'm changing to
+         * use a kinder, gentler way of killing a specific thread
+         * that is just as effective.
+         */
+        kill_thread(pid);
+#endif
+        break;
+                
+    case GIVEUP:
+        /* gave it our best shot, but alas...  If this really
+         * is a child we are trying to kill and it really hasn't
+         * exited, we will likely fail to bind to the port
+         * after the restart.
+         */
+        ap_log_error(APLOG_MARK, APLOG_ERR,
+                     0, ap_server_conf,
+                     "could not make child process %" APR_PID_T_FMT
+                     " exit, "
+                     "attempting to continue anyway",
+                     pid);
+        break;
+    }
+    
+    return 0;
+}
+
 void ap_reclaim_child_processes(int terminate)
 {
+    apr_time_t waittime = 1024 * 16;
     int i;
-    long int waittime = 1024 * 16;      /* in usecs */
-    apr_status_t waitret;
-    int tries;
+    extra_process_t *cur_extra;
     int not_dead_yet;
     int max_daemons;
+    apr_time_t starttime = apr_time_now();
+    /* this table of actions and elapsed times tells what action is taken
+     * at which elapsed time from starting the reclaim
+     */
+    struct {
+        action_t action;
+        apr_time_t action_time;
+    } action_table[] = {
+        {DO_NOTHING, 0}, /* dummy entry for iterations where we reap
+                          * children but take no action against
+                          * stragglers
+                          */
+        {SEND_SIGTERM, apr_time_from_sec(3)},
+        {SEND_SIGTERM, apr_time_from_sec(5)},
+        {SEND_SIGTERM, apr_time_from_sec(7)},
+        {SEND_SIGKILL, apr_time_from_sec(9)},
+        {GIVEUP,       apr_time_from_sec(10)}
+    };
+    int cur_action;      /* index of action we decided to take this
+                          * iteration
+                          */
+    int next_action = 1; /* index of first real action */
 
     ap_mpm_query(AP_MPMQ_MAX_DAEMON_USED, &max_daemons);
 
-    for (tries = terminate ? 4 : 1; tries <= 9; ++tries) {
-        /* don't want to hold up progress any more than
-         * necessary, but we need to allow children a few moments to exit.
-         * Set delay with an exponential backoff.
-         */
+    do {
         apr_sleep(waittime);
+        /* don't let waittime get longer than 1 second; otherwise, we don't
+         * react quickly to the last child exiting, and taking action can
+         * be delayed
+         */
         waittime = waittime * 4;
+        if (waittime > apr_time_from_sec(1)) {
+            waittime = apr_time_from_sec(1);
+        }
+
+        /* see what action to take, if any */
+        if (action_table[next_action].action_time <= apr_time_now() - starttime) {
+            cur_action = next_action;
+            ++next_action;
+        }
+        else {
+            cur_action = 0; /* nothing to do */
+        }
 
         /* now see who is done */
         not_dead_yet = 0;
         for (i = 0; i < max_daemons; ++i) {
             pid_t pid = MPM_CHILD_PID(i);
-            apr_proc_t proc;
 
-            if (pid == 0)
-                continue;
+            if (pid == 0) {
+                continue; /* not every scoreboard entry is in use */
+            }
 
-            proc.pid = pid;
-            waitret = apr_proc_wait(&proc, NULL, NULL, APR_NOWAIT);
-            if (waitret != APR_CHILD_NOTDONE) {
+            if (reclaim_one_pid(pid, action_table[cur_action].action)) {
                 MPM_NOTE_CHILD_KILLED(i);
                 continue;
             }
-
-            ++not_dead_yet;
-            switch (tries) {
-            case 1:     /*  16ms */
-            case 2:     /*  82ms */
-            case 3:     /* 344ms */
-            case 4:     /*  16ms */
-                break;
-
-            case 5:     /*  82ms */
-            case 6:     /* 344ms */
-            case 7:     /* 1.4sec */
-                /* ok, now it's being annoying */
-                ap_log_error(APLOG_MARK, APLOG_WARNING,
-                             0, ap_server_conf,
-                             "child process %ld still did not exit, "
-                             "sending a SIGTERM",
-                             (long)pid);
-                kill(pid, SIGTERM);
-                break;
-
-            case 8:     /*  6 sec */
-                /* die child scum */
-                ap_log_error(APLOG_MARK, APLOG_ERR,
-                             0, ap_server_conf,
-                             "child process %ld still did not exit, "
-                             "sending a SIGKILL",
-                             (long)pid);
-#ifndef BEOS
-                kill(pid, SIGKILL);
-#else
-                /* sending a SIGKILL kills the entire team on BeOS, and as
-                 * httpd thread is part of that team it removes any chance
-                 * of ever doing a restart.  To counter this I'm changing to
-                 * use a kinder, gentler way of killing a specific thread
-                 * that is just as effective.
-                 */
-                kill_thread(pid);
-#endif
-                break;
-
-            case 9:     /* 14 sec */
-                /* gave it our best shot, but alas...  If this really
-                 * is a child we are trying to kill and it really hasn't
-                 * exited, we will likely fail to bind to the port
-                 * after the restart.
-                 */
-                ap_log_error(APLOG_MARK, APLOG_ERR,
-                             0, ap_server_conf,
-                             "could not make child process %ld exit, "
-                             "attempting to continue anyway",
-                             (long)pid);
-                break;
+            else {
+                ++not_dead_yet;
             }
         }
 
+        cur_extra = extras;
+        while (cur_extra) {
+            extra_process_t *next = cur_extra->next;
+
+            if (reclaim_one_pid(cur_extra->pid, action_table[cur_action].action)) {
+                AP_DEBUG_ASSERT(1 == ap_unregister_extra_mpm_process(cur_extra->pid));
+            }
+            else {
+                ++not_dead_yet;
+            }
+            cur_extra = next;
+        }
 #if APR_HAS_OTHER_CHILD
         apr_proc_other_child_check();
 #endif
 
-        if (!not_dead_yet) {
-            /* nothing left to wait for */
-            break;
-        }
-    }
+    } while (not_dead_yet > 0 &&
+             action_table[cur_action].action != GIVEUP);
 }
 #endif /* AP_MPM_WANT_RECLAIM_CHILD_PROCESSES */
 
@@ -264,8 +362,7 @@
             ap_log_error(APLOG_MARK, APLOG_ALERT,
                          0, ap_server_conf,
                          "Child %" APR_PID_T_FMT
-                         " returned a Fatal error..." APR_EOL_STR
-                         "Apache is exiting!",
+			 " returned a Fatal error... Apache is exiting!",
                          pid->pid);
             return APEXIT_CHILDFATAL;
         }
@@ -910,3 +1007,57 @@
 }
 
 #endif /* AP_MPM_WANT_SET_MAX_MEM_FREE */
+
+#if AP_ENABLE_EXCEPTION_HOOK
+
+int ihs_exception_hook_enabled;
+
+const char *ap_mpm_set_exception_hook(cmd_parms *cmd, void *dummy,
+                                      const char *arg)
+{
+    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+    if (err != NULL) {
+        return err;
+    }
+
+    if (cmd->server->is_virtual) {
+	return "EnableExceptionHook directive not allowed in <VirtualHost>";
+    }
+
+    if (strcasecmp(arg, "on") == 0) {
+        ihs_exception_hook_enabled = 1;
+    }
+    else if (strcasecmp(arg, "off") == 0) {
+        ihs_exception_hook_enabled = 0;
+    }
+    else {
+        return "parameter must be 'on' or 'off'";
+    }
+
+    return NULL;
+}
+#endif /* AP_ENABLE_EXCEPTION_HOOK */
+
+#ifdef AP_MPM_WANT_SET_STACKSIZE
+apr_size_t ap_thread_stacksize = 0; /* use system default */
+
+const char *ap_mpm_set_thread_stacksize(cmd_parms *cmd, void *dummy,
+                                        const char *arg)
+{
+    long value;
+    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+    if (err != NULL) {
+        return err;
+    }
+    
+    value = strtol(arg, NULL, 0);
+    if (value < 0 || errno == ERANGE)
+        return apr_pstrcat(cmd->pool, "Invalid ThreadStackSize value: ", 
+                           arg, NULL);
+
+    ap_thread_stacksize = (apr_size_t)value;
+
+    return NULL;
+}
+
+#endif /* AP_MPM_WANT_SET_STACKSIZE */
Index: server/protocol.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/protocol.c,v
retrieving revision 1.1.1.1
retrieving revision 1.22
diff -u -u -r1.1.1.1 -r1.22
--- server/protocol.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/protocol.c	13 Apr 2006 20:26:37 -0000	1.22
@@ -1,59 +1,16 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/* Copyright 2001-2004 The Apache Software Foundation
  *
- * Copyright (c) 2000-2003 The Apache Software Foundation.  All rights
- * reserved.
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Apache" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- * Portions of this software are based upon public domain software
- * originally written at the National Center for Supercomputing Applications,
- * University of Illinois, Urbana-Champaign.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 /*
@@ -90,6 +47,7 @@
 #include "mod_core.h"
 #include "util_charset.h"
 #include "util_ebcdic.h"
+#include "scoreboard.h"
 
 #if APR_HAVE_STDARG_H
 #include <stdarg.h>
@@ -147,6 +105,7 @@
     core_dir_config *conf =
         (core_dir_config *)ap_get_module_config(r->per_dir_config,
                                                 &core_module);
+    core_request_config *request_conf;
     apr_size_t type_len;
 
     if (!type) {
@@ -157,6 +116,12 @@
         return type;
     }
 
+    request_conf =
+        ap_get_module_config(r->request_config, &core_module);
+    if (request_conf->suppress_charset) {
+        return type;
+    }
+
     type_len = strlen(type);
 
     if (apr_strmatch(charset_pattern, type, type_len) != NULL) {
@@ -292,6 +257,15 @@
         /* Would this overrun our buffer?  If so, we'll die. */
         if (n < bytes_handled + len) {
             *read = bytes_handled;
+            if (*s) {
+                /* ensure this string is NUL terminated */
+                if (bytes_handled > 0) {
+                    (*s)[bytes_handled-1] = '\0';
+                }
+                else {
+                    (*s)[0] = '\0';
+                }
+            }
             return APR_ENOSPC;
         }
 
@@ -338,35 +312,13 @@
         }
     }
 
-    /* We now go backwards over any CR (if present) or white spaces.
-     *
-     * Trim any extra trailing spaces or tabs except for the first
-     * space or tab at the beginning of a blank string.  This makes
-     * it much easier to check field values for exact matches, and
-     * saves memory as well.  Terminate string at end of line.
-     */
-    pos = last_char;
-    if (pos > *s && *(pos - 1) == APR_ASCII_CR) {
-        --pos;
+    /* Now NUL-terminate the string at the end of the line; 
+     * if the last-but-one character is a CR, terminate there */
+    if (last_char > *s && last_char[-1] == APR_ASCII_CR) {
+        last_char--;
     }
-
-    /* Trim any extra trailing spaces or tabs except for the first
-     * space or tab at the beginning of a blank string.  This makes
-     * it much easier to check field values for exact matches, and
-     * saves memory as well.
-     */
-    while (pos > ((*s) + 1)
-           && (*(pos - 1) == APR_ASCII_BLANK || *(pos - 1) == APR_ASCII_TAB)) {
-        --pos;
-    }
-
-    /* Since we want to remove the LF from the line, we'll go ahead
-     * and set this last character to be the term NULL and reset
-     * bytes_handled accordingly.
-     */
-    *pos = '\0';
-    last_char = pos;
-    bytes_handled = pos - *s;
+    *last_char = '\0';
+    bytes_handled = last_char - *s;
 
     /* If we're folding, we have more work to do.
      *
@@ -422,6 +374,8 @@
             /* Do we have enough space? We may be full now. */
                 if (bytes_handled >= n) {
                     *read = n;
+                    /* ensure this string is terminated */
+                    (*s)[n-1] = '\0';
                     return APR_ENOSPC;
                 }
                 else {
@@ -620,11 +574,22 @@
          * if there are empty lines
          */
         r->the_request = NULL;
-        rv = ap_rgetline(&(r->the_request), DEFAULT_LIMIT_REQUEST_LINE + 2,
+        rv = ap_rgetline(&(r->the_request), (apr_size_t)(r->server->limit_req_line + 2),
                          &len, r, 0, bb);
 
         if (rv != APR_SUCCESS) {
             r->request_time = apr_time_now();
+
+            /* ap_rgetline returns APR_ENOSPC if it fills up the
+             * buffer before finding the end-of-line.  This is only going to
+             * happen if it exceeds the configured limit for a request-line.
+             */
+            if (rv == APR_ENOSPC) {
+                r->status    = HTTP_REQUEST_URI_TOO_LARGE;
+                r->proto_num = HTTP_VERSION(1,0);
+                r->protocol  = apr_pstrdup(r->pool, "HTTP/1.0");
+            }
+
             return 0;
         }
     } while ((len <= 0) && (++num_blank_lines < max_blank_lines));
@@ -654,18 +619,6 @@
 
     ap_parse_uri(r, uri);
 
-    /* ap_getline returns (size of max buffer - 1) if it fills up the
-     * buffer before finding the end-of-line.  This is only going to
-     * happen if it exceeds the configured limit for a request-line.
-     * The cast is safe, limit_req_line cannot be negative
-     */
-    if (len > (apr_size_t)r->server->limit_req_line) {
-        r->status    = HTTP_REQUEST_URI_TOO_LARGE;
-        r->proto_num = HTTP_VERSION(1,0);
-        r->protocol  = apr_pstrdup(r->pool, "HTTP/1.0");
-        return 0;
-    }
-
     if (ll[0]) {
         r->assbackwards = 0;
         pro = ll;
@@ -705,10 +658,7 @@
     char *value;
     apr_size_t len;
     int fields_read = 0;
-    apr_table_t *tmp_headers;
-
-    /* We'll use apr_table_overlap later to merge these into r->headers_in. */
-    tmp_headers = apr_table_make(r->pool, 50);
+    char *tmp_field;
 
     /*
      * Read header lines until we get the empty separator line, a read error,
@@ -754,6 +704,23 @@
                  * continuations that span many many lines.
                  */
                 apr_size_t fold_len = last_len + len + 1; /* trailing null */
+
+                if ((fold_len - 1) > r->server->limit_req_fieldsize) {
+                    r->status = HTTP_BAD_REQUEST;
+                    /* report what we have accumulated so far before the
+                     * overflow (last_field) as the field with the problem
+                     */
+                    apr_table_setn(r->notes, "error-notes",
+                                   apr_pstrcat(r->pool,
+                                               "Size of a request header field " 
+                                               "after folding "
+                                               "exceeds server limit.<br />\n"
+                                               "<pre>\n",
+                                               ap_escape_html(r->pool, last_field),
+                                               "</pre>\n", NULL));
+                    return;
+                }
+
                 if (fold_len > alloc_len) {
                     char *fold_buf;
                     alloc_len += alloc_len;
@@ -768,7 +735,7 @@
                 last_len += len;
                 folded = 1;
             }
-            else {
+            else /* not a continuation line */ {
 
                 if (r->server->limit_req_fields
                     && (++fields_read > r->server->limit_req_fields)) {
@@ -792,18 +759,33 @@
                     return;
                 }
 
-                *value = '\0';
-                ++value;
+                tmp_field = value - 1; /* last character of field-name */
+
+                *value++ = '\0'; /* NUL-terminate at colon */
+
                 while (*value == ' ' || *value == '\t') {
                     ++value;            /* Skip to start of value   */
                 }
 
-                apr_table_addn(tmp_headers, last_field, value);
+                /* Strip LWS after field-name: */
+                while (tmp_field > last_field 
+                       && (*tmp_field == ' ' || *tmp_field == '\t')) {
+                    *tmp_field-- = '\0';
+                    }
+                
+                /* Strip LWS after field-value: */
+                tmp_field = last_field + last_len - 1;
+                while (tmp_field > value
+                       && (*tmp_field == ' ' || *tmp_field == '\t')) {
+                    *tmp_field-- = '\0';
+                }
+
+                apr_table_addn(r->headers_in, last_field, value);
 
                 /* reset the alloc_len so that we'll allocate a new
                  * buffer if we have to do any more folding: we can't
                  * use the previous buffer because its contents are
-                 * now part of tmp_headers
+                 * now part of r->headers_in
                  */
                 alloc_len = 0;
 
@@ -825,7 +807,7 @@
         }
     }
 
-    apr_table_overlap(r->headers_in, tmp_headers, APR_OVERLAP_TABLES_MERGE);
+    apr_table_compress(r->headers_in, APR_OVERLAP_TABLES_MERGE);
 }
 
 AP_DECLARE(void) ap_get_mime_headers(request_rec *r)
@@ -845,6 +827,7 @@
     apr_bucket_brigade *tmp_bb;
 
     apr_pool_create(&p, conn->pool);
+    apr_pool_tag(p, "request");
     r = apr_pcalloc(p, sizeof(request_rec));
     r->pool            = p;
     r->connection      = conn;
@@ -885,9 +868,10 @@
     if (!read_request_line(r, tmp_bb)) {
         if (r->status == HTTP_REQUEST_URI_TOO_LARGE) {
             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
-                          "request failed: URI too long");
+                          "request failed: URI too long (longer than %d)", r->server->limit_req_line);
             ap_send_error_response(r, 0);
-            ap_run_log_transaction(r);
+            ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
+            ihs_run_log_transaction(r);
             apr_brigade_destroy(tmp_bb);
             return r;
         }
@@ -902,10 +886,20 @@
             ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                           "request failed: error reading the headers");
             ap_send_error_response(r, 0);
-            ap_run_log_transaction(r);
+            ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
+            ihs_run_log_transaction(r);
             apr_brigade_destroy(tmp_bb);
             return r;
         }
+
+        if (apr_table_get(r->headers_in, "Transfer-Encoding")
+            && apr_table_get(r->headers_in, "Content-Length")) {
+            /* 2616 section 4.4, point 3: "if both Transfer-Encoding
+             * and Content-Length are received, the latter MUST be
+             * ignored"; so unset it here to prevent any confusion
+             * later. */
+            apr_table_unset(r->headers_in, "Content-Length");
+        }
     }
     else {
         if (r->header_only) {
@@ -920,7 +914,8 @@
             r->header_only = 0;
             r->status = HTTP_BAD_REQUEST;
             ap_send_error_response(r, 0);
-            ap_run_log_transaction(r);
+            ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
+            ihs_run_log_transaction(r);
             apr_brigade_destroy(tmp_bb);
             return r;
         }
@@ -956,7 +951,8 @@
 
     if (r->status != HTTP_OK) {
         ap_send_error_response(r, 0);
-        ap_run_log_transaction(r);
+        ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
+        ihs_run_log_transaction(r);
         return r;
     }
 
@@ -977,7 +973,8 @@
                           "client sent an unrecognized expectation value of "
                           "Expect: %s", expect);
             ap_send_error_response(r, 0);
-            ap_run_log_transaction(r);
+            ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
+            ihs_run_log_transaction(r);
             return r;
         }
     }
@@ -987,13 +984,35 @@
 
     if ((access_status = ap_run_post_read_request(r))) {
         ap_die(access_status, r);
-        ap_run_log_transaction(r);
+        ap_update_child_status(conn->sbh, SERVER_BUSY_LOG, r);
+        ihs_run_log_transaction(r);
         return NULL;
     }
 
     return r;
 }
 
+/* if a request with a body creates a subrequest, clone the original request's
+ * input headers minus any headers pertaining to the body which has already
+ * been read.  out-of-line helper function for ap_set_sub_req_protocol.
+ */
+
+static void clone_headers_no_body(request_rec *rnew,
+                                  const request_rec *r)
+{
+    rnew->headers_in = apr_table_copy(rnew->pool, r->headers_in);
+    apr_table_unset(rnew->headers_in, "Content-Encoding");
+    apr_table_unset(rnew->headers_in, "Content-Language");
+    apr_table_unset(rnew->headers_in, "Content-Length");
+    apr_table_unset(rnew->headers_in, "Content-Location");
+    apr_table_unset(rnew->headers_in, "Content-MD5");
+    apr_table_unset(rnew->headers_in, "Content-Range");
+    apr_table_unset(rnew->headers_in, "Content-Type");
+    apr_table_unset(rnew->headers_in, "Expires");
+    apr_table_unset(rnew->headers_in, "Last-Modified");
+    apr_table_unset(rnew->headers_in, "Transfer-Encoding");
+}        
+
 /*
  * A couple of other functions which initialize some of the fields of
  * a request structure, as appropriate for adjuncts of one kind or another
@@ -1014,7 +1033,16 @@
 
     rnew->status          = HTTP_OK;
 
-    rnew->headers_in      = r->headers_in;
+    /* did the original request have a body?  (e.g. POST w/SSI tags)
+     * if so, make sure the subrequest doesn't inherit body headers
+     */
+    if (apr_table_get(r->headers_in, "Content-Length")
+        || apr_table_get(r->headers_in, "Transfer-Encoding")) {
+        clone_headers_no_body(rnew, r);
+    } else {
+        /* no body (common case).  clone headers the cheap way */
+        rnew->headers_in      = r->headers_in;
+    }
     rnew->subprocess_env  = apr_table_copy(rnew->pool, r->subprocess_env);
     rnew->headers_out     = apr_table_make(rnew->pool, 5);
     rnew->err_headers_out = apr_table_make(rnew->pool, 5);
@@ -1142,10 +1170,6 @@
     }
 
     t = ap_pbase64decode(r->pool, auth_line);
-    /* Note that this allocation has to be made from r->connection->pool
-     * because it has the lifetime of the connection.  The other allocations
-     * are temporary and can be tossed away any time.
-     */
     r->user = ap_getword_nulls (r->pool, &t, ':');
     r->ap_auth_type = "Basic";
 
@@ -1244,7 +1268,13 @@
      * We can only set a C-L in the response header if we haven't already
      * sent any buckets on to the next output filter for this request.
      */
-    if (ctx->data_sent == 0 && eos) {
+    if (ctx->data_sent == 0 && eos && 
+         /* don't whack the C-L if it has already been set for a HEAD
+          * by something like proxy.  the brigade only has an EOS bucket
+          * in this case, making r->bytes_sent zero.
+          */
+        !(r->header_only && r->bytes_sent == 0 && 
+            apr_table_get(r->headers_out, "Content-Length"))) {
         ap_set_content_length(r, r->bytes_sent);
     }
 
Index: server/request.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/request.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- server/request.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/request.c	8 Mar 2005 19:53:29 -0000	1.3
@@ -227,12 +227,12 @@
         switch (ap_satisfies(r)) {
         case SATISFY_ALL:
         case SATISFY_NOSPEC:
-            if ((access_status = ap_run_access_checker(r)) != 0) {
+            if ((access_status = ihs_run_access_checker(r)) != 0) {
                 return decl_die(access_status, "check access", r);
             }
 
             if (ap_some_auth_required(r)) {
-                if (((access_status = ap_run_check_user_id(r)) != 0)
+                if (((access_status = ihs_run_check_user_id(r)) != 0)
                     || !ap_auth_type(r)) {
                     return decl_die(access_status, ap_auth_type(r)
                                   ? "check user.  No user file?"
@@ -251,12 +251,12 @@
             break;
 
         case SATISFY_ANY:
-            if (((access_status = ap_run_access_checker(r)) != 0)) {
+            if (((access_status = ihs_run_access_checker(r)) != 0)) {
                 if (!ap_some_auth_required(r)) {
                     return decl_die(access_status, "check access", r);
                 }
 
-                if (((access_status = ap_run_check_user_id(r)) != 0)
+                if (((access_status = ihs_run_check_user_id(r)) != 0)
                     || !ap_auth_type(r)) {
                     return decl_die(access_status, ap_auth_type(r)
                                   ? "check user.  No user file?"
@@ -1505,6 +1505,7 @@
     request_rec *rnew;
 
     apr_pool_create(&rrp, r->pool);
+    apr_pool_tag(rrp, "subrequest");
     rnew = apr_pcalloc(rrp, sizeof(request_rec));
     rnew->pool = rrp;
 
Index: server/scoreboard.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/scoreboard.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- server/scoreboard.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/scoreboard.c	1 Jun 2005 12:25:50 -0000	1.2
@@ -466,15 +466,15 @@
                                                status, r);
 }
 
-void ap_time_process_request(int child_num, int thread_num, int status)
+void ap_time_process_request(ap_sb_handle_t *sbh, int status)
 {
     worker_score *ws;
 
-    if (child_num < 0) {
+    if (sbh->child_num < 0) {
         return;
     }
 
-    ws = &ap_scoreboard_image->servers[child_num][thread_num];
+    ws = &ap_scoreboard_image->servers[sbh->child_num][sbh->thread_num];
 
     if (status == START_PREQUEST) {
         ws->start_time = apr_time_now(); 
Index: server/util.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/util.c,v
retrieving revision 1.1.1.1
retrieving revision 1.6
diff -u -u -r1.1.1.1 -r1.6
--- server/util.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/util.c	12 Dec 2005 17:39:17 -0000	1.6
@@ -765,7 +765,7 @@
 
     *resp++ = '\0';
 #if RESOLVE_ENV_PER_TOKEN
-    return ap_resolve_env(p,result);
+    return (char *)ap_resolve_env(p,result);
 #else
     return result;
 #endif
@@ -825,39 +825,87 @@
  */
 AP_DECLARE(const char *) ap_resolve_env(apr_pool_t *p, const char * word)
 {
-       char tmp[ MAX_STRING_LEN ];
-       const char *s, *e;
-       tmp[0] = '\0';
-
-       if (!(s=ap_strchr_c(word,'$')))
-               return word;
-
-       do {
-               /* XXX - relies on strncat() to add '\0'
-                */
-               strncat(tmp,word,s - word);
-               if ((s[1] == '{') && (e=ap_strchr_c(s,'}'))) {
-                       const char *e2 = e;
-                       char *var;
-                       word = e + 1;
-                       var = apr_pstrndup(p, s+2, e2-(s+2));
-                       e = getenv(var);
-                       if (e) {
-                           strcat(tmp,e);
-                       } else {
-                           strncat(tmp, s, e2-s);
-                           strcat(tmp,"}");
-                       }
-               } else {
-                       /* ignore invalid strings */
-                       word = s+1;
-                       strcat(tmp,"$");
-               };
-       } while ((s=ap_strchr_c(word,'$')));
-       strcat(tmp,word);
+# define SMALL_EXPANSION 5
+    struct sll {
+        struct sll *next;
+        const char *string;
+        apr_size_t len;
+    } *result, *current, sresult[SMALL_EXPANSION];
+    char *res_buf, *cp;
+    const char *s, *e, *ep;
+    unsigned spc;
+    apr_size_t outlen;
+
+    s = ap_strchr_c(word, '$');
+    if (!s) {
+        return word;
+    }
+
+    /* well, actually something to do */
+    ep = word + strlen(word);
+    spc = 0;
+    result = current = &(sresult[spc++]);
+    current->next = NULL;
+    current->string = word;
+    current->len = s - word;
+    outlen = current->len;
+
+    do {
+        /* prepare next entry */
+        if (current->len) {
+            current->next = (spc < SMALL_EXPANSION)
+                            ? &(sresult[spc++])
+                            : (struct sll *)apr_palloc(p,
+                                                       sizeof(*current->next));
+            current = current->next;
+            current->next = NULL;
+            current->len = 0;
+        }
+
+        if (*s == '$') {
+            if (s[1] == '{' && (e = ap_strchr_c(s, '}'))) {
+                word = getenv(apr_pstrndup(p, s+2, e-s-2));
+                if (word) {
+                    current->string = word;
+                    current->len = strlen(word);
+                    outlen += current->len;
+                }
+                else {
+                    current->string = s;
+                    current->len = e - s + 1;
+                    outlen += current->len;
+                }
+                s = e + 1;
+            }
+            else {
+                current->string = s++;
+                current->len = 1;
+                ++outlen;
+            }
+        }
+        else {
+            word = s;
+            s = ap_strchr_c(s, '$');
+            current->string = word;
+            current->len = s ? s - word : ep - word;
+            outlen += current->len;
+        }
+    } while (s && *s);
+
+    /* assemble result */
+    res_buf = cp = apr_palloc(p, outlen + 1);
+    do {
+        if (result->len) {
+            memcpy(cp, result->string, result->len);
+            cp += result->len;
+        }
+        result = result->next;
+    } while (result);
+    res_buf[outlen] = '\0';
 
-       return apr_pstrdup(p,tmp);
+    return res_buf;
 }
+
 AP_DECLARE(int) ap_cfg_closefile(ap_configfile_t *cfp)
 {
 #ifdef DEBUG
@@ -1623,16 +1671,12 @@
             else {
                 char decoded;
                 decoded = x2c(y + 1);
-                if (IS_SLASH(decoded)) {
-                    *x++ = *y++;
-                    *x = *y;
+                if (decoded == '\0') {
+                    badpath = 1;
                 }
                 else {
                     *x = decoded;
                     y += 2;
-                    if (decoded == '\0') {
-                        badpath = 1;
-                    }
                 }
             }
         }
@@ -1760,6 +1804,8 @@
             j += 3;
         else if (s[i] == '&')
             j += 4;
+        else if (s[i] == '"')
+            j += 5;
 
     if (j == 0)
         return apr_pstrmemdup(p, s, i);
@@ -1778,6 +1824,10 @@
             memcpy(&x[j], "&amp;", 5);
             j += 4;
         }
+        else if (s[i] == '"') {
+            memcpy(&x[j], "&quot;", 6);
+            j += 5;
+        }
         else
             x[j] = s[i];
 
@@ -1835,6 +1885,70 @@
     *d = '\0';
 
     return ret;
+}
+
+AP_DECLARE(apr_size_t) ap_escape_errorlog_item(char *dest, const char *source,
+                                               apr_size_t buflen)
+{
+    unsigned char *d, *ep;
+    const unsigned char *s;
+
+    if (!source || !buflen) { /* be safe */
+        return 0;
+    }
+
+    d = (unsigned char *)dest;
+    s = (const unsigned char *)source;
+    ep = d + buflen - 1;
+
+    for (; d < ep && *s; ++s) {
+
+        if (TEST_CHAR(*s, T_ESCAPE_LOGITEM)) {
+            *d++ = '\\';
+            if (d >= ep) {
+                --d;
+                break;
+            }
+
+            switch(*s) {
+            case '\b':
+                *d++ = 'b';
+                break;
+            case '\n':
+                *d++ = 'n';
+                break;
+            case '\r':
+                *d++ = 'r';
+                break;
+            case '\t':
+                *d++ = 't';
+                break;
+            case '\v':
+                *d++ = 'v';
+                break;
+            case '\\':
+                *d++ = *s;
+                break;
+            case '"': /* no need for this in error log */
+                d[-1] = *s;
+                break;
+            default:
+                if (d >= ep - 2) {
+                    ep = --d; /* break the for loop as well */
+                    break;
+                }
+                c2x(*s, d);
+                *d = 'x';
+                d += 3;
+            }
+        }
+        else {
+            *d++ = *s;
+        }
+    }
+    *d = '\0';
+
+    return (d - (unsigned char *)dest);
 }
 
 AP_DECLARE(int) ap_is_directory(apr_pool_t *p, const char *path)
Index: server/util_script.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/util_script.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- server/util_script.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/util_script.c	26 May 2005 19:01:08 -0000	1.3
@@ -286,6 +286,17 @@
     if (r->user) {
 	apr_table_addn(e, "REMOTE_USER", r->user);
     }
+    else if (r->prev) {
+        request_rec *back = r->prev;
+
+        while (back) {
+            if (back->user) {
+                apr_table_addn(e, "REDIRECT_REMOTE_USER", back->user);
+                break;
+            }
+            back = back->prev;
+        }
+    }
     if (r->ap_auth_type) {
 	apr_table_addn(e, "AUTH_TYPE", r->ap_auth_type);
     }
@@ -588,6 +599,9 @@
 	else if (!strcasecmp(w, "Content-Length")) {
 	    apr_table_set(r->headers_out, w, l);
 	}
+        else if (!strcasecmp(w, "Content-Range")) {
+            apr_table_set(r->headers_out, w, l);
+        }
 	else if (!strcasecmp(w, "Transfer-Encoding")) {
 	    apr_table_set(r->headers_out, w, l);
 	}
Index: server/vhost.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/vhost.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- server/vhost.c	29 Jul 2003 20:19:24 -0000	1.1.1.1
+++ server/vhost.c	11 Jun 2004 19:49:53 -0000	1.3
@@ -240,15 +240,18 @@
         }
     }
 
-    /* XXX Gotta go through *all* addresses for the host name! 
-     * Fix apr_sockaddr_info_get() to save them! */
+    /* Remember all addresses for the host */
+
+    do {
+        sar = apr_pcalloc(p, sizeof(server_addr_rec));
+        **paddr = sar;
+        *paddr = &sar->next;
+        sar->host_addr = my_addr;
+        sar->host_port = port;
+        sar->virthost = host;
+        my_addr = my_addr->next;
+    } while (my_addr);
 
-    sar = apr_pcalloc(p, sizeof(server_addr_rec));
-    **paddr = sar;
-    *paddr = &sar->next;
-    sar->host_addr = my_addr;
-    sar->host_port = port;
-    sar->virthost = host;
     return NULL;
 }
 
@@ -563,6 +566,8 @@
     server_rec *s;
     int i;
     ipaddr_chain **iphash_table_tail[IPHASH_TABLE_SIZE];
+    /* inaddr_any[] moved here to work around gcc bug on s/390 */
+    char inaddr_any[16] = {0}; /* big enough to handle IPv4 or IPv6 */
 
     /* terminate the name_vhost list */
     *name_vhost_list_tail = NULL;
@@ -584,7 +589,7 @@
      * occured in the config file, we'll copy it in that order.
      */
     for (sar = name_vhost_list; sar; sar = sar->next) {
-        char inaddr_any[16] = {0}; /* big enough to handle IPv4 or IPv6 */
+        /* inaddr_any[] removed here to work around gcc bug on s/390 */
         unsigned bucket = hash_addr(sar->host_addr);
         ipaddr_chain *ic = new_ipaddr_chain(p, NULL, sar);
 
@@ -616,7 +621,7 @@
         has_default_vhost_addr = 0;
         for (sar = s->addrs; sar; sar = sar->next) {
             ipaddr_chain *ic;
-            char inaddr_any[16] = {0}; /* big enough to handle IPv4 or IPv6 */
+            /* inaddr_any[] removed here to work around gcc bug on s/390 */
 
             if ((sar->host_addr->family == AF_INET &&
                  sar->host_addr->sa.sin.sin_addr.s_addr == DEFAULT_VHOST_ADDR)
Index: server/mpm/prefork/prefork.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/mpm/prefork/prefork.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- server/mpm/prefork/prefork.c	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ server/mpm/prefork/prefork.c	11 Nov 2004 23:10:29 -0000	1.3
@@ -182,6 +182,19 @@
 
 static int die_now = 0;
 
+/* IHS changes for fatal exception hook */
+APR_HOOK_STRUCT(
+    APR_HOOK_LINK(ihs_fatal_exception_received)
+    APR_HOOK_LINK(fatal_exception)
+)
+
+AP_IMPLEMENT_HOOK_RUN_ALL(int,ihs_fatal_exception_received,
+                         (ihs_exception_info_t *ei), (ei), OK, DECLINED)
+/* end of IHS changes for fatal exception hook */
+
+AP_IMPLEMENT_HOOK_RUN_ALL(int, fatal_exception,
+                          (ap_exception_info_t *ei), (ei), OK, DECLINED)
+
 #ifdef GPROF
 /* 
  * change directory for gprof to plop the gmon.out file
@@ -353,11 +366,45 @@
 }
 #endif
 
+#if AP_ENABLE_EXCEPTION_HOOK
+static void run_fatal_exception_hook(int sig)
+{
+    ap_exception_info_t ei = {0};
+
+    if (ihs_exception_hook_enabled &&
+        geteuid() != 0 && 
+        ap_my_pid != parent_pid) {
+        ei.sig = sig;
+        ei.pid = ap_my_pid;
+        ap_run_fatal_exception(&ei);
+    }
+}
+#endif
+
 /* handle all varieties of core dumping signals */
 static void sig_coredump(int sig)
 {
+    /* IHS changes for fatal exception hook */
+    ihs_exception_info_t ei = {0};
+    static volatile int hook_run_before = 0;
+    int run_hook_now;
+
+    ei.format = 0;
+    ei.sig = sig;
+    ei.pid = ap_my_pid;
+    /* don't run it again if it has ever run before in this process */
+    run_hook_now = hook_run_before == 0;
+    hook_run_before++;
+    if (run_hook_now) {
+        ap_run_ihs_fatal_exception_received(&ei);
+    }
+    /* end of IHS changes for fatal exception hook */
+
     chdir(ap_coredump_dir);
     apr_signal(sig, SIG_DFL);
+#if AP_ENABLE_EXCEPTION_HOOK
+    run_fatal_exception_hook(sig);
+#endif
     if (ap_my_pid == parent_pid) {
             ap_log_error(APLOG_MARK, APLOG_NOTICE,
                          0, ap_server_conf,
Index: server/mpm/winnt/child.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/mpm/winnt/child.c,v
retrieving revision 1.1.1.1
retrieving revision 1.11
diff -u -u -r1.1.1.1 -r1.11
--- server/mpm/winnt/child.c	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ server/mpm/winnt/child.c	5 Apr 2005 19:00:42 -0000	1.11
@@ -102,11 +102,12 @@
 static unsigned int g_blocked_threads = 0;
 static HANDLE max_requests_per_child_event;
 
-
+static apr_thread_mutex_t  *child_lock;
 static apr_thread_mutex_t  *qlock;
 static PCOMP_CONTEXT qhead = NULL;
 static PCOMP_CONTEXT qtail = NULL;
 static int num_completion_contexts = 0;
+static int max_num_completion_contexts = 0;
 static HANDLE ThreadDispatchIOCP = NULL;
 static HANDLE qwait_event = NULL;
 
@@ -155,11 +156,12 @@
         apr_thread_mutex_unlock(qlock);
   
         if (!context) {
-            /* We failed to grab a context off the queue, consider allocating a
-             * new one out of the child pool. There may be up to ap_threads_per_child
-             * contexts in the system at once.
+            /* We failed to grab a context off the queue, consider allocating
+             * a new one out of the child pool. There may be up to 
+             * (ap_threads_per_child + num_listeners) contexts in the system 
+             * at once.
              */
-            if (num_completion_contexts >= ap_threads_per_child) {
+            if (num_completion_contexts >= max_num_completion_contexts) {
                 /* All workers are busy, need to wait for one */
                 static int reported = 0;
                 if (!reported) {
@@ -185,6 +187,9 @@
                  * Multiple failures in the next two steps will cause the pchild pool
                  * to 'leak' storage. I don't think this is worth fixing...
                  */
+                apr_allocator_t *allocator;
+
+                apr_thread_mutex_lock(child_lock);
                 context = (PCOMP_CONTEXT) apr_pcalloc(pchild, sizeof(COMP_CONTEXT));
   
                 context->Overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
@@ -192,21 +197,31 @@
                     /* Hopefully this is a temporary condition ... */
                     ap_log_error(APLOG_MARK,APLOG_WARNING, apr_get_os_error(), ap_server_conf,
                                  "mpm_get_completion_context: CreateEvent failed.");
+
+                    apr_thread_mutex_unlock(child_lock);
                     return NULL;
                 }
  
                 /* Create the tranaction pool */
-                if ((rv = apr_pool_create(&context->ptrans, pchild)) != APR_SUCCESS) {
+                apr_allocator_create(&allocator);
+                apr_allocator_max_free_set(allocator, ap_max_mem_free);
+                rv = apr_pool_create_ex(&context->ptrans, pchild, NULL, allocator);
+                if (rv != APR_SUCCESS) {
                     ap_log_error(APLOG_MARK,APLOG_WARNING, rv, ap_server_conf,
                                  "mpm_get_completion_context: Failed to create the transaction pool.");
                     CloseHandle(context->Overlapped.hEvent);
+
+                    apr_thread_mutex_unlock(child_lock);
                     return NULL;
                 }
-                apr_pool_tag(context->ptrans, "ptrans");
+                apr_allocator_owner_set(allocator, context->ptrans);
+                apr_pool_tag(context->ptrans, "transaction");
  
                 context->accept_socket = INVALID_SOCKET;
                 context->ba = apr_bucket_alloc_create(pchild);
                 apr_atomic_inc(&num_completion_contexts); 
+
+                apr_thread_mutex_unlock(child_lock);
                 break;
             }
         } else {
@@ -244,16 +259,21 @@
     ap_listen_rec *lr;
     SOCKET nsd;
 
-    for (lr = head_listener; lr ; lr = lr->next) {
+    lr = head_listener;
+    do {
         apr_os_sock_get(&nsd, lr->sd);
-	if (FD_ISSET(nsd, main_fds)) {
-	    head_listener = lr->next;
-            if (head_listener == NULL)
+        if (FD_ISSET(nsd, main_fds)) {
+            head_listener = lr->next;
+            if (!head_listener) {
                 head_listener = ap_listeners;
-
-	    return (lr);
-	}
-    }
+            }
+            return lr;
+        }
+        lr = lr->next;
+        if (!lr) {
+            lr = ap_listeners;
+        }
+    } while (lr != head_listener);
     return NULL;
 }
 
@@ -352,13 +372,17 @@
     int wait_time = 1;
     int csd;
     SOCKET nsd = INVALID_SOCKET;
-    struct sockaddr_in sa_client;
     int count_select_errors = 0;
     int rc;
     int clen;
     ap_listen_rec *lr;
     struct fd_set listenfds;
     SOCKET listenmaxfd = INVALID_SOCKET;
+#if APR_HAVE_IPV6
+    struct sockaddr_in6 sa_client;
+#else
+    struct sockaddr_in sa_client;
+#endif
 
     /* Setup the listeners 
      * ToDo: Use apr_poll()
@@ -371,6 +395,8 @@
             if (listenmaxfd == INVALID_SOCKET || nsd > listenmaxfd) {
                 listenmaxfd = nsd;
             }
+            ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
+                         "Child %d: Listening on port %d.", my_pid, lr->bind_addr->port);
         }
     }
 
@@ -433,14 +459,26 @@
 static PCOMP_CONTEXT win9x_get_connection(PCOMP_CONTEXT context)
 {
     apr_os_sock_info_t sockinfo;
-    int len;
+    int len, salen;
+#if APR_HAVE_IPV6
+    salen = sizeof(struct sockaddr_in6);
+#else
+    salen = sizeof(struct sockaddr_in);
+#endif
+
 
     if (context == NULL) {
         /* allocate the completion context and the transaction pool */
+        apr_allocator_t *allocator;
+        apr_thread_mutex_lock(child_lock);
         context = apr_pcalloc(pchild, sizeof(COMP_CONTEXT));
-        apr_pool_create(&context->ptrans, pchild);
-        apr_pool_tag(context->ptrans, "ptrans");
+        apr_allocator_create(&allocator);
+        apr_allocator_max_free_set(allocator, ap_max_mem_free);
+        apr_pool_create_ex(&context->ptrans, pchild, NULL, allocator);
+        apr_allocator_owner_set(allocator, context->ptrans);
+        apr_pool_tag(context->ptrans, "transaction");
         context->ba = apr_bucket_alloc_create(pchild);
+        apr_thread_mutex_unlock(child_lock);
     }
     
     while (1) {
@@ -449,7 +487,7 @@
         if (context->accept_socket == INVALID_SOCKET) {
             return NULL;
         }
-	len = sizeof(struct sockaddr);
+        len = salen;
         context->sa_server = apr_palloc(context->ptrans, len);
         if (getsockname(context->accept_socket, 
                         context->sa_server, &len)== SOCKET_ERROR) {
@@ -457,7 +495,7 @@
                          "getsockname failed");
             continue;
         }
-        len = sizeof(struct sockaddr);
+        len = salen;
         context->sa_client = apr_palloc(context->ptrans, len);
         if ((getpeername(context->accept_socket,
                          context->sa_client, &len)) == SOCKET_ERROR) {
@@ -468,7 +506,7 @@
         sockinfo.os_sock = &context->accept_socket;
         sockinfo.local   = context->sa_server;
         sockinfo.remote  = context->sa_client;
-        sockinfo.family  = APR_INET;
+        sockinfo.family  = context->sa_server->sa_family;
         sockinfo.type    = SOCK_STREAM;
         apr_os_sock_make(&context->sock, &sockinfo, context->ptrans);
 
@@ -491,6 +529,7 @@
  *    Worker threads block on the ThreadDispatch IOCompletionPort awaiting 
  *    connections to service.
  */
+#define MAX_ACCEPTEX_ERR_COUNT 100
 static void winnt_accept(void *lr_) 
 {
     ap_listen_rec *lr = (ap_listen_rec *)lr_;
@@ -498,10 +537,21 @@
     PCOMP_CONTEXT context = NULL;
     DWORD BytesRead;
     SOCKET nlsd;
-    int rv;
+    int rv, err_count = 0;
+#if APR_HAVE_IPV6
+    SOCKADDR_STORAGE ss_listen;
+    int namelen = sizeof(ss_listen);
+#endif
 
     apr_os_sock_get(&nlsd, lr->sd);
 
+#if APR_HAVE_IPV6
+    if (getsockname(nlsd, (struct sockaddr *)&ss_listen, &namelen) == SOCKET_ERROR) { 
+        ap_log_error(APLOG_MARK,APLOG_ERR, apr_get_netos_error(), ap_server_conf,
+                    "winnt_accept: getsockname error on listening socket, is IPv6 available?");
+        return;
+   }
+#endif
     while (!shutdown_in_progress) {
         if (!context) {
             context = mpm_get_completion_context();
@@ -513,6 +563,25 @@
         }
 
         /* Create and initialize the accept socket */
+#if APR_HAVE_IPV6
+        if (context->accept_socket == INVALID_SOCKET) {
+            context->accept_socket = socket(ss_listen.ss_family, SOCK_STREAM, IPPROTO_TCP);
+            context->socket_family = ss_listen.ss_family;
+        }
+        else if (context->socket_family != ss_listen.ss_family) { 
+            closesocket(context->accept_socket);
+            context->accept_socket = socket(ss_listen.ss_family, SOCK_STREAM, IPPROTO_TCP);
+            context->socket_family = ss_listen.ss_family;
+        }
+
+        if (context->accept_socket == INVALID_SOCKET) {
+            ap_log_error(APLOG_MARK,APLOG_WARNING, apr_get_netos_error(), ap_server_conf,
+                         "winnt_accept: Failed to allocate an accept socket. "
+                         "Temporary resource constraint? Try again.");
+            Sleep(100);
+            continue;
+        }
+#else
         if (context->accept_socket == INVALID_SOCKET) {
             context->accept_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
             if (context->accept_socket == INVALID_SOCKET) {
@@ -524,7 +593,7 @@
                 continue;
             }
         }
-
+#endif
         /* AcceptEx on the completion context. The completion context will be 
          * signaled when a connection is accepted. 
          */
@@ -538,26 +607,40 @@
             rv = apr_get_netos_error();
             if ((rv == APR_FROM_OS_ERROR(WSAEINVAL)) ||
                 (rv == APR_FROM_OS_ERROR(WSAENOTSOCK))) {
-                /* Hack alert. Occasionally, TransmitFile will not recycle the 
-                 * accept socket (usually when the client disconnects early). 
-                 * Get a new socket and try the call again.
+                /* We can get here when:
+                 * 1) the client disconnects early
+                 * 2) TransmitFile does not properly recycle the accept socket (typically
+                 *    because the client disconnected)
+                 * 3) there is VPN or Firewall software installed with buggy AcceptEx implementation
+                 * 4) the webserver is using a dynamic address that has changed
                  */
+                ++err_count;
                 closesocket(context->accept_socket);
                 context->accept_socket = INVALID_SOCKET;
-                ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf,
-                       "winnt_accept: AcceptEx failed due to early client "
-                       "disconnect. Reallocate the accept socket and try again.");
+                if (err_count > MAX_ACCEPTEX_ERR_COUNT) {
+                    ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf,
+                                 "Child %d: Encountered too many errors accepting client connections. "
+                                 "Possible causes: dynamic address renewal, or incompatible VPN or firewall software. "
+                                 "Try using the Win32DisableAcceptEx directive.", my_pid);
+                    err_count = 0;
+                }          
                 continue;
             }
             else if ((rv != APR_FROM_OS_ERROR(ERROR_IO_PENDING)) &&
                      (rv != APR_FROM_OS_ERROR(WSA_IO_PENDING))) {
+                ++err_count;
+                if (err_count > MAX_ACCEPTEX_ERR_COUNT) { 
                 ap_log_error(APLOG_MARK,APLOG_ERR, rv, ap_server_conf,
-                             "winnt_accept: AcceptEx failed. Attempting to recover.");
+                                 "Child %d: Encountered too many errors accepting client connections. "
+                                 "Possible causes: Unknown. "
+                                 "Try using the Win32DisableAcceptEx directive.", my_pid);
+                    err_count = 0;
+                }
                 closesocket(context->accept_socket);
                 context->accept_socket = INVALID_SOCKET;
-                Sleep(100);
                 continue;
             }
+            err_count = 0;  
 
             /* Wait for pending i/o. 
              * Wake up once per second to check for shutdown .
@@ -592,7 +675,7 @@
                 continue;
             }
         }
-
+        err_count = 0;  
         /* Inherit the listen socket settings. Required for 
          * shutdown() to work 
          */
@@ -617,7 +700,7 @@
         sockinfo.os_sock = &context->accept_socket;
         sockinfo.local   = context->sa_server;
         sockinfo.remote  = context->sa_client;
-        sockinfo.family  = APR_INET;
+        sockinfo.family  = context->sa_server->sa_family;
         sockinfo.type    = SOCK_STREAM;
         apr_os_sock_make(&context->sock, &sockinfo, context->ptrans);
 
@@ -692,8 +775,6 @@
     PCOMP_CONTEXT context = NULL;
     ap_sb_handle_t *sbh;
 
-    ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, ap_server_conf,
-                 "Child %d: Worker thread %d starting.", my_pid, thread_num);
     while (1) {
         conn_rec *c;
         apr_int32_t disconnected;
@@ -701,11 +782,11 @@
         ap_update_child_status_from_indexes(0, thread_num, SERVER_READY, NULL);
 
         /* Grab a connection off the network */
-        if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
-            context = win9x_get_connection(context);
+        if (use_acceptex) {
+            context = winnt_get_connection(context);
         }
         else {
-            context = winnt_get_connection(context);
+            context = win9x_get_connection(context);
         }
         if (!context) {
             /* Time for the thread to exit */
@@ -733,6 +814,16 @@
                 context->accept_socket = INVALID_SOCKET;
                 ap_lingering_close(c);
             }
+            else if (!use_acceptex) {
+                /* If the socket is disconnected but we are not using acceptex, 
+                 * we cannot reuse the socket. Disconnected sockets are removed
+                 * from the apr_socket_t struct by apr_sendfile() to prevent the
+                 * socket descriptor from being inadvertently closed by a call 
+                 * to apr_socket_close(), so close it directly.
+                 */
+                closesocket(context->accept_socket);
+                context->accept_socket = INVALID_SOCKET;
+            }
         }
         else {
             /* ap_run_create_connection closes the socket on failure */
@@ -743,8 +834,6 @@
     ap_update_child_status_from_indexes(0, thread_num, SERVER_DEAD, 
                                         (request_rec *) NULL);
 
-    ap_log_error(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, ap_server_conf,
-                 "Child %d: Worker thread %d exiting.", my_pid, thread_num);
 }
 
 
@@ -769,7 +858,8 @@
 static void create_listener_thread()
 {
     int tid;
-    if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
+    int num_listeners = 0;
+    if (!use_acceptex) {
         _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) win9x_accept,
                        NULL, 0, &tid);
     } else {
@@ -777,6 +867,20 @@
          * XXX: Why would we have a NULL sd in our listeners?
          */
         ap_listen_rec *lr;
+
+        /* Number of completion_contexts allowed in the system is
+         * (ap_threads_per_child + num_listeners). We need the additional
+         * completion contexts to prevent server hangs when ThreadsPerChild
+         * is configured to something less than or equal to the number
+         * of listeners. This is not a usual case, but people have 
+         * encountered it.
+         * */
+        for (lr = ap_listeners; lr ; lr = lr->next) {
+            num_listeners++;
+        }
+        max_num_completion_contexts = ap_threads_per_child + num_listeners;
+
+        /* Now start a thread per listener */
         for (lr = ap_listeners; lr; lr = lr->next) {
             if (lr->sd != NULL) {
                 _beginthreadex(NULL, 1000, (LPTHREAD_START_ROUTINE) winnt_accept,
@@ -840,7 +944,7 @@
      * Create the worker thread dispatch IOCompletionPort
      * on Windows NT/2000
      */
-    if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
+    if (use_acceptex) {
         /* Create the worker thread dispatch IOCP */
         ThreadDispatchIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE,
                                                     NULL,
@@ -861,6 +965,8 @@
     ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf, 
                  "Child %d: Starting %d worker threads.", my_pid, ap_threads_per_child);
     child_handles = (HANDLE) apr_pcalloc(pchild, ap_threads_per_child * sizeof(int));
+    apr_thread_mutex_create(&child_lock, APR_THREAD_MUTEX_DEFAULT, pchild);
+
     while (1) {
         for (i = 0; i < ap_threads_per_child; i++) {
             int *score_idx;
@@ -869,7 +975,8 @@
                 continue;
             }
             ap_update_child_status_from_indexes(0, i, SERVER_STARTING, NULL);
-            child_handles[i] = (HANDLE) _beginthreadex(NULL, 0, (LPTHREAD_START_ROUTINE) worker_main,
+            child_handles[i] = (HANDLE) _beginthreadex(NULL, (unsigned)ap_thread_stacksize,
+                                                       (LPTHREAD_START_ROUTINE) worker_main,
                                                        (void *) i, 0, &tid);
             if (child_handles[i] == 0) {
                 ap_log_error(APLOG_MARK, APLOG_CRIT, apr_get_os_error(), ap_server_conf,
@@ -883,9 +990,11 @@
             /* Save the score board index in ht keyed to the thread handle. We need this 
              * when cleaning up threads down below...
              */
+            apr_thread_mutex_lock(child_lock);
             score_idx = apr_pcalloc(pchild, sizeof(int));
             *score_idx = i;
             apr_hash_set(ht, &child_handles[i], sizeof(HANDLE), score_idx);
+            apr_thread_mutex_unlock(child_lock);
         }
         /* Start the listener only when workers are available */
         if (!listener_started && threads_created) {
@@ -1007,7 +1116,7 @@
     }
 
     /* Shutdown the worker threads */
-    if (osver.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
+    if (!use_acceptex) {
         for (i = 0; i < threads_created; i++) {
             add_job(INVALID_SOCKET);
         }
@@ -1050,7 +1159,8 @@
     /* Kill remaining threads off the hard way */
     if (threads_created) {
         ap_log_error(APLOG_MARK,APLOG_NOTICE, APR_SUCCESS, ap_server_conf, 
-                     "Child %d: Terminating %d threads that failed to exit.", my_pid);
+                     "Child %d: Terminating %d threads that failed to exit.",
+                     my_pid, threads_created);
     }
     for (i = 0; i < threads_created; i++) {
         int *score_idx;
@@ -1065,8 +1175,10 @@
 
     CloseHandle(allowed_globals.jobsemaphore);
     apr_thread_mutex_destroy(allowed_globals.jobmutex);
-    if (osver.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) {
-    	apr_thread_mutex_destroy(qlock);
+    apr_thread_mutex_destroy(child_lock);
+
+    if (use_acceptex) {
+        apr_thread_mutex_destroy(qlock);
         CloseHandle(qwait_event);
     }
 
Index: server/mpm/winnt/mpm.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/mpm/winnt/mpm.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- server/mpm/winnt/mpm.h	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ server/mpm/winnt/mpm.h	14 Mar 2004 15:21:11 -0000	1.3
@@ -72,6 +72,8 @@
 #define AP_MPM_WANT_SET_MAX_REQUESTS
 #define AP_MPM_WANT_SET_COREDUMPDIR
 #define AP_MPM_WANT_SET_SCOREBOARD
+#define AP_MPM_WANT_SET_MAX_MEM_FREE
+#define AP_MPM_WANT_SET_STACKSIZE
 
 extern int ap_threads_per_child;
 extern int ap_thread_limit;
Index: server/mpm/winnt/mpm_winnt.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/mpm/winnt/mpm_winnt.c,v
retrieving revision 1.1.1.1
retrieving revision 1.7
diff -u -u -r1.1.1.1 -r1.7
--- server/mpm/winnt/mpm_winnt.c	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ server/mpm/winnt/mpm_winnt.c	26 Feb 2005 16:57:32 -0000	1.7
@@ -103,6 +103,7 @@
 DWORD my_pid;
 
 int ap_threads_per_child = 0;
+int use_acceptex = 1;
 static int thread_limit = DEFAULT_THREAD_LIMIT;
 static int first_thread_limit = 0;
 static int changed_limit_at_restart;
@@ -217,6 +218,19 @@
     }
     return NULL;
 }
+static const char *set_disable_acceptex(cmd_parms *cmd, void *dummy, char *arg) 
+{
+    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+    if (err != NULL) {
+        return err;
+    }
+    if (use_acceptex) {
+        use_acceptex = 0;
+        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, NULL, 
+                     "Disabled use of AcceptEx() WinSock2 API");
+    }
+    return NULL;
+}
 
 static const command_rec winnt_cmds[] = {
 LISTEN_COMMANDS,
@@ -224,6 +238,8 @@
   "Number of threads each child creates" ),
 AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF,
   "Maximum worker threads in a server for this run of Apache"),
+AP_INIT_NO_ARGS("Win32DisableAcceptEx", set_disable_acceptex, NULL, RSRC_CONF,
+  "Disable use of the high performance AcceptEx WinSock2 API to work around buggy VPN or Firewall software"),
 { NULL }
 };
 
@@ -693,7 +709,7 @@
     if ((rv = apr_procattr_io_set(attr, APR_FULL_BLOCK, 
                                   APR_NO_PIPE, APR_NO_PIPE)) != APR_SUCCESS) {
         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
-                        "Parent: Unable to create child stdin pipe.\n");
+                        "Parent: Unable to create child stdin pipe.");
         apr_pool_destroy(ptemp);
         return -1;
     }
@@ -704,7 +720,7 @@
         || ((rv = apr_procattr_child_out_set(attr, child_out, NULL)) 
                 != APR_SUCCESS)) {
         ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
-                        "Parent: Unable to connect child stdout to NUL.\n");
+                        "Parent: Unable to connect child stdout to NUL.");
         apr_pool_destroy(ptemp);
         return -1;
     }
@@ -722,7 +738,7 @@
         if ((rv = apr_procattr_child_err_set(attr, child_err, NULL))
                 != APR_SUCCESS) {
             ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
-                            "Parent: Unable to connect child stderr.\n");
+                            "Parent: Unable to connect child stderr.");
             apr_pool_destroy(ptemp);
             return -1;
         }
@@ -1091,7 +1107,8 @@
     /* Handle the following SCM aspects in this phase:
      *
      *   -k runservice [transition for WinNT, nothing for Win9x]
-     *   -k (!)install [error out if name is not installed]
+     *   -k install
+     *   -k config
      *   -k uninstall
      *   -k stop
      *   -k shutdown (same as -k stop). Maintained for backward compatability.
@@ -1292,7 +1309,7 @@
                                            AP_DEFAULT_SERVICE_NAME);
     }
 
-    if (!strcasecmp(signal_arg, "install")) /* -k install */
+    if (!strcasecmp(signal_arg, "install")) /* Service already installed? */
     {
         if (service_set == APR_SUCCESS) 
         {
@@ -1301,7 +1318,7 @@
             exit(APEXIT_INIT);
         }
     }
-    else if (running_as_service)
+    else if (running_as_service) /* -k start|restart|uninstall|stop|shutdown */
     {
         if (service_set == APR_SUCCESS) 
         {
@@ -1353,6 +1370,32 @@
     inst_argv = (const char * const *)mpm_new_argv->elts
         + mpm_new_argv->nelts - inst_argc;
 
+    /* Now, do service install or reconfigure then proceed to
+     * post_config to test the installed configuration.
+     */
+    if (!strcasecmp(signal_arg, "config")) { /* -k config */
+        /* Reconfigure the service */
+        rv = mpm_service_install(process->pool, inst_argc, inst_argv, 1);
+        if (rv != APR_SUCCESS) {
+            exit(rv);
+        }
+
+        fprintf(stderr,"Testing httpd.conf....\n");
+        fprintf(stderr,"Errors reported here must be corrected before the "
+                "service can be started.\n");
+    }
+    else if (!strcasecmp(signal_arg, "install")) { /* -k install */
+        /* Install the service */
+        rv = mpm_service_install(process->pool, inst_argc, inst_argv, 0);
+        if (rv != APR_SUCCESS) {
+            exit(rv);
+        }
+
+        fprintf(stderr,"Testing httpd.conf....\n");
+        fprintf(stderr,"Errors reported here must be corrected before the "
+                "service can be started.\n");
+    }
+    
     process->argc = mpm_new_argv->nelts; 
     process->argv = (const char * const *) mpm_new_argv->elts;
 }
@@ -1399,8 +1442,8 @@
 
     /* Handle the following SCM aspects in this phase:
      *
-     *   -k install
-     *   -k config
+     *   -k install (catch and exit as install was handled in rewrite_args)
+     *   -k config  (catch and exit as config was handled in rewrite_args)
      *   -k start
      *   -k restart
      *   -k runservice [Win95, only once - after we parsed the config]
@@ -1413,12 +1456,22 @@
      */
 
     if (!strcasecmp(signal_arg, "install")) {
-        rv = mpm_service_install(ptemp, inst_argc, inst_argv, 0);
-        exit (rv);
+        /* Service install happens in the rewrite_args hooks. If we 
+         * made it this far, the server configuration is clean and the
+         * service will successfully start.
+         */
+        apr_pool_destroy(s->process->pool);
+        apr_terminate();
+        exit(0);
     }
     if (!strcasecmp(signal_arg, "config")) {
-        rv = mpm_service_install(ptemp, inst_argc, inst_argv, 1);
-        exit (rv);
+        /* Service reconfiguration happens in the rewrite_args hooks. If we 
+         * made it this far, the server configuration is clean and the
+         * service will successfully start.
+         */
+        apr_pool_destroy(s->process->pool);
+        apr_terminate();
+        exit(0);
     }
 
     if (!strcasecmp(signal_arg, "start")) {
@@ -1430,11 +1483,15 @@
             lr->active = 0;
         }
         rv = mpm_service_start(ptemp, inst_argc, inst_argv);
+        apr_pool_destroy(s->process->pool);
+        apr_terminate();
         exit (rv);
     }
 
     if (!strcasecmp(signal_arg, "restart")) {
         mpm_signal_service(ptemp, 1);
+        apr_pool_destroy(s->process->pool);
+        apr_terminate();
         exit (rv);
     }
 
@@ -1590,6 +1647,7 @@
 {
     static int restart = 0;            /* Default is "not a restart" */
 
+
     if (!restart) {
         first_thread_limit = thread_limit;
     }
@@ -1629,6 +1687,21 @@
     else 
     {
         /* A real-honest to goodness parent */
+        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, 
+                     "%s configured -- resuming normal operations", 
+                     /* If customer has set ServerTokens directive to 
+                      * eliminate the IHS version string from the contents 
+                      * of the Server: response header field, then we 
+                      * wouldn't normally be able to find the IHS version 
+                      * string in an error log due to the mechanics of 
+                      * ap_get_server_version().  Check for this condition, 
+                      * and if version number has been eliminated then 
+                      * make sure we log it at startup. 
+                      */ 
+                     ap_strstr_c(ap_get_server_version(), IHS_VERSION) ? 
+                     ap_get_server_version() : AP_SERVER_BASEVERSION); 
+        ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, 
+                     "Server built: %s", ap_get_server_built()); 
 
         restart = master_main(ap_server_conf, shutdown_event, restart_event);
 
Index: server/mpm/winnt/mpm_winnt.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/mpm/winnt/mpm_winnt.h,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- server/mpm/winnt/mpm_winnt.h	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ server/mpm/winnt/mpm_winnt.h	22 Mar 2005 22:31:27 -0000	1.4
@@ -100,7 +100,7 @@
 void mpm_nt_eventlog_stderr_flush(void);
 
 /* From winnt.c: */
-
+extern int use_acceptex;
 extern OSVERSIONINFO osver;
 extern void clean_child_exit(int);
 
@@ -126,7 +126,12 @@
 #define CONTAINING_RECORD(address, type, field) ((type *)( \
                                                   (PCHAR)(address) - \
                                                   (PCHAR)(&((type *)0)->field)))
-#define PADDED_ADDR_SIZE sizeof(SOCKADDR_IN)+16
+#if APR_HAVE_IPV6
+#define PADDED_ADDR_SIZE (sizeof(SOCKADDR_IN6)+16)
+#else
+#define PADDED_ADDR_SIZE (sizeof(SOCKADDR_IN)+16)
+#endif
+
 typedef struct CompContext {
     struct CompContext *next;
     OVERLAPPED Overlapped;
@@ -139,6 +144,7 @@
     int sa_client_len;
     apr_pool_t *ptrans;
     apr_bucket_alloc_t *ba;
+    short socket_family;
 } COMP_CONTEXT, *PCOMP_CONTEXT;
 
 typedef enum {
Index: server/mpm/worker/mpm.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/mpm/worker/mpm.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- server/mpm/worker/mpm.h	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ server/mpm/worker/mpm.h	14 Mar 2004 15:21:11 -0000	1.2
@@ -76,6 +76,7 @@
 #define AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
 #define AP_MPM_WANT_SIGNAL_SERVER
 #define AP_MPM_WANT_SET_MAX_MEM_FREE
+#define AP_MPM_WANT_SET_STACKSIZE
 #define AP_MPM_DISABLE_NAGLE_ACCEPTED_SOCK
 
 #define MPM_CHILD_PID(i) (ap_scoreboard_image->parent[i].pid)
Index: server/mpm/worker/worker.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/server/mpm/worker/worker.c,v
retrieving revision 1.1.1.1
retrieving revision 1.23
diff -u -u -r1.1.1.1 -r1.23
--- server/mpm/worker/worker.c	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ server/mpm/worker/worker.c	3 Jan 2006 16:02:26 -0000	1.23
@@ -175,6 +175,22 @@
 static int resource_shortage = 0;
 static fd_queue_t *worker_queue;
 static fd_queue_info_t *worker_queue_info;
+static int sick_child_detected;
+
+/* IHS changes for fatal exception hook */
+APR_HOOK_STRUCT(
+    APR_HOOK_LINK(ihs_fatal_exception_received)
+    APR_HOOK_LINK(fatal_exception)
+)
+
+AP_IMPLEMENT_HOOK_RUN_ALL(int,ihs_fatal_exception_received,
+                          (ihs_exception_info_t *ei), (ei), OK, DECLINED)
+
+static apr_thread_mutex_t *fatal_hook_mutex;
+/* end of IHS changes for fatal exception hook */
+
+AP_IMPLEMENT_HOOK_RUN_ALL(int, fatal_exception,
+                          (ap_exception_info_t *ei), (ei), OK, DECLINED)
 
 /* The structure used to pass unique initialization info to each thread */
 typedef struct {
@@ -257,12 +273,26 @@
  * perform a non-graceful (forced) shutdown of the server. */
 static apr_socket_t **worker_sockets;
 
+static void unblock_signal(int signal); 
+
 static void close_worker_sockets(void)
 {
     int i;
     for (i = 0; i < ap_threads_per_child; i++) {
         if (worker_sockets[i]) {
-            apr_socket_close(worker_sockets[i]);
+            /* Apache does this:
+             *   apr_socket_close(worker_sockets[i]);
+             *
+             * IHS: For SSL sockets, apr_socket_close() frees
+             *      memory used by the security library.  That
+             *      can cause a crash on the worker thread.
+             *      We need to be sure we're simply closing the
+             *      socket descriptor.
+             */
+            int sockfd;
+            
+            apr_os_sock_get(&sockfd, worker_sockets[i]);
+            close(sockfd);
             worker_sockets[i] = NULL;
         }
     }
@@ -374,11 +404,47 @@
     exit(code);
 }
 
+#if AP_ENABLE_EXCEPTION_HOOK
+static void run_fatal_exception_hook(int sig)
+{
+    ap_exception_info_t ei = {0};
+
+    if (ihs_exception_hook_enabled &&
+        geteuid() != 0 && 
+        ap_my_pid != parent_pid) {
+        ei.sig = sig;
+        ei.pid = ap_my_pid;
+        ap_run_fatal_exception(&ei);
+    }
+}
+#endif
+
 /* handle all varieties of core dumping signals */
 static void sig_coredump(int sig)
 {
+    /* IHS changes for fatal exception hook */
+    ihs_exception_info_t ei = {0};
+    static volatile int hook_run_before = 0;
+    int run_hook_now;
+
+    ei.format = 0;
+    ei.sig = sig;
+    ei.pid = ap_my_pid;
+    /* don't run it again if it has ever run before in this process */
+    apr_thread_mutex_lock(fatal_hook_mutex);
+    run_hook_now = hook_run_before == 0;
+    hook_run_before++;
+    apr_thread_mutex_unlock(fatal_hook_mutex);
+    if (run_hook_now) {
+        ap_run_ihs_fatal_exception_received(&ei);
+    }
+    /* end of IHS changes for fatal exception hook */
+
     apr_filepath_set(ap_coredump_dir, pconf);
     apr_signal(sig, SIG_DFL);
+#if AP_ENABLE_EXCEPTION_HOOK
+    run_fatal_exception_hook(sig);
+#endif
     if (ap_my_pid == parent_pid) {
         ap_log_error(APLOG_MARK, APLOG_NOTICE,
                      0, ap_server_conf,
@@ -391,6 +457,9 @@
          * system since this function is no longer the signal handler   GLA
          */
     }
+#ifdef __MVS__
+    unblock_signal(sig);
+#endif
     kill(ap_my_pid, sig);
     /* At this point we've got sig blocked, because we're still inside
      * the signal handler.  When we leave the signal handler it will
@@ -616,16 +685,6 @@
     ap_create_sb_handle(&sbh, p, my_child_num, my_thread_num);
     apr_os_sock_get(&csd, sock);
 
-    if (csd >= FD_SETSIZE) {
-        ap_log_error(APLOG_MARK, APLOG_WARNING, 0, NULL,
-                     "new file descriptor %d is too large; you probably need "
-                     "to rebuild Apache with a larger FD_SETSIZE "
-                     "(currently %d)", 
-                     csd, FD_SETSIZE);
-        apr_socket_close(sock);
-        return;
-    }
-
     current_conn = ap_run_create_connection(p, ap_server_conf, sock,
                                             conn_id, sbh, bucket_alloc);
     if (current_conn) {
@@ -803,6 +862,7 @@
             }
             else {
                 ptrans = recycled_pool;
+                recycled_pool = NULL;
             }
             apr_pool_tag(ptrans, "transaction");
             rv = lr->accept_func(&csd, lr, ptrans);
@@ -839,16 +899,26 @@
                     apr_socket_close(csd);
                     ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
                                  "ap_queue_push failed");
+                    recycled_pool = ptrans;
                 }
                 else {
                     have_idle_worker = 0;
                 }
             }
+            else {
+                recycled_pool = ptrans;
+            }
         }
         else {
             if ((rv = SAFE_ACCEPT(apr_proc_mutex_unlock(accept_mutex)))
                 != APR_SUCCESS) {
-                ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf,
+                int level = APLOG_EMERG;
+                
+                if (ap_scoreboard_image->parent[process_slot].generation != 
+                    ap_scoreboard_image->global->running_generation) {
+                    level = APLOG_DEBUG; /* common to get these at restart time */
+                }
+                ap_log_error(APLOG_MARK, level, rv, ap_server_conf,
                              "apr_proc_mutex_unlock failed. Attempting to "
                              "shutdown process gracefully.");
                 signal_threads(ST_GRACEFUL);
@@ -891,8 +961,6 @@
 
     ap_update_child_status_from_indexes(process_slot, thread_slot, SERVER_STARTING, NULL);
 
-    bucket_alloc = apr_bucket_alloc_create(apr_thread_pool_get(thd));
-
     while (!workers_may_exit) {
         if (!is_idle) {
             rv = ap_queue_info_set_idle(worker_queue_info, last_ptrans);
@@ -944,6 +1012,7 @@
         }
         is_idle = 0;
         worker_sockets[thread_slot] = csd;
+        bucket_alloc = apr_bucket_alloc_create(ptrans);
         process_socket(ptrans, csd, process_slot, thread_slot, bucket_alloc);
         worker_sockets[thread_slot] = NULL;
         requests_this_child--; /* FIXME: should be synchronized - aaron */
@@ -954,8 +1023,6 @@
     ap_update_child_status_from_indexes(process_slot, thread_slot,
         (dying) ? SERVER_DEAD : SERVER_GRACEFUL, (request_rec *) NULL);
 
-    apr_bucket_alloc_destroy(bucket_alloc);
-
     apr_thread_exit(thd, APR_SUCCESS);
     return NULL;
 }
@@ -986,14 +1053,8 @@
     if (rv != APR_SUCCESS) {
         ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
                      "apr_thread_create: unable to create listener thread");
-        /* In case system resources are maxxed out, we don't want
-         * Apache running away with the CPU trying to fork over and
-         * over and over again if we exit.
-         * XXX Jeff doesn't see how Apache is going to try to fork again since
-         * the exit code is APEXIT_CHILDFATAL
-         */
-        apr_sleep(apr_time_from_sec(10));
-        clean_child_exit(APEXIT_CHILDFATAL);
+        /* let the parent decide how bad this really is */
+        clean_child_exit(APEXIT_CHILDSICK);
     }
     apr_os_thread_get(&listener_os_thread, ts->listener);
 }
@@ -1070,11 +1131,8 @@
             if (rv != APR_SUCCESS) {
                 ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
                     "apr_thread_create: unable to create worker thread");
-                /* In case system resources are maxxed out, we don't want
-                   Apache running away with the CPU trying to fork over and
-                   over and over again if we exit. */
-                apr_sleep(apr_time_from_sec(10));
-                clean_child_exit(APEXIT_CHILDFATAL);
+                /* let the parent decide how bad this really is */
+                clean_child_exit(APEXIT_CHILDSICK);
             }
             threads_created++;
         }
@@ -1144,7 +1202,7 @@
             ++iter;
         }
         if (iter >= 10) {
-            ap_log_error(APLOG_MARK, APLOG_CRIT, 0, ap_server_conf,
+            ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
                          "the listener thread didn't exit");
         }
         else {
@@ -1236,6 +1294,11 @@
     
     /* Setup worker threads */
 
+    /* IHS change for fatal exception hook */
+    rv = apr_thread_mutex_create(&fatal_hook_mutex, APR_THREAD_MUTEX_DEFAULT, pchild);
+    ap_assert(rv == APR_SUCCESS);
+    /* end of IHS change for fatal exception hook */
+
     /* clear the storage; we may not create all our threads immediately, 
      * and we want a 0 entry to indicate a thread which was not created
      */
@@ -1253,6 +1316,10 @@
     /* 0 means PTHREAD_CREATE_JOINABLE */
     apr_threadattr_detach_set(thread_attr, 0);
 
+    if (ap_thread_stacksize != 0) {
+        apr_threadattr_stacksize_set(thread_attr, ap_thread_stacksize);
+    }
+    
     ts->threads = threads;
     ts->listener = NULL;
     ts->child_num_arg = child_num_arg;
@@ -1263,11 +1330,8 @@
     if (rv != APR_SUCCESS) {
         ap_log_error(APLOG_MARK, APLOG_ALERT, rv, ap_server_conf,
                      "apr_thread_create: unable to create worker thread");
-        /* In case system resources are maxxed out, we don't want
-           Apache running away with the CPU trying to fork over and
-           over and over again if we exit. */
-        apr_sleep(apr_time_from_sec(10));
-        clean_child_exit(APEXIT_CHILDFATAL);
+        /* let the parent decide how bad this really is */
+        clean_child_exit(APEXIT_CHILDSICK);
     }
 
     /* If we are only running in one_process mode, we will want to
@@ -1393,6 +1457,21 @@
         clean_child_exit(0);
     }
     /* else */
+    if (ap_scoreboard_image->parent[slot].pid != 0) {
+        /* This new child process is squatting on the scoreboard
+         * entry owned by an exiting child process, which cannot
+         * exit until all active requests complete.
+         * Don't forget about this exiting child process, or we
+         * won't be able to kill it if it doesn't exit by the
+         * time the server is shut down.
+         */
+        ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf,
+                     "taking over scoreboard slot from %" APR_PID_T_FMT "%s",
+                     ap_scoreboard_image->parent[slot].pid,
+                     ap_scoreboard_image->parent[slot].quiescing ?
+                         " (quiescing)" : "");
+        ap_register_extra_mpm_process(ap_scoreboard_image->parent[slot].pid);
+    }
     ap_scoreboard_image->parent[slot].quiescing = 0;
     ap_scoreboard_image->parent[slot].pid = pid;
     return 0;
@@ -1438,6 +1517,7 @@
     int free_slots[MAX_SPAWN_RATE];
     int last_non_dead;
     int total_non_dead;
+    int active_thread_count = 0;
 
     /* initialize the free_list */
     free_length = 0;
@@ -1475,17 +1555,20 @@
              * So we hopefully won't need to fork more if we count it.
              * This depends on the ordering of SERVER_READY and SERVER_STARTING.
              */
-            if (status <= SERVER_READY && status != SERVER_DEAD &&
-                    !ps->quiescing &&
-                    ps->generation == ap_my_generation &&
-                 /* XXX the following shouldn't be necessary if we clean up 
-                  *     properly after seg faults, but we're not yet    GLA 
-                  */     
-                    ps->pid != 0) {
-                ++idle_thread_count;
+            if (ps->pid != 0) { /* XXX just set all_dead_threads in outer for
+                                   loop if no pid?  not much else matters */
+                if (status <= SERVER_READY && status != SERVER_DEAD &&
+                        !ps->quiescing &&
+                        ps->generation == ap_my_generation) {
+                    ++idle_thread_count;
+                }
+                if (status >= SERVER_READY && status < SERVER_GRACEFUL) {
+                    ++active_thread_count;
+                }
             }
         }
-        if (any_dead_threads && totally_free_length < idle_spawn_rate 
+        if (any_dead_threads && totally_free_length < idle_spawn_rate
+                && free_length < MAX_SPAWN_RATE
                 && (!ps->pid               /* no process in the slot */
                     || ps->quiescing)) {   /* or at least one is going away */
             if (all_dead_threads) {
@@ -1512,6 +1595,28 @@
             ++total_non_dead;
         }
     }
+
+    if (sick_child_detected) {
+        if (active_thread_count > 0) {
+            /* some child processes appear to be working.  don't kill the
+             * whole server.
+             */
+            sick_child_detected = 0;
+        }
+        else {
+            /* looks like a basket case.  give up.  
+             */
+            shutdown_pending = 1;
+            child_fatal = 1;
+            ap_log_error(APLOG_MARK, APLOG_ALERT, 0,
+                         ap_server_conf,
+                         "No active workers found..."
+                         " Apache is exiting!");
+            /* the child already logged the failure details */
+            return;
+        }
+    }
+                                                    
     ap_max_daemons_limit = last_non_dead + 1;
 
     if (idle_thread_count > max_spare_threads) {
@@ -1585,6 +1690,12 @@
                 child_fatal = 1;
                 return;
             }
+            else if (processed_status == APEXIT_CHILDSICK) {
+                /* tell perform_idle_server_maintenance to check into this
+                 * on the next timer pop
+                 */
+                sick_child_detected = 1;
+            }
             /* non-fatal death... note that it's gone in the scoreboard. */
             child_slot = find_child_by_pid(&pid);
             if (child_slot >= 0) {
@@ -1606,6 +1717,9 @@
                     make_child(ap_server_conf, child_slot);
                     --remaining_children_to_start;
                 }
+            }
+            else if (ap_unregister_extra_mpm_process(pid.pid) == 1) {
+                /* handled */
 #if APR_HAS_OTHER_CHILD
             }
             else if (apr_proc_other_child_read(&pid, status) == 0) {
@@ -1646,6 +1760,82 @@
     }
 }
 
+/* IHS addition */
+static void check_tuning(server_rec *s)
+{
+/* On z/OS, don't complain about ulimit -c 0 or missing CoreDumpDirectory since
+ * . Limit of 0 bytes for core files doesn't prevent CEEDUMP from being written.
+ * . CoreDumpDirectory will be respected if possible, but if missing it will
+ *   fall back to other locations, such as /tmp
+ */
+#ifndef __MVS__
+    struct rlimit rl;
+    int rc;
+    int already_complained = 0;
+
+    rc = getrlimit(RLIMIT_CORE, &rl);
+    if (rc == 0) {
+        if (rl.rlim_cur == 0) {
+            /* Regardless of whether or not the server was started as root,
+             * a soft limit of zero for core file size prevents core dumps
+             * from being written for any web server processes.
+             * Theoretically we could try to raise the soft limit to the
+             * hard limit (if it is higher), but perhaps this is the
+             * administrator's way to say they want no core dumps.
+             */
+            ap_log_error(APLOG_MARK, APLOG_NOTICE,
+                         0,
+                         s,
+                         "Core file limit is 0; core dumps will be not be "
+                         "written for server crashes");
+            already_complained = 1;
+        }
+    }
+
+    if (!already_complained &&
+        geteuid() == 0 &&
+        !ap_coredumpdir_configured) {
+        /* The server has started as root, so child processes run as another
+         * user.  They SHOULD NOT have permission to write to the web server
+         * install directory, so if CoreDumpDirectory hasn't been specified,
+         * then in general no core dump can be written.
+         * Exception: On Solaris, the coreadm command can be used to specify
+         * an alternate directory for core dumps to be written.
+         * Potentially the same feature is/will be available on other platforms.
+         */
+        ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE,
+                     0,
+                     s,
+                     "CoreDumpDirectory not set; core dumps may not be written for "
+                     "child process crashes");
+    }
+#endif /* ifndef __MVS__ */
+#ifdef _AIX
+    if (sizeof(s) == 4) { /* logic applies only to a 32-bit build */
+        const char *ldrcntrl = getenv("LDR_CNTRL");
+
+        /* LDR_CNTRL is potentially used to set multiple attributes.
+         * It may be present but neglect to set the key attribute MAXDATA.
+         */
+        if (!ldrcntrl || !strstr(ldrcntrl, "MAXDATA")) {
+            ap_log_error(APLOG_MARK, APLOG_NOTICE,
+                         0,
+                         s,
+                         "The LDR_CNTRL environment variable %s; httpd "
+                         "processes may fail under load due to memory "
+                         "limitations.",
+                         ldrcntrl ? "does not specify MAXDATA" : "is not set");
+            ap_log_error(APLOG_MARK, APLOG_NOTICE,
+                         0,
+                         s,
+                         "Verify that IBM HTTP Server was started with "
+                         "apachectl and that the envvars file sets LDR_CNTRL.");
+        }
+    }
+#endif
+}
+/* end IHS addition */
+
 int ap_mpm_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
 {
     int remaining_children_to_start;
@@ -1729,7 +1919,17 @@
 
     ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf,
                 "%s configured -- resuming normal operations",
-                ap_get_server_version());
+                 /* If customer has set ServerTokens directive to
+                  * eliminate the IHS version string from the contents
+                  * of the Server: response header field, then we
+                  * wouldn't normally be able to find the IHS version
+                  * string in an error log due to the mechanics of
+                  * ap_get_server_version().  Check for this condition,
+                  * and if version number has been eliminated then
+                  * make sure we log it at startup.
+                  */
+                 ap_strstr_c(ap_get_server_version(), IHS_VERSION) ?
+                     ap_get_server_version() : AP_SERVER_BASEVERSION);
     ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf,
                 "Server built: %s", ap_get_server_built());
 #ifdef AP_MPM_WANT_SET_ACCEPT_LOCK_MECH
@@ -1738,6 +1938,10 @@
 		apr_proc_mutex_name(accept_mutex),
 		apr_proc_mutex_defname());
 #endif
+    /* IHS addition */
+    check_tuning(ap_server_conf);
+    /* end IHS addition */
+    
     restart_pending = shutdown_pending = 0;
 
     server_main_loop(remaining_children_to_start);
@@ -1919,6 +2123,9 @@
     ap_lock_fname = DEFAULT_LOCKFILE;
     ap_max_requests_per_child = DEFAULT_MAX_REQUESTS_PER_CHILD;
     ap_extended_status = 0;
+#ifdef AP_MPM_WANT_SET_MAX_MEM_FREE
+    ap_max_mem_free = APR_ALLOCATOR_MAX_FREE_UNLIMITED;
+#endif
 
     apr_cpystrn(ap_coredump_dir, ap_server_root, sizeof(ap_coredump_dir));
 
@@ -2031,7 +2238,7 @@
                     server_limit);
        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
                     " Automatically lowering MaxClients to %d.  To increase,",
-                    server_limit);
+                    server_limit * ap_threads_per_child);
        ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, 
                     " please see the ServerLimit directive.");
        ap_daemons_limit = server_limit;
Index: srclib/apr/CHANGES
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/CHANGES,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
Index: srclib/apr/configure.in
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/configure.in,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- srclib/apr/configure.in	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ srclib/apr/configure.in	26 Oct 2005 14:47:52 -0000	1.4
@@ -314,7 +314,13 @@
 # combinations
 case "$host:$CC" in
     *-hp-hpux*:cc )
-	APR_ADDTO(CFLAGS,[-Ae +DAportable +Z])
+	case $host in
+	  ia64-* )
+	    ;;
+          * )
+	    APR_ADDTO(CFLAGS,[-Ae +DAportable +Z])
+            ;;
+        esac
 	;;
     powerpc-*-beos:mwcc* )
 	APR_SETVAR(CPP,[mwcc -E])
@@ -786,8 +792,21 @@
 AC_CHECK_FUNCS(getrlimit, [ have_getrlimit="1" ], [ have_getrlimit="0" ]) 
 AC_CHECK_FUNCS(writev)
 sendfile="0"
-AC_CHECK_LIB(sendfile, sendfilev)
-AC_CHECK_FUNCS(sendfile send_file sendfilev, [ sendfile="1" ])
+dnl --- IBM-specific change
+dnl --- skip right over the sendfile detection logic on Solaris/Sparc.
+dnl --- otherwise, even when we specify --without-sendfile APR will
+dnl --- still refer to libsendfile and httpd/APR won't load on a
+dnl --- Solaris machine which doesn't have the sendfile enhancement
+
+case $host in
+    *sparc*-solaris2*)
+        echo "sendfile library and function search disabled"
+        ;;
+    *)
+        AC_CHECK_LIB(sendfile, sendfilev)
+        AC_CHECK_FUNCS(sendfile send_file sendfilev, [ sendfile="1" ])
+        ;;
+esac
 
 dnl THIS MUST COME AFTER THE THREAD TESTS - FreeBSD doesn't always have a
 dnl threaded poll() and we don't want to use sendfile on early FreeBSD 
@@ -1135,6 +1154,18 @@
 fi
 if test "$ac_cv_socklen_t" = "yes"; then
     socklen_t_value="socklen_t"
+    case $host in
+        *-hp-hpux*)
+            if test "$ac_cv_sizeof_long" = "8"; then
+                # 64-bit HP-UX requires 32-bit socklens in
+                # kernel, but user-space declarations say
+                # 64-bit (socklen_t == size_t == long).
+                # This will result in many compile warnings,
+                # but we're functionally busted otherwise.
+                socklen_t_value="int"
+            fi
+            ;;
+    esac
 else
     socklen_t_value="int"
 fi
Index: srclib/apr/atomic/os390/atomic.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/atomic/os390/atomic.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/atomic/os390/atomic.c	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ srclib/apr/atomic/os390/atomic.c	7 Sep 2005 16:07:45 -0000	1.3
@@ -79,4 +79,23 @@
     return old; /* old is automatically updated from mem on cs failure */
 }
 
+/************************************************************************/
+/* WARNING: apr_atomic_casptr does not work with apr/test/testatomic
+    the apache doc indicates that mem is a **, but testatomic assumes it
+    is a single *                                                     */
+/***********************************************************************/
+#if APR_SIZEOF_VOIDP == 8
+void *apr_atomic_casptr(volatile void  **mem_ptr,
+                        void    *swap_ptr,
+                        const void  *cmp_ptr )
+{
+    cds_t *temp_ptr;
+    cds_t *old_ptr;
+    old_ptr = (cds_t *)cmp_ptr;
+     __cds (old_ptr,
+          *(cds_t **) mem_ptr ,
+          *(cds_t *)  swap_ptr);
+    return old_ptr;
+}
+#endif /* APR_SIZEOF_VOIDP */
 #endif /* APR_HAS_THREADS */
Index: srclib/apr/build/apr_hints.m4
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/build/apr_hints.m4,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- srclib/apr/build/apr_hints.m4	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ srclib/apr/build/apr_hints.m4	4 Feb 2006 13:45:46 -0000	1.4
@@ -61,7 +61,7 @@
           APR_SETIFNULL(AIX_XLC, [yes])
           APR_ADDTO(CFLAGS, [-qHALT=E])
         fi
-	APR_SETIFNULL(apr_iconv_inbuf_const, [1])
+        APR_SETIFNULL(apr_lock_method, [USE_SYSVSEM_SERIALIZE])
 	APR_SETIFNULL(apr_sysvsem_is_global, [yes])
 	APR_ADDTO(LDFLAGS, [-Wl,-brtl])
         ;;
@@ -105,6 +105,7 @@
 	           ;;
         esac
 	APR_ADDTO(CPPFLAGS, [-D_REENTRANT])
+        APR_SETIFNULL(apr_lock_method, [USE_SYSVSEM_SERIALIZE])
 	;;
     *-GNU*)
 	APR_ADDTO(CPPFLAGS, [-DHURD])
Index: srclib/apr/build/apr_threads.m4
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/build/apr_threads.m4,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/build/apr_threads.m4	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ srclib/apr/build/apr_threads.m4	28 Apr 2004 03:25:47 -0000	1.3
@@ -117,7 +117,16 @@
 AC_CACHE_CHECK(for pthreads_cflags,ac_cv_pthreads_cflags,[
 ac_cv_pthreads_cflags=""
 if test "$pthreads_working" != "yes"; then
-  for flag in -kthread -pthread -pthreads -mthreads -Kthread -threads; do 
+  case $host in
+    *-solaris2*)
+      # -mt on Solaris avoids linking in -lpthread
+      MTOPT=""
+      ;;
+    *)
+      MTOPT="-mt"
+      ;;
+  esac
+  for flag in -kthread -pthread -pthreads $MTOPT -mthreads -Kthread -threads; do 
     ac_save="$CFLAGS"
     CFLAGS="$CFLAGS $flag"
     APR_PTHREADS_CHECK_COMPILE
Index: srclib/apr/file_io/unix/Makefile.in
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/file_io/unix/Makefile.in,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/file_io/unix/Makefile.in	29 Jul 2003 20:19:25 -0000	1.1.1.1
+++ srclib/apr/file_io/unix/Makefile.in	11 Jan 2005 19:48:38 -0000	1.2
@@ -15,7 +15,8 @@
 	pipe.lo \
 	readwrite.lo \
 	seek.lo \
-	mktemp.lo
+	mktemp.lo \
+	tempdir.lo
 
 # bring in rules.mk for standard functionality
 @INCLUDE_RULES@
Index: srclib/apr/file_io/unix/open.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/file_io/unix/open.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/file_io/unix/open.c	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/file_io/unix/open.c	1 Feb 2005 18:10:23 -0000	1.2
@@ -137,6 +137,11 @@
         oflags |= O_BINARY;
     }
 #endif
+#ifdef O_LARGEFILE
+    if (flag & APR_LARGEFILE) {
+        oflags |= O_LARGEFILE;
+    }
+#endif
     
 #if APR_HAS_THREADS
     if ((flag & APR_BUFFERED) && (flag & APR_XTHREAD)) {
Index: srclib/apr/file_io/unix/pipe.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/file_io/unix/pipe.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/file_io/unix/pipe.c	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/file_io/unix/pipe.c	5 Oct 2003 12:51:38 -0000	1.3
@@ -171,9 +171,10 @@
     return APR_EINVAL;
 }
 
-APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file,
-                                          apr_os_file_t *thefile,
-                                          apr_pool_t *pool)
+APR_DECLARE(apr_status_t) ihs_os_pipe_put_ex(apr_file_t **file,
+                                             apr_os_file_t *thefile,
+                                             apr_int32_t extra_flags,
+                                             apr_pool_t *pool)
 {
     int *dafile = thefile;
     
@@ -185,12 +186,19 @@
     (*file)->timeout = -1;
     (*file)->ungetchar = -1; /* no char avail */
     (*file)->filedes = *dafile;
-    (*file)->flags = APR_FILE_NOCLEANUP;
+    (*file)->flags = APR_FILE_NOCLEANUP | extra_flags;
     (*file)->buffered = 0;
 #if APR_HAS_THREADS
     (*file)->thlock = NULL;
 #endif
     return APR_SUCCESS;
+}
+
+APR_DECLARE(apr_status_t) apr_os_pipe_put(apr_file_t **file,
+                                          apr_os_file_t *thefile,
+                                          apr_pool_t *pool)
+{
+    return ihs_os_pipe_put_ex(file, thefile, 0, pool);
 }
 
 APR_DECLARE(apr_status_t) apr_file_pipe_create(apr_file_t **in, apr_file_t **out, apr_pool_t *pool)
Index: srclib/apr/file_io/win32/seek.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/file_io/win32/seek.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/file_io/win32/seek.c	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/file_io/win32/seek.c	1 Jun 2004 20:46:15 -0000	1.2
@@ -122,7 +122,10 @@
         *offset = thefile->filePtr - thefile->dataRead + thefile->bufpos;
         return rc;
     } 
-    else if (thefile->pOverlapped) {
+    /* A file opened with APR_XTHREAD has been opened for overlapped i/o. 
+     * APR must explicitly track the file pointer in this case.
+     */
+    else if (thefile->pOverlapped || thefile->flags & APR_XTHREAD) {
         switch(where) {
             case APR_SET:
                 thefile->filePtr = *offset;
Index: srclib/apr/include/apr.hw
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/apr.hw,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/include/apr.hw	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/apr.hw	22 Mar 2005 22:18:52 -0000	1.3
@@ -87,11 +87,12 @@
  *   C4075: slight indirection changes (unsigned short* vs short[])
  *   C4100: unreferenced formal parameter
  *   C4127: conditional expression is constant
+ *   C4163: '_rotl64' : not available as an intrinsic function
  *   C4201: nonstandard extension nameless struct/unions
  *   C4244: int to char/short - precision loss
  *   C4514: unreferenced inline function removed
  */
-#pragma warning(disable: 4100 4127 4201 4514; once: 4057 4075 4244)
+#pragma warning(disable: 4100 4127 4163 4201 4514; once: 4057 4075 4244)
 
 /* Has windows.h already been included?  If so, our preferences don't matter,
  * but we will still need the winsock things no matter what was included.
@@ -244,7 +245,7 @@
 #define APR_HAVE_IN_ADDR        1
 #define APR_HAVE_INET_ADDR      1
 #define APR_HAVE_INET_NETWORK   0
-#define APR_HAVE_IPV6           0
+#define APR_HAVE_IPV6           1
 #define APR_HAVE_MEMMOVE        1
 #define APR_HAVE_SETRLIMIT      0
 #define APR_HAVE_SIGACTION      0
Index: srclib/apr/include/apr_atomic.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/apr_atomic.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/include/apr_atomic.h	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/apr_atomic.h	23 Aug 2005 19:00:21 -0000	1.3
@@ -251,6 +251,11 @@
 
 #define apr_atomic_t cs_t
 
+#if APR_SIZEOF_VOIDP == 8
+#define APR_OVERRIDE_ATOMIC_CASPTR 1
+void *apr_atomic_casptr(volatile void **mem, void *with, const void *cmp);
+#endif /* APR_SIZEOF_VOIDP */
+
 apr_int32_t apr_atomic_add(volatile apr_atomic_t *mem, apr_int32_t val);
 apr_uint32_t apr_atomic_cas(volatile apr_atomic_t *mem, apr_uint32_t swap, 
                             apr_uint32_t cmp);
Index: srclib/apr/include/apr_errno.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/apr_errno.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/include/apr_errno.h	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/apr_errno.h	17 Aug 2005 17:40:42 -0000	1.2
@@ -1161,7 +1161,12 @@
 /** path name is too long */
 #define APR_STATUS_IS_ENAMETOOLONG(s)   ((s) == APR_ENAMETOOLONG)
 /** no such file or directory */
+#ifdef EMVSCATLG /* z/OS-specific does-not-exist error code */
+#define APR_STATUS_IS_ENOENT(s)         ((s) == APR_ENOENT \
+                || (s) == EMVSCATLG)
+#else
 #define APR_STATUS_IS_ENOENT(s)         ((s) == APR_ENOENT)
+#endif
 /** not a directory */
 #define APR_STATUS_IS_ENOTDIR(s)        ((s) == APR_ENOTDIR)
 /** no space left on device */
Index: srclib/apr/include/apr_file_io.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/apr_file_io.h,v
retrieving revision 1.1.1.1
retrieving revision 1.5
diff -u -u -r1.1.1.1 -r1.5
--- srclib/apr/include/apr_file_io.h	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/apr_file_io.h	1 Feb 2005 18:10:23 -0000	1.5
@@ -104,7 +104,27 @@
 #define APR_FILE_NOCLEANUP  2048   /**< Do not register a cleanup when the file
                                         is opened */
 #define APR_SENDFILE_ENABLED  4096 /**< Advisory flag that this file should 
-                                        support apr_sendfile operation */ 
+                                        support apr_sendfile operation */
+#define APR_LARGEFILE   0x04000    /**< Platform dependent flag to enable large file
+                                        support; WARNING see below. */
+
+/* IHS_FILE_NO_BUCKET_CLOSE_AT_EOF is a temporary IHS extension which will
+ * not necessarily be maintained in the future.  Do not use it.
+ */
+#define IHS_FILE_NO_BUCKET_CLOSE_AT_EOF 65536  /**< Tell pipe bucket read not to close
+                                                    pipe after hitting EOF */
+
+/** @warning The APR_LARGEFILE flag only has effect on some platforms
+ * where sizeof(apr_off_t) == 4.  Where implemented, it allows opening
+ * and writing to a file which exceeds the size which can be
+ * represented by apr_off_t (2 gigabytes).  When a file's size does
+ * exceed 2Gb, apr_file_info_get() will fail with an error on the
+ * descriptor, likewise apr_stat()/apr_lstat() will fail on the
+ * filename.  apr_dir_read() will fail with APR_INCOMPLETE on a
+ * directory entry for a large file depending on the particular
+ * APR_FINFO_* flags.  Generally, it is not recommended to use this
+ * flag. */
+
 /** @} */
 
 /**
@@ -748,6 +768,21 @@
  */
 APR_DECLARE(apr_status_t) apr_file_mktemp(apr_file_t **fp, char *templ,
                                           apr_int32_t flags, apr_pool_t *p);
+
+/**
+ * Find an existing directory suitable as a temporary storage location.
+ * @param temp_dir The temp directory.
+ * @param p The pool to use for any necessary allocations.
+ * @remark
+ * This function uses an algorithm to search for a directory that an
+ * an application can use for temporary storage.  Once such a
+ * directory is found, that location is cached by the library.  Thus,
+ * callers only pay the cost of this algorithm once if that one time
+ * is successful.
+ *
+ */
+APR_DECLARE(apr_status_t) apr_temp_dir_get(const char **temp_dir,
+                                           apr_pool_t *p);
 
 /** @} */
 
Index: srclib/apr/include/apr_network_io.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/apr_network_io.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/include/apr_network_io.h	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/apr_network_io.h	29 Jul 2003 21:22:15 -0000	1.2
@@ -214,6 +214,8 @@
 
 /** A structure to represent sockets */
 typedef struct apr_socket_t     apr_socket_t;
+typedef struct apr_socket_iol_t apr_socket_iol_t;
+
 /**
  * A structure to encapsulate headers and trailers for apr_socket_sendfile
  */
@@ -863,6 +865,103 @@
 
 /** @} */
 
+
+/*
+ * Socket IOL
+ */
+
+APR_DECLARE(apr_status_t) apr_socket_iol_push(apr_socket_iol_t **newiol,
+                                              apr_socket_t *sock,
+                                              apr_socket_iol_t *iol,
+                                              const char *name);
+typedef apr_status_t (*apr_shutdown_fn_t) (apr_socket_t *thesocket,
+                                           apr_shutdown_how_e how);
+typedef apr_status_t (*apr_socket_close_fn_t) (apr_socket_t *thesocket);
+typedef apr_status_t (*apr_bind_fn_t) (apr_socket_t *sock, apr_sockaddr_t *sa);
+typedef apr_status_t (*apr_listen_fn_t) (apr_socket_t *sock, apr_int32_t backlog);
+typedef apr_status_t (*apr_accept_fn_t) (apr_socket_t **new_sock,
+                                         apr_socket_t *sock,
+                                         apr_pool_t *connection_pool);
+typedef apr_status_t (*apr_connect_fn_t) (apr_socket_t *sock, apr_sockaddr_t *sa);
+typedef apr_status_t (*apr_socket_data_get_fn_t) (void **data, const char *key,
+                                                  apr_socket_t *sock);
+typedef apr_status_t (*apr_socket_data_set_fn_t) (apr_socket_t *sock, void *data,
+                                                  const char *key,
+                                                  apr_status_t (*cleanup)(void*));
+typedef apr_status_t (*apr_send_fn_t) (apr_socket_t *sock, const char *buf,
+                                       apr_size_t *len);
+typedef apr_status_t (*apr_sendv_fn_t) (apr_socket_t *sock,
+                                        const struct iovec *vec,
+                                        apr_int32_t nvec, apr_size_t *len);
+typedef apr_status_t (*apr_sendto_fn_t) (apr_socket_t *sock, apr_sockaddr_t *where,
+                                         apr_int32_t flags, const char *buf,
+                                         apr_size_t *len);
+typedef apr_status_t (*apr_recvfrom_fn_t) (apr_sockaddr_t *from, apr_socket_t *sock,
+                                           apr_int32_t flags, char *buf,
+                                           apr_size_t *len);
+#if APR_HAS_SENDFILE
+typedef apr_status_t (*apr_sendfile_fn_t) (apr_socket_t *sock, apr_file_t *file,
+                                           apr_hdtr_t *hdtr, apr_off_t *offset,
+                                           apr_size_t *len, apr_int32_t flags);
+#endif /* APR_HAS_SENDFILE */
+typedef apr_status_t (*apr_recv_fn_t) (apr_socket_t *sock,
+                                       char *buf, apr_size_t *len);
+typedef apr_status_t (*apr_setsocketopt_fn_t) (apr_socket_t *sock,
+                                               apr_int32_t opt, apr_int32_t on);
+typedef apr_status_t (*apr_getsocketopt_fn_t) (apr_socket_t *sock,
+                                               apr_int32_t opt, apr_int32_t *on);
+typedef apr_status_t (*apr_socket_opt_set_fn_t) (apr_socket_t *sock,
+                                                 apr_int32_t opt, apr_int32_t on);
+typedef apr_status_t (*apr_socket_opt_get_fn_t) (apr_socket_t *sock,
+                                                 apr_int32_t opt, apr_int32_t *on);
+typedef apr_status_t (*apr_socket_timeout_set_fn_t) (apr_socket_t *sock,
+                                                     apr_interval_time_t t);
+typedef apr_status_t (*apr_socket_timeout_get_fn_t) (apr_socket_t *sock,
+                                                     apr_interval_time_t *t);
+typedef apr_status_t (*apr_socket_addr_get_fn_t) (apr_sockaddr_t **sa,
+                                                  apr_interface_e which,
+                                                  apr_socket_t *sock);
+typedef void (*apr_socket_set_inherit_fn_t) (apr_socket_t *sock);
+typedef void (*apr_socket_unset_inherit_fn_t) (apr_socket_t *sock);
+#if APR_HAS_SO_ACCEPTFILTER
+typedef apr_status_t (*apr_socket_accept_filter_fn_t) (apr_socket_t *sock, char *name,
+                                      char *args);
+#endif
+
+
+struct apr_socket_iol_t
+{
+    struct apr_socket_iol_t      *next;
+    const char                   *name;
+    apr_shutdown_fn_t             iol_socket_shutdown;
+    apr_socket_close_fn_t         iol_socket_close;
+    apr_bind_fn_t                 iol_socket_bind;
+    apr_listen_fn_t               iol_socket_listen;
+    apr_accept_fn_t               iol_socket_accept;
+    apr_connect_fn_t              iol_socket_connect;
+    apr_socket_data_get_fn_t      iol_socket_data_get;
+    apr_socket_data_set_fn_t      iol_socket_data_set;
+    apr_send_fn_t                 iol_socket_send;
+    apr_sendv_fn_t                iol_socket_sendv;
+    apr_sendto_fn_t               iol_socket_sendto;
+    apr_recvfrom_fn_t             iol_socket_recvfrom;
+#if APR_HAS_SENDFILE
+    apr_sendfile_fn_t             iol_socket_sendfile;
+#endif /* APR_HAS_SENDFILE */
+    apr_recv_fn_t                 iol_socket_recv;
+    apr_setsocketopt_fn_t         iol_socket_setsocketopt;
+    apr_getsocketopt_fn_t         iol_socket_getsocketopt;
+    apr_socket_opt_set_fn_t       iol_socket_opt_set;
+    apr_socket_opt_get_fn_t       iol_socket_opt_get;
+    apr_socket_timeout_set_fn_t   iol_socket_timeout_set;
+    apr_socket_timeout_get_fn_t   iol_socket_timeout_get;
+    apr_socket_addr_get_fn_t      iol_socket_addr_get;
+    apr_socket_set_inherit_fn_t   iol_socket_set_inherit;
+    apr_socket_unset_inherit_fn_t iol_socket_unset_inherit;
+#if APR_HAS_SO_ACCEPTFILTER
+    apr_socket_accept_filter_fn_t iol_socket_accept_filter;
+#endif
+};
 #ifdef __cplusplus
 }
 #endif
Index: srclib/apr/include/apr_portable.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/apr_portable.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/include/apr_portable.h	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/apr_portable.h	5 Oct 2003 12:51:39 -0000	1.3
@@ -390,6 +390,14 @@
                                           apr_os_file_t *thefile,
                                           apr_pool_t *cont);
 
+/* ihs_os_pipe_put_ex() is a temporary IHS extension which will
+ * not necessarily be maintained in the future.  Do not use it.
+ */
+APR_DECLARE(apr_status_t) ihs_os_pipe_put_ex(apr_file_t **file,
+                                             apr_os_file_t *thefile,
+                                             apr_int32_t flags,
+                                             apr_pool_t *cont);
+
 /**
  * convert the dir from os specific type to apr type.
  * @param dir The apr dir we are converting to.
Index: srclib/apr/include/apr_thread_proc.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/apr_thread_proc.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/include/apr_thread_proc.h	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/apr_thread_proc.h	15 Jun 2005 16:33:09 -0000	1.3
@@ -84,7 +84,10 @@
     APR_SHELLCMD,       /**< use the shell to invoke the program */
     APR_PROGRAM,        /**< invoke the program directly, no copied env */
     APR_PROGRAM_ENV,    /**< invoke the program, replicating our environment */
-    APR_PROGRAM_PATH    /**< find program on PATH, use our environment */
+    APR_PROGRAM_PATH,   /**< find program on PATH, use our environment */
+    APR_SHELLCMD_ENV    /**< use the shell to invoke the program,
+                         *   replicating our environment
+                         */
 } apr_cmdtype_e;
 
 typedef enum {
@@ -255,6 +258,14 @@
 APR_DECLARE(apr_status_t) apr_threadattr_detach_get(apr_threadattr_t *attr);
 
 /**
+ * Set the stack size of newly created threads.
+ * @param attr The threadattr to affect 
+ * @param on The stack size in bytes
+ */
+APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr,
+                                                       apr_size_t stacksize);
+
+/**
  * Create a new thread of execution
  * @param new_thread The newly created thread handle.
  * @param attr The threadattr to use to determine how to create the thread
@@ -550,8 +561,8 @@
  *             one should be the program name.
  * @param env The new environment table for the new process.  This 
  *            should be a list of NULL-terminated strings. This argument
- *            is ignored for APR_PROGRAM_ENV and APR_PROGRAM_PATH types
- *            of commands.
+ *            is ignored for APR_PROGRAM_ENV, APR_PROGRAM_PATH, and
+ *            APR_SHELLCMD_ENV types of commands.
  * @param attr the procattr we should use to determine how to create the new
  *         process
  * @param cont The pool to use. 
Index: srclib/apr/include/arch/unix/apr_arch_networkio.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/arch/unix/apr_arch_networkio.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/include/arch/unix/apr_arch_networkio.h	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/arch/unix/apr_arch_networkio.h	9 Mar 2004 15:23:35 -0000	1.3
@@ -55,6 +55,8 @@
 #ifndef NETWORK_IO_H
 #define NETWORK_IO_H
 
+#define APR_DEBUG_NET  /* IBM: save input data for problem diagnosis */
+
 #include "apr.h"
 #include "apr_private.h"
 #include "apr_network_io.h"
@@ -122,6 +124,22 @@
 #define POLLNVAL 32
 #endif
 
+#ifdef APR_DEBUG_NET
+struct apr_debug_net_buffer {
+    struct apr_debug_net_buffer *next;
+    apr_int32_t saved_len;
+    apr_int32_t actual_len;
+    char data[1]; /* actual data starts here */
+};
+#endif
+
+typedef struct sock_userdata_t sock_userdata_t;
+struct sock_userdata_t {
+    sock_userdata_t *next;
+    const char *key;
+    void *data;
+};
+
 struct apr_socket_t {
     apr_pool_t *cntxt;
     int socketdes;
@@ -138,6 +156,13 @@
     int remote_addr_unknown;
     apr_int32_t netmask;
     apr_int32_t inherit;
+#ifdef APR_DEBUG_NET
+    struct apr_debug_net_buffer *head;
+    int num_saved_buffers;
+#endif
+    /* IBM: added for socket IOLs */
+    apr_socket_iol_t *iol;
+    sock_userdata_t    *userdata;
 };
 
 const char *apr_inet_ntop(int af, const void *src, char *dst, apr_size_t size);
Index: srclib/apr/include/arch/win32/apr_arch_networkio.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/arch/win32/apr_arch_networkio.h,v
retrieving revision 1.1.1.1
retrieving revision 1.5
diff -u -u -r1.1.1.1 -r1.5
--- srclib/apr/include/arch/win32/apr_arch_networkio.h	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/arch/win32/apr_arch_networkio.h	24 Jul 2004 02:13:48 -0000	1.5
@@ -58,6 +58,13 @@
 #include "apr_network_io.h"
 #include "apr_general.h"
 
+typedef struct sock_userdata_t sock_userdata_t;
+struct sock_userdata_t {
+    sock_userdata_t *next;
+    const char *key;
+    void *data;
+};
+
 struct apr_socket_t {
     apr_pool_t         *cntxt;
     SOCKET              socketdes;
@@ -73,6 +80,13 @@
     int                 remote_addr_unknown;
     apr_int32_t         netmask;
     apr_int32_t         inherit;
+    /* As of 07.20.04, the overlapped structure is only used by 
+     * apr_socket_sendfile and that's where it will be allocated 
+     * and initialized.
+     */
+    OVERLAPPED         *overlapped;
+    sock_userdata_t    *userdata;
+    apr_socket_iol_t   *iol; /* IBM: socket iols */
 };
 
 #ifdef _WIN32_WCE
Index: srclib/apr/include/arch/win32/apr_arch_threadproc.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/include/arch/win32/apr_arch_threadproc.h,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/include/arch/win32/apr_arch_threadproc.h	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/include/arch/win32/apr_arch_threadproc.h	26 Aug 2004 15:49:13 -0000	1.3
@@ -74,6 +74,7 @@
 struct apr_threadattr_t {
     apr_pool_t *pool;
     apr_int32_t detach;
+    apr_size_t stacksize;
 };
 
 struct apr_threadkey_t {
@@ -92,6 +93,8 @@
     char *currdir;
     apr_int32_t cmdtype;
     apr_int32_t detached;
+    apr_child_errfn_t *errfn;
+    apr_int32_t errchk;
 };
 
 struct apr_thread_once_t {
Index: srclib/apr/memory/unix/apr_pools.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/memory/unix/apr_pools.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/memory/unix/apr_pools.c	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/memory/unix/apr_pools.c	31 Jul 2003 02:36:00 -0000	1.2
@@ -856,7 +856,7 @@
 #if APR_HAS_THREADS
         apr_thread_mutex_t *mutex;
 
-        if ((mutex = apr_allocator_mutex_get(allocator)) != NULL)
+        if ((mutex = apr_allocator_mutex_get(parent->allocator)) != NULL)
             apr_thread_mutex_lock(mutex);
 #endif /* APR_HAS_THREADS */
 
Index: srclib/apr/misc/unix/errorcodes.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/misc/unix/errorcodes.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/misc/unix/errorcodes.c	29 Jul 2003 20:19:26 -0000	1.1.1.1
+++ srclib/apr/misc/unix/errorcodes.c	8 Sep 2005 19:43:39 -0000	1.3
@@ -164,6 +164,8 @@
         return "The given path was above the root path";
     case APR_EBADPATH:
         return "The given path misformatted or contained invalid characters";
+    case APR_EPATHWILD:
+        return "The given path contained wildcard characters";
     case APR_EPROC_UNKNOWN:
         return "The process is not recognized.";
     default:
@@ -400,7 +402,12 @@
     sprintf(err, "Native Error #%d", statcode);
     return stuffbuffer(buf, bufsize, err);
 #else
-    return stuffbuffer(buf, bufsize, strerror(statcode));
+    const char *err = strerror(statcode);
+    if (err) {
+        return stuffbuffer(buf, bufsize, err);
+    } else {
+        return stuffbuffer(buf, bufsize, "APR does not understand this error code"); 
+    }
 #endif
 }
 #endif
Index: srclib/apr/network_io/unix/Makefile.in
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/network_io/unix/Makefile.in,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/network_io/unix/Makefile.in	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/network_io/unix/Makefile.in	29 Jul 2003 21:22:17 -0000	1.2
@@ -6,6 +6,7 @@
 	sockets.lo \
 	sockopt.lo \
 	sockaddr.lo \
+       aprsockapi.lo \
 	inet_ntop.lo \
 	inet_pton.lo
 
Index: srclib/apr/network_io/unix/sendrecv.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/network_io/unix/sendrecv.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/network_io/unix/sendrecv.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/network_io/unix/sendrecv.c	29 Jul 2003 21:22:17 -0000	1.2
@@ -54,6 +54,12 @@
 
 #include "apr_arch_networkio.h"
 #include "apr_support.h"
+/* IBM add in socket IOLs */
+#include "../../include/arch/rename.h"
+
+#ifdef APR_DEBUG_NET
+#include <stddef.h>
+#endif
 
 #if APR_HAS_SENDFILE
 /* This file is needed to allow us access to the apr_file_t internals. */
@@ -141,6 +147,20 @@
         sock->netmask |= APR_INCOMPLETE_READ;
     }
     (*len) = rv;
+#ifdef APR_DEBUG_NET
+    if (sock->num_saved_buffers < 20)
+    {
+        apr_size_t bytes_to_save = (*len > 1024) ? 1024 : *len;
+        struct apr_debug_net_buffer *new = apr_palloc(sock->cntxt,
+                                                      offsetof(struct apr_debug_net_buffer, data) + bytes_to_save);
+        memcpy(new->data, buf, bytes_to_save);
+        new->saved_len = bytes_to_save;
+        new->actual_len = *len;
+        new->next = sock->head;
+        sock->head = new;
+        ++sock->num_saved_buffers;
+    }
+#endif
     if (rv == 0) {
         return APR_EOF;
     }
Index: srclib/apr/network_io/unix/sockaddr.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/network_io/unix/sockaddr.c,v
retrieving revision 1.1.1.1
retrieving revision 1.6
diff -u -u -r1.1.1.1 -r1.6
--- srclib/apr/network_io/unix/sockaddr.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/network_io/unix/sockaddr.c	13 Oct 2005 11:14:12 -0000	1.6
@@ -54,6 +54,9 @@
 
 #include "apr_arch_networkio.h"
 #include "apr_strings.h"
+/* IBM add in socket IOLs */
+#include "../../include/arch/rename.h"
+
 #include "apr.h"
 #include "apr_lib.h"
 #include "apr_strings.h"
@@ -600,7 +603,30 @@
     /* default flags are NI_NAMREQD; otherwise, getnameinfo() will return
      * a numeric address string if it fails to resolve the host name;
      * that is *not* what we want here
+     *
+     * Additionally, if we know getnameinfo() doesn't handle IPv4-mapped
+     * IPv6 addresses correctly, drop down to IPv4 before calling
+     * getnameinfo().
      */
+/* IHS: assume no platforms have this working; little extra overhead
+ *      to assume that, but APR configure-time check is not
+ *      sufficient
+ */
+#define GETNAMEINFO_IPV4_MAPPED_FAILS
+#if APR_HAVE_IPV6 && defined(GETNAMEINFO_IPV4_MAPPED_FAILS)
+    if (sockaddr->family == AF_INET6 &&
+        IN6_IS_ADDR_V4MAPPED(&sockaddr->sa.sin6.sin6_addr)) {
+        struct sockaddr_in tmpsa;
+        tmpsa.sin_family = AF_INET;
+        tmpsa.sin_port = 0;
+        tmpsa.sin_addr.s_addr = ((apr_uint32_t *)sockaddr->ipaddr_ptr)[3];
+
+        rc = getnameinfo((const struct sockaddr *)&tmpsa, sizeof(tmpsa),
+                         tmphostname, sizeof(tmphostname), NULL, 0,
+                         flags != 0 ? flags : NI_NAMEREQD);
+    }
+    else
+#endif
     rc = getnameinfo((const struct sockaddr *)&sockaddr->sa, sockaddr->salen,
                      tmphostname, sizeof(tmphostname), NULL, 0,
                      flags != 0 ? flags : NI_NAMEREQD);
Index: srclib/apr/network_io/unix/sockets.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/network_io/unix/sockets.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- srclib/apr/network_io/unix/sockets.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/network_io/unix/sockets.c	9 Mar 2004 15:23:37 -0000	1.4
@@ -54,9 +54,12 @@
 
 #include "apr_arch_networkio.h"
 #include "apr_network_io.h"
+#include "apr_strings.h"
 #include "apr_support.h"
 #include "apr_portable.h"
 #include "apr_arch_inherit.h"
+/* IBM add in socket IOLs */
+#include "../../include/arch/rename.h"
 
 #if defined(BEOS) && !defined(BEOS_BONE)
 #define close closesocket
@@ -293,7 +296,7 @@
 #endif /* SO_ERROR */
     }
 
-    if (rc == -1) {
+    if (rc == -1 && errno != EISCONN) {
         return errno;
     }
 
@@ -318,13 +321,36 @@
 
 apr_status_t apr_socket_data_get(void **data, const char *key, apr_socket_t *sock)
 {
-    return apr_pool_userdata_get(data, key, sock->cntxt);
+    sock_userdata_t *cur = sock->userdata;
+
+    *data = NULL;
+
+    while (cur) {
+        if (!strcmp(cur->key, key)) {
+            *data = cur->data;
+            break;
+        }
+        cur = cur->next;
+    }
+
+    return APR_SUCCESS;
 }
 
 apr_status_t apr_socket_data_set(apr_socket_t *sock, void *data, const char *key,
                               apr_status_t (*cleanup) (void *))
 {
-    return apr_pool_userdata_set(data, key, cleanup, sock->cntxt);
+    sock_userdata_t *new = apr_palloc(sock->cntxt, sizeof(sock_userdata_t));
+
+    new->key = apr_pstrdup(sock->cntxt, key);
+    new->data = data;
+    new->next = sock->userdata;
+    sock->userdata = new;
+
+    if (cleanup) {
+        apr_pool_cleanup_register(sock->cntxt, data, cleanup, cleanup);
+    }
+
+    return APR_SUCCESS;
 }
 
 apr_status_t apr_os_sock_get(apr_os_sock_t *thesock, apr_socket_t *sock)
Index: srclib/apr/network_io/unix/sockopt.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/network_io/unix/sockopt.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/network_io/unix/sockopt.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/network_io/unix/sockopt.c	29 Jul 2003 21:22:17 -0000	1.2
@@ -54,6 +54,8 @@
 
 #include "apr_arch_networkio.h"
 #include "apr_strings.h"
+/* IBM add in socket IOLs */
+#include "../../include/arch/rename.h"
 
 static apr_status_t soblock(int sd)
 {
Index: srclib/apr/network_io/win32/sendrecv.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/network_io/win32/sendrecv.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/network_io/win32/sendrecv.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/network_io/win32/sendrecv.c	22 Jul 2004 03:42:42 -0000	1.3
@@ -62,6 +62,9 @@
 #include <time.h>
 #endif
 
+/* IBM add in socket IOLs */
+#include "../../include/arch/rename.h"
+
 /* MAX_SEGMENT_SIZE is the maximum amount of data that will be sent to a client
  * in one call of TransmitFile. This number must be small enough to give the 
  * slowest client time to receive the data before the socket timeout triggers.
@@ -245,16 +248,6 @@
 
 #if APR_HAS_SENDFILE
 /*
- *#define WAIT_FOR_EVENT
- * Note: Waiting for the socket directly is much faster than creating a seperate
- * wait event. There are a couple of dangerous aspects to waiting directly 
- * for the socket. First, we should not wait on the socket if concurrent threads
- * can wait-on/signal the same socket. This shouldn't be happening with Apache since 
- * a socket is uniquely tied to a thread. This will change when we begin using 
- * async I/O with completion ports on the socket. 
- */
-
-/*
  * apr_status_t apr_socket_sendfile(apr_socket_t *, apr_file_t *, apr_hdtr_t *, 
  *                                 apr_off_t *, apr_size_t *, apr_int32_t flags)
  *    Send a file from an open file descriptor to a socket, along with 
@@ -278,13 +271,11 @@
     apr_off_t curoff = *offset;
     DWORD dwFlags = 0;
     DWORD nbytes;
-    OVERLAPPED overlapped;
     TRANSMIT_FILE_BUFFERS tfb, *ptfb = NULL;
     int ptr = 0;
     int bytes_to_send;   /* Bytes to send out of the file (not including headers) */
     int disconnected = 0;
     int sendv_trailers = 0;
-    HANDLE wait_event;
     char hdtrbuf[4096];
 
     if (apr_os_level < APR_WIN_NT) {
@@ -316,12 +307,6 @@
 
     /* Initialize the header/trailer and overlapped structures */
     memset(&tfb, '\0', sizeof (tfb));
-    memset(&overlapped,'\0', sizeof(overlapped));
-#ifdef WAIT_FOR_EVENT
-    wait_event = overlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
-#else
-    wait_event = (HANDLE) sock->socketdes;
-#endif
 
     /* Collapse the headers into a single buffer */
     if (hdtr && hdtr->numheaders) {
@@ -340,6 +325,12 @@
         }
     }
 
+    /* Initialize the overlapped structure used on TransmitFile
+     */
+    if (!sock->overlapped) {
+        sock->overlapped = apr_pcalloc(sock->cntxt, sizeof(OVERLAPPED));
+        sock->overlapped->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
+    }
     while (bytes_to_send) {
         if (bytes_to_send > MAX_SEGMENT_SIZE) {
             nbytes = MAX_SEGMENT_SIZE;
@@ -368,16 +359,16 @@
             }
         }
 
-        overlapped.Offset = (DWORD)(curoff);
+        sock->overlapped->Offset = (DWORD)(curoff);
 #if APR_HAS_LARGE_FILES
-        overlapped.OffsetHigh = (DWORD)(curoff >> 32);
-#endif  
+        sock->overlapped->OffsetHigh = (DWORD)(curoff >> 32);
+#endif
         /* XXX BoundsChecker claims dwFlags must not be zero. */
         rv = TransmitFile(sock->socketdes,  /* socket */
                           file->filehand, /* open file descriptor of the file to be sent */
                           nbytes,         /* number of bytes to send. 0=send all */
                           0,              /* Number of bytes per send. 0=use default */
-                          &overlapped,    /* OVERLAPPED structure */
+                          sock->overlapped,    /* OVERLAPPED structure */
                           ptfb,           /* header and trailer buffers */
                           dwFlags);       /* flags to control various aspects of TransmitFile */
         if (!rv) {
@@ -385,17 +376,20 @@
             if ((status == APR_FROM_OS_ERROR(ERROR_IO_PENDING)) ||
                 (status == APR_FROM_OS_ERROR(WSA_IO_PENDING))) 
             {
-                rv = WaitForSingleObject(wait_event, 
+                rv = WaitForSingleObject(sock->overlapped->hEvent, 
                                          (DWORD)(sock->timeout >= 0 
                                                  ? sock->timeout_ms : INFINITE));
                 if (rv == WAIT_OBJECT_0) {
                     status = APR_SUCCESS;
                     if (!disconnected) {
-                        if (!GetOverlappedResult(wait_event, &overlapped, 
-                                                 &nbytes, FALSE)) {
-                            status = apr_get_os_error();
+                        if (!WSAGetOverlappedResult(sock->socketdes,
+                                                    sock->overlapped,
+                                                    &nbytes,
+                                                    FALSE,
+                                                    &dwFlags)) {
+                            status = apr_get_netos_error();
                         }
-                        /* Ugly code alert: GetOverlappedResult returns
+                        /* Ugly code alert: WSAGetOverlappedResult returns
                          * a count of all bytes sent. This loop only
                          * tracks bytes sent out of the file.
                          */
@@ -454,9 +448,6 @@
         }
     }
 
-#ifdef WAIT_FOR_EVENT
-    CloseHandle(overlapped.hEvent);
-#endif
     return status;
 }
 
Index: srclib/apr/network_io/win32/sockets.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/network_io/win32/sockets.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- srclib/apr/network_io/win32/sockets.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/network_io/win32/sockets.c	22 Jul 2004 03:42:42 -0000	1.4
@@ -57,6 +57,9 @@
 #include "apr_general.h"
 #include "apr_lib.h"
 #include "apr_portable.h"
+#include "apr_strings.h"
+/* IBM add in socket IOLs */
+#include "../../include/arch/rename.h"
 #include <string.h>
 #include "apr_arch_inherit.h"
 #include "apr_arch_misc.h"
@@ -73,6 +76,10 @@
         }
         thesocket->socketdes = INVALID_SOCKET;
     }
+    if (thesocket->overlapped) {
+        CloseHandle(thesocket->overlapped->hEvent);
+        thesocket->overlapped = NULL;
+    }
     return APR_SUCCESS;
 }
 
@@ -172,6 +179,7 @@
 
     (*new)->timeout = -1;
     (*new)->disconnected = 0;
+    (*new)->iol = NULL;
 
     apr_pool_cleanup_register((*new)->cntxt, (void *)(*new), 
                         socket_cleanup, apr_pool_cleanup_null);
@@ -403,16 +411,39 @@
 }
 
 APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key,
-                                             apr_socket_t *socket)
+                                             apr_socket_t *sock)
 {
-    return apr_pool_userdata_get(data, key, socket->cntxt);
+    sock_userdata_t *cur = sock->userdata;
+
+    *data = NULL;
+
+    while (cur) {
+        if (!strcmp(cur->key, key)) {
+            *data = cur->data;
+            break;
+        }
+        cur = cur->next;
+    }
+
+    return APR_SUCCESS;
 }
 
-APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *socket, void *data,
+APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data,
                                              const char *key,
                                              apr_status_t (*cleanup)(void *))
 {
-    return apr_pool_userdata_set(data, key, cleanup, socket->cntxt);
+    sock_userdata_t *new = apr_palloc(sock->cntxt, sizeof(sock_userdata_t));
+
+    new->key = apr_pstrdup(sock->cntxt, key);
+    new->data = data;
+    new->next = sock->userdata;
+    sock->userdata = new;
+
+    if (cleanup) {
+        apr_pool_cleanup_register(sock->cntxt, data, cleanup, cleanup);
+    }
+
+    return APR_SUCCESS;
 }
 
 APR_DECLARE(apr_status_t) apr_os_sock_get(apr_os_sock_t *thesock,
Index: srclib/apr/network_io/win32/sockopt.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/network_io/win32/sockopt.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/network_io/win32/sockopt.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/network_io/win32/sockopt.c	14 Jun 2005 12:21:39 -0000	1.3
@@ -57,6 +57,8 @@
 #include "apr_general.h"
 #include "apr_strings.h"
 #include <string.h>
+/* IBM add in socket IOLs */
+#include "../../include/arch/rename.h"
 
 apr_status_t soblock(SOCKET sd)
 {
@@ -154,6 +156,18 @@
                 return apr_get_netos_error();
             }
             apr_set_option(&sock->netmask, APR_SO_DEBUG, on);
+        }
+        break;
+    case APR_SO_SNDBUF:
+        if (setsockopt(sock->socketdes, SOL_SOCKET, SO_SNDBUF,
+                       (void *)&on, sizeof(int)) == -1) {
+            return apr_get_netos_error();
+        }
+        break;
+    case APR_SO_RCVBUF:
+        if (setsockopt(sock->socketdes, SOL_SOCKET, SO_RCVBUF,
+                       (void *)&on, sizeof(int)) == -1) {
+            return apr_get_netos_error();
         }
         break;
     case APR_SO_REUSEADDR:
Index: srclib/apr/poll/unix/poll.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/poll/unix/poll.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/poll/unix/poll.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/poll/unix/poll.c	29 Jul 2003 21:22:18 -0000	1.2
@@ -67,6 +67,8 @@
 #if HAVE_ALLOCA_H
 #include <alloca.h>
 #endif
+/*IBM add in socket iols */
+#include "../../include/arch/rename.h"
 
 #ifdef NETWARE
 #define HAS_SOCKETS(dt) (dt == APR_POLL_SOCKET) ? 1 : 0
Index: srclib/apr/strings/apr_cpystrn.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/strings/apr_cpystrn.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/strings/apr_cpystrn.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/strings/apr_cpystrn.c	22 Oct 2005 15:32:42 -0000	1.2
@@ -207,6 +207,7 @@
 
     /*  determine first argument */
     for (argnum = 0; argnum < (numargs-1); argnum++) {
+        SKIP_WHITESPACE(cp);
         CHECK_QUOTATION(cp, isquoted);
         ct = cp;
         DETERMINE_NEXTSTRING(cp, isquoted);
@@ -215,7 +216,6 @@
         apr_cpystrn((*argv_out)[argnum], ct, cp - ct);
         cleaned = dirty = (*argv_out)[argnum];
         REMOVE_ESCAPE_CHARS(cleaned, dirty, escaped);
-        SKIP_WHITESPACE(cp);
     }
     (*argv_out)[argnum] = NULL;
 
Index: srclib/apr/threadproc/unix/proc.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/threadproc/unix/proc.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/threadproc/unix/proc.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/threadproc/unix/proc.c	10 Oct 2005 10:47:30 -0000	1.3
@@ -317,6 +317,14 @@
                                           apr_pool_t *pool)
 {
     int i;
+    const char * const empty_envp[] = {NULL};
+
+    if (!env) { /* Specs require an empty array instead of NULL;
+                 * Purify will trigger a failure, even if many
+                 * implementations don't.
+                 */
+        env = empty_envp;
+    }
 
     new->in = attr->parent_in;
     new->err = attr->parent_err;
@@ -421,7 +429,8 @@
             exit(-1);   /* We have big problems, the child should exit. */
         }
 
-        if (attr->cmdtype == APR_SHELLCMD) {
+        if (attr->cmdtype == APR_SHELLCMD ||
+            attr->cmdtype == APR_SHELLCMD_ENV) {
             int onearg_len = 0;
             const char *newargs[4];
 
@@ -472,7 +481,12 @@
                 apr_proc_detach(APR_PROC_DETACH_DAEMONIZE);
             }
 
-            execve(SHELL_PATH, (char * const *) newargs, (char * const *)env);
+            if (attr->cmdtype == APR_SHELLCMD) {
+                execve(SHELL_PATH, (char * const *) newargs, (char * const *)env);
+            }
+            else {
+                execv(SHELL_PATH, (char * const *)newargs);
+            }
         }
         else if (attr->cmdtype == APR_PROGRAM) {
             if (attr->detached) {
Index: srclib/apr/threadproc/unix/thread.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/threadproc/unix/thread.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/threadproc/unix/thread.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/threadproc/unix/thread.c	14 Mar 2004 15:21:13 -0000	1.2
@@ -121,6 +121,22 @@
     return APR_NOTDETACH;
 }
 
+APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr,
+                                                       apr_size_t stacksize)
+{
+    int stat;
+
+    stat = pthread_attr_setstacksize(attr->attr, stacksize);
+    if (stat == 0) {
+        return APR_SUCCESS;
+    }
+#ifdef PTHREAD_SETS_ERRNO
+    stat = errno;
+#endif
+
+    return stat;
+}
+
 static void *dummy_worker(void *opaque)
 {
     apr_thread_t *thread = (apr_thread_t*)opaque;
Index: srclib/apr/threadproc/win32/proc.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/threadproc/win32/proc.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr/threadproc/win32/proc.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/threadproc/win32/proc.c	15 Jun 2005 16:33:09 -0000	1.3
@@ -284,14 +284,14 @@
 APR_DECLARE(apr_status_t) apr_procattr_child_errfn_set(apr_procattr_t *attr,
                                                        apr_child_errfn_t *errfn)
 {
-    /* won't ever be called on this platform, so don't save the function pointer */
+    attr->errfn = errfn;
     return APR_SUCCESS;
 }
 
 APR_DECLARE(apr_status_t) apr_procattr_error_check_set(apr_procattr_t *attr,
                                                        apr_int32_t chk)
 {
-    /* won't ever be used on this platform, so don't save the flag */
+    attr->errchk = chk;
     return APR_SUCCESS;
 }
 
@@ -343,6 +343,12 @@
         char *fullpath = NULL;
         if ((rv = apr_filepath_merge(&fullpath, attr->currdir, progname, 
                                      APR_FILEPATH_NATIVE, pool)) != APR_SUCCESS) {
+            if (attr->errfn) {
+                attr->errfn(pool, rv, 
+                            apr_pstrcat(pool, "filepath_merge failed.", 
+                                        " currdir: ", attr->currdir, 
+                                        " progname: ", progname,NULL));
+            }
             return rv;
         }
         progname = fullpath;
@@ -381,9 +387,12 @@
     }
 
 #ifndef _WIN32_WCE
-    if (attr->cmdtype == APR_SHELLCMD) {
+    if (attr->cmdtype == APR_SHELLCMD || attr->cmdtype == APR_SHELLCMD_ENV) {
         char *shellcmd = getenv("COMSPEC");
         if (!shellcmd) {
+            if (attr->errfn) {
+                attr->errfn(pool, APR_EINVAL, "COMSPEC envar is not set");
+            }
             return APR_EINVAL;
         }
         if (shellcmd[0] == '"') {
@@ -420,6 +429,9 @@
         {
             char *shellcmd = getenv("COMSPEC");
             if (!shellcmd) {
+                if (attr->errfn) {
+                    attr->errfn(pool, APR_EINVAL, "COMSPEC envar is not set");
+                }
                 return APR_EINVAL;
             }
             if (shellcmd[0] == '"') {
@@ -477,8 +489,10 @@
         }
     }
 
-    if (!env || attr->cmdtype == APR_PROGRAM_ENV) 
+    if (!env || attr->cmdtype == APR_PROGRAM_ENV ||
+        attr->cmdtype == APR_SHELLCMD_ENV) {
         pEnvBlock = NULL;
+    }
     else {
         apr_size_t iEnvBlockLen;
         /*
@@ -509,6 +523,12 @@
                 if ((rv = apr_conv_utf8_to_ucs2(env[i], &in, 
                                                 pNext, &iEnvBlockLen)) 
                         != APR_SUCCESS) {
+                    if (attr->errfn) {
+                        attr->errfn(pool, rv, 
+                                    apr_pstrcat(pool, 
+                                                "utf8 to ucs2 conversion failed" 
+                                                " on this string: ", env[i], NULL));
+                    }
                     return rv;
                 }
                 pNext = wcschr(pNext, L'\0') + 1;
@@ -555,6 +575,12 @@
             wprg = apr_palloc(pool, nwprg * sizeof(wprg[0]));
             if ((rv = apr_conv_utf8_to_ucs2(progname, &nprg, wprg, &nwprg))
                    != APR_SUCCESS) {
+                if (attr->errfn) {
+                    attr->errfn(pool, rv, 
+                                apr_pstrcat(pool, 
+                                            "utf8 to ucs2 conversion failed" 
+                                            " on progname: ", progname, NULL));
+                }
                 return rv;
             }
         }
@@ -565,6 +591,12 @@
             wcmd = apr_palloc(pool, nwcmd * sizeof(wcmd[0]));
             if ((rv = apr_conv_utf8_to_ucs2(cmdline, &ncmd, wcmd, &nwcmd))
                     != APR_SUCCESS) {
+                if (attr->errfn) {
+                    attr->errfn(pool, rv, 
+                                apr_pstrcat(pool, 
+                                            "utf8 to ucs2 conversion failed" 
+                                            " on cmdline: ", cmdline, NULL));
+                }
                 return rv;
             }
         }
@@ -577,6 +609,12 @@
             if ((rv = apr_conv_utf8_to_ucs2(attr->currdir, &ncwd, 
                                             wcwd, &nwcwd))
                     != APR_SUCCESS) {
+                if (attr->errfn) {
+                    attr->errfn(pool, rv, 
+                                apr_pstrcat(pool, 
+                                            "utf8 to ucs2 conversion failed" 
+                                            " on currdir: ", attr->currdir,NULL));
+                }
                 return rv;
             }
         }
Index: srclib/apr/threadproc/win32/thread.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr/threadproc/win32/thread.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr/threadproc/win32/thread.c	29 Jul 2003 20:19:27 -0000	1.1.1.1
+++ srclib/apr/threadproc/win32/thread.c	14 Mar 2004 15:21:14 -0000	1.2
@@ -77,6 +77,9 @@
     }
 
     (*new)->pool = pool;
+    (*new)->detach = 0;
+    (*new)->stacksize = 0;
+
     return APR_SUCCESS;
 }
 
@@ -94,6 +97,13 @@
     return APR_NOTDETACH;
 }
 
+APR_DECLARE(apr_status_t) apr_threadattr_stacksize_set(apr_threadattr_t *attr,
+                                                       apr_size_t stacksize)
+{
+    attr->stacksize = stacksize;
+    return APR_SUCCESS;
+}
+
 static void *dummy_worker(void *opaque)
 {
     apr_thread_t *thd = (apr_thread_t *)opaque;
@@ -128,13 +138,15 @@
      * same size as the calling thread. 
      */
 #ifndef _WIN32_WCE
-    if (((*new)->td = (HANDLE)_beginthreadex(NULL, 0, 
+    if (((*new)->td = (HANDLE)_beginthreadex(NULL,
+                        attr && attr->stacksize > 0 ? attr->stacksize : 0,
                         (unsigned int (APR_THREAD_FUNC *)(void *))dummy_worker,
                         (*new), 0, &temp)) == 0) {
         return APR_FROM_OS_ERROR(_doserrno);
     }
 #else
-   if (((*new)->td = CreateThread(NULL, 0, 
+   if (((*new)->td = CreateThread(NULL,
+                        attr && attr->stacksize > 0 ? attr->stacksize : 0,
                         (unsigned int (APR_THREAD_FUNC *)(void *))dummy_worker,
                         (*new), 0, &temp)) == 0) {
         return apr_get_os_error();
Index: srclib/apr-util/Makefile.in
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/Makefile.in,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr-util/Makefile.in	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/Makefile.in	23 May 2005 20:18:54 -0000	1.2
@@ -100,7 +100,7 @@
 	$(AWK) -f @APR_SOURCE_DIR@/build/make_var_export.awk $(EXPORT_FILES) > $@
 
 aprutil.exp: exports.c export_vars.h
-	@echo "#! libaprutil.so" > $@
+	@echo "#! lib@APRUTIL_LIBNAME@.so" > $@
 	@echo "* This file was AUTOGENERATED at build time." >> $@
 	@echo "* Please do not edit by hand." >> $@
 	$(CPP) $(ALL_CPPFLAGS) $(ALL_INCLUDES) exports.c | grep "ap_hack_" | sed -e 's/^.*[)]\(.*\);$$/\1/' >> $@
Index: srclib/apr-util/buckets/apr_buckets_file.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/buckets/apr_buckets_file.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr-util/buckets/apr_buckets_file.c	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/buckets/apr_buckets_file.c	10 Apr 2006 19:39:58 -0000	1.2
@@ -171,7 +171,7 @@
     apr_bucket_heap_make(e, buf, *len, apr_bucket_free);
 
     /* If we have more to read from the file, then create another bucket */
-    if (filelength > 0) {
+    if (filelength > 0 && rv != APR_EOF) {
         /* for efficiency, we can just build a new apr_bucket struct
          * to wrap around the existing file bucket */
         b = apr_bucket_alloc(sizeof(*b), e->list);
@@ -188,7 +188,7 @@
     }
 
     *str = buf;
-    return APR_SUCCESS;
+    return rv;
 }
 
 APU_DECLARE(apr_bucket *) apr_bucket_file_make(apr_bucket *b, apr_file_t *fd,
Index: srclib/apr-util/buckets/apr_buckets_pipe.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/buckets/apr_buckets_pipe.c,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- srclib/apr-util/buckets/apr_buckets_pipe.c	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/buckets/apr_buckets_pipe.c	5 Oct 2003 12:51:39 -0000	1.3
@@ -107,7 +107,11 @@
         a = apr_bucket_immortal_make(a, "", 0);
         *str = a->data;
         if (rv == APR_EOF) {
-            apr_file_close(p);
+            apr_int32_t flags = apr_file_flags_get(p);
+            
+            if (!(flags & IHS_FILE_NO_BUCKET_CLOSE_AT_EOF)) {
+                apr_file_close(p);
+            }
         }
     }
     return APR_SUCCESS;
Index: srclib/apr-util/build/apu-hints.m4
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/build/apu-hints.m4,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr-util/build/apu-hints.m4	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/build/apu-hints.m4	8 Jan 2004 11:06:49 -0000	1.2
@@ -24,7 +24,7 @@
     *-hp-hpux11.*)
         APR_SETIFNULL(apu_crypt_threadsafe, [1])
         ;;
-    *-ibm-aix*)
+    *-ibm-aix4*|*-ibm-aix5.1*)
         APR_SETIFNULL(apu_iconv_inbuf_const, [1])
         ;;
     *-ibm-os390)
Index: srclib/apr-util/crypto/apr_md5.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/crypto/apr_md5.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr-util/crypto/apr_md5.c	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/crypto/apr_md5.c	7 Jun 2005 10:27:47 -0000	1.2
@@ -97,6 +97,7 @@
  */
 #include "apr_strings.h"
 #include "apr_md5.h"
+#include "apr_sha1.h" /* needed by apr_password_validate */
 #include "apr_lib.h"
 #include "apu_config.h"
 
@@ -721,6 +722,9 @@
          * The hash was created using our custom algorithm.
          */
         apr_md5_encode(passwd, hash, sample, sizeof(sample));
+    }
+    else if (!strncmp(hash, APR_SHA1PW_ID, APR_SHA1PW_IDLEN)) {
+        apr_sha1_base64(passwd, strlen(passwd), sample);
     }
     else {
         /*
Index: srclib/apr-util/include/apr_optional.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/include/apr_optional.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr-util/include/apr_optional.h	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/include/apr_optional.h	7 Mar 2005 14:41:57 -0000	1.2
@@ -102,6 +102,7 @@
 /** @internal deprecated function, see apr_dynamic_fn_register */
 APU_DECLARE_NONSTD(void) apr_register_optional_fn(const char *szName, 
                                                   apr_opt_fn_t *pfn);
+#define APR_OPTIONAL_FN_TYPE(name) apr_OFN_##name##_t
 
 /**
  * Register an optional function. This can be later retrieved, type-safely, by
@@ -109,9 +110,10 @@
  * confusingly but correctly, the function itself can be static!
  * @param name The name of the function
  */
-#define APR_REGISTER_OPTIONAL_FN(name) \
-    (((void (*)(const char *, APR_OPTIONAL_FN_TYPE(name) *)) \
-               &apr_dynamic_fn_register)(#name,name))
+#define APR_REGISTER_OPTIONAL_FN(name) do { \
+  APR_OPTIONAL_FN_TYPE(name) *apu__opt = name; \
+  apr_dynamic_fn_register(#name,(apr_opt_fn_t *)apu__opt); \
+} while (0)
 
 /** @internal
  * Private function! DO NOT USE! 
Index: srclib/apr-util/include/apr_optional_hooks.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/include/apr_optional_hooks.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr-util/include/apr_optional_hooks.h	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/include/apr_optional_hooks.h	7 Mar 2005 14:41:57 -0000	1.2
@@ -99,10 +99,10 @@
  * @param nOrder an integer determining order before honouring aszPre and aszSucc (for example HOOK_MIDDLE)
  */
 
-#define APR_OPTIONAL_HOOK(ns,name,pfn,aszPre,aszSucc,nOrder) \
-    ((void (APR_THREAD_FUNC *)(const char *,ns##_HOOK_##name##_t *,const char * const *, \
-	       const char * const *,int))&apr_optional_hook_add)(#name,pfn,aszPre, \
-							   aszSucc, nOrder)
+#define APR_OPTIONAL_HOOK(ns,name,pfn,aszPre,aszSucc,nOrder) do { \
+  ns##_HOOK_##name##_t *apu__hook = pfn; \
+  apr_optional_hook_add(#name,(void (*)(void))apu__hook,aszPre, aszSucc, nOrder); \
+} while (0)
 
 /**
  * @internal
Index: srclib/apr-util/include/apr_sdbm.h
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/include/apr_sdbm.h,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr-util/include/apr_sdbm.h	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/include/apr_sdbm.h	11 Apr 2006 15:51:11 -0000	1.2
@@ -88,7 +88,7 @@
     /** pointer to the data stored/retrieved */
     char *dptr;
     /** size of data */
-    int dsize;
+    apr_size_t dsize;
 } apr_sdbm_datum_t;
 
 /* The extensions used for the database files */
Index: srclib/apr-util/include/apu.hw
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/include/apu.hw,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr-util/include/apu.hw	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/include/apu.hw	29 Jul 2003 21:22:19 -0000	1.2
@@ -154,7 +154,7 @@
 #endif
 #endif
 
-#define APU_HAVE_APR_ICONV     1
+#define APU_HAVE_APR_ICONV     0
 #define APU_HAVE_ICONV         0
 #define APR_HAS_XLATE          (APU_HAVE_APR_ICONV || APU_HAVE_ICONV)
 
Index: srclib/apr-util/misc/apr_rmm.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/misc/apr_rmm.c,v
retrieving revision 1.1.1.1
retrieving revision 1.6
diff -u -u -r1.1.1.1 -r1.6
--- srclib/apr-util/misc/apr_rmm.c	29 Jul 2003 20:19:30 -0000	1.1.1.1
+++ srclib/apr-util/misc/apr_rmm.c	7 Mar 2006 13:02:35 -0000	1.6
@@ -72,6 +72,9 @@
     apr_rmm_off_t /* rmm_block_t */ firstfree;
 } rmm_hdr_block_t;
 
+#define RMM_HDR_BLOCK_SIZE (APR_ALIGN_DEFAULT(sizeof(rmm_hdr_block_t)))
+#define RMM_BLOCK_SIZE (APR_ALIGN_DEFAULT(sizeof(rmm_block_t)))
+
 struct apr_rmm_t {
     apr_pool_t *p;
     rmm_hdr_block_t *base;
@@ -126,7 +129,7 @@
         next = blk->next;
     }
 
-    if (bestsize - size > sizeof(struct rmm_block_t*)) {
+    if (bestsize > RMM_BLOCK_SIZE + size) {
         struct rmm_block_t *blk = (rmm_block_t*)((char*)rmm->base + best);
         struct rmm_block_t *new = (rmm_block_t*)((char*)rmm->base + best + size);
 
@@ -138,16 +141,12 @@
         blk->next = best + size;
 
         if (new->next) {
-            blk = (rmm_block_t*)((char*)rmm->base + blk->next);
+            blk = (rmm_block_t*)((char*)rmm->base + new->next);
             blk->prev = best + size;
         }
     }
 
-    if (best) {
-        return best;
-    }
-     
-    return 0;
+    return best;
 }
 
 static void move_block(apr_rmm_t *rmm, apr_rmm_off_t this, int free)
@@ -244,7 +243,7 @@
 
     (*rmm)->base->abssize = size;
     (*rmm)->base->firstused = 0;
-    (*rmm)->base->firstfree = sizeof(rmm_hdr_block_t);
+    (*rmm)->base->firstfree = RMM_HDR_BLOCK_SIZE;
 
     blk = (rmm_block_t *)((char*)base + (*rmm)->base->firstfree);
 
@@ -252,8 +251,7 @@
     blk->prev = 0;
     blk->next = 0;
 
-    APR_ANYLOCK_UNLOCK(lock);
-    return APR_SUCCESS;
+    return APR_ANYLOCK_UNLOCK(lock);
 }
 
 APU_DECLARE(apr_status_t) apr_rmm_destroy(apr_rmm_t *rmm)
@@ -286,8 +284,7 @@
     rmm->base->abssize = 0;
     rmm->size = 0;
 
-    APR_ANYLOCK_UNLOCK(&rmm->lock);
-    return APR_SUCCESS;
+    return APR_ANYLOCK_UNLOCK(&rmm->lock);
 }
 
 APU_DECLARE(apr_status_t) apr_rmm_attach(apr_rmm_t **rmm, apr_anylock_t *lock,
@@ -320,15 +317,15 @@
 {
     apr_rmm_off_t this;
     
-    reqsize = APR_ALIGN_DEFAULT(reqsize);
+    reqsize = APR_ALIGN_DEFAULT(reqsize) + RMM_BLOCK_SIZE;
 
     APR_ANYLOCK_LOCK(&rmm->lock);
 
-    this = find_block_of_size(rmm, reqsize + sizeof(rmm_block_t));
+    this = find_block_of_size(rmm, reqsize);
 
     if (this) {
         move_block(rmm, this, 0);
-        this += sizeof(rmm_block_t);
+        this += RMM_BLOCK_SIZE;
     }
 
     APR_ANYLOCK_UNLOCK(&rmm->lock);
@@ -339,16 +336,16 @@
 {
     apr_rmm_off_t this;
         
-    reqsize = APR_ALIGN_DEFAULT(reqsize);
+    reqsize = APR_ALIGN_DEFAULT(reqsize) + RMM_BLOCK_SIZE;
 
     APR_ANYLOCK_LOCK(&rmm->lock);
 
-    this = find_block_of_size(rmm, reqsize + sizeof(rmm_block_t));
+    this = find_block_of_size(rmm, reqsize);
 
     if (this) {
         move_block(rmm, this, 0);
-        this += sizeof(rmm_block_t);
-        memset((char*)rmm->base + this, 0, reqsize);
+        this += RMM_BLOCK_SIZE;
+        memset((char*)rmm->base + this, 0, reqsize - RMM_BLOCK_SIZE);
     }
 
     APR_ANYLOCK_UNLOCK(&rmm->lock);
@@ -360,6 +357,8 @@
 {
     apr_rmm_off_t this;
     apr_rmm_off_t old;
+    struct rmm_block_t *blk;
+    apr_size_t oldsize;
 
     if (!entity) {
         return apr_rmm_malloc(rmm, reqsize);
@@ -369,11 +368,14 @@
     old = apr_rmm_offset_get(rmm, entity);
 
     if ((this = apr_rmm_malloc(rmm, reqsize)) == 0) {
-        return this;
+        return 0;
     }
 
+    blk = (rmm_block_t*)((char*)rmm->base + old - RMM_BLOCK_SIZE);
+    oldsize = blk->size;
+
     memcpy(apr_rmm_addr_get(rmm, this),
-           apr_rmm_addr_get(rmm, old), reqsize);
+           apr_rmm_addr_get(rmm, old), oldsize < reqsize ? oldsize : reqsize);
     apr_rmm_free(rmm, old);
 
     return this;
@@ -387,11 +389,11 @@
     /* A little sanity check is always healthy, especially here.
      * If we really cared, we could make this compile-time
      */
-    if (this < sizeof(rmm_hdr_block_t) + sizeof(rmm_block_t)) {
+    if (this < RMM_HDR_BLOCK_SIZE + RMM_BLOCK_SIZE) {
         return APR_EINVAL;
     }
 
-    this -= sizeof(rmm_block_t);
+    this -= RMM_BLOCK_SIZE;
 
     blk = (rmm_block_t*)((char*)rmm->base + this);
 
@@ -424,8 +426,7 @@
      */
     move_block(rmm, this, 1);
     
-    APR_ANYLOCK_UNLOCK(&rmm->lock);
-    return APR_SUCCESS;
+    return APR_ANYLOCK_UNLOCK(&rmm->lock);
 }
 
 APU_DECLARE(void *) apr_rmm_addr_get(apr_rmm_t *rmm, apr_rmm_off_t entity) 
@@ -447,5 +448,8 @@
 
 APU_DECLARE(apr_size_t) apr_rmm_overhead_get(int n) 
 {
-    return sizeof(rmm_hdr_block_t) + n * sizeof(rmm_block_t);
+    /* overhead per block is at most APR_ALIGN_DEFAULT(1) wasted bytes
+     * for alignment overhead, plus the size of the rmm_block_t
+     * structure. */
+    return RMM_HDR_BLOCK_SIZE + n * (RMM_BLOCK_SIZE + APR_ALIGN_DEFAULT(1));
 }
Index: srclib/apr-util/uri/apr_uri.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/apr-util/uri/apr_uri.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/apr-util/uri/apr_uri.c	29 Jul 2003 20:19:31 -0000	1.1.1.1
+++ srclib/apr-util/uri/apr_uri.c	14 Aug 2004 11:38:00 -0000	1.2
@@ -346,12 +346,12 @@
         if (*hostinfo == '[') {
             v6_offset1 = 1;
             v6_offset2 = 2;
-            s = uri;
-            do {
-                --s;
-            } while (s >= hostinfo && *s != ':' && *s != ']');
-            if (s < hostinfo || *s == ']') {
-                s = NULL; /* no port */
+            s = memchr(hostinfo, ']', uri - hostinfo);
+            if (s == NULL) {
+                return APR_EGENERAL;
+            }
+            if (*++s != ':') {
+                s = NULL; /* no port segment after [...] */
             }
         }
         else {
Index: srclib/pcre/pcre.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/srclib/pcre/pcre.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- srclib/pcre/pcre.c	29 Jul 2003 20:19:28 -0000	1.1.1.1
+++ srclib/pcre/pcre.c	14 Sep 2005 18:12:50 -0000	1.2
@@ -714,7 +714,18 @@
 int min = 0;
 int max = -1;
 
+/* Read the minimum value and do a paranoid check: a negative value indicates
+an integer overflow. */
+
 while ((cd->ctypes[*p] & ctype_digit) != 0) min = min * 10 + *p++ - '0';
+if (min < 0 || min > 65535)
+  {
+  *errorptr = ERR5;
+  return p;
+  }
+
+/* Read the maximum value if there is one, and again do a paranoid on its size.
+Also, max must not be less than min. */
 
 if (*p == '}') max = min; else
   {
@@ -722,6 +733,11 @@
     {
     max = 0;
     while((cd->ctypes[*p] & ctype_digit) != 0) max = max * 10 + *p++ - '0';
+    if (max < 0 || max > 65535)
+      {
+      *errorptr = ERR5;
+      return p;
+      }
     if (max < min)
       {
       *errorptr = ERR4;
@@ -730,16 +746,11 @@
     }
   }
 
-/* Do paranoid checks, then fill in the required variables, and pass back the
-pointer to the terminating '}'. */
+/* Fill in the required variables, and pass back the pointer to the terminating
+'}'. */
 
-if (min > 65535 || max > 65535)
-  *errorptr = ERR5;
-else
-  {
   *minp = min;
   *maxp = max;
-  }
 return p;
 }
 
Index: support/Makefile.in
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/support/Makefile.in,v
retrieving revision 1.1.1.1
retrieving revision 1.3
diff -u -u -r1.1.1.1 -r1.3
--- support/Makefile.in	29 Jul 2003 20:19:31 -0000	1.1.1.1
+++ support/Makefile.in	5 Nov 2003 03:00:54 -0000	1.3
@@ -16,6 +16,7 @@
 	@test -d $(DESTDIR)$(sbindir) || $(MKINSTALLDIRS) $(DESTDIR)$(sbindir)
 	@test -d $(DESTDIR)$(libexecdir) || $(MKINSTALLDIRS) $(DESTDIR)$(libexecdir)
 	@cp -p $(top_builddir)/server/httpd.exp $(DESTDIR)$(libexecdir)
+	@cp -p updateinstallpath $(DESTDIR)$(bindir)
 	@for i in apxs apachectl dbmmanage; do \
 	    if test -f "$(builddir)/$$i"; then \
 	        cp -p $$i $(DESTDIR)$(sbindir); \
Index: support/ab.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/support/ab.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- support/ab.c	29 Jul 2003 20:19:31 -0000	1.1.1.1
+++ support/ab.c	1 Aug 2003 11:01:09 -0000	1.4
@@ -227,8 +227,11 @@
 
 /* good old state hostname */
 #define STATE_UNCONNECTED 0
-#define STATE_CONNECTING  1
-#define STATE_READ        2
+#define STATE_CONNECTING  1     /* TCP connect initiated, but we don't
+                                 * know if it worked yet
+                                 */
+#define STATE_CONNECTED   2     /* we know TCP connect completed */
+#define STATE_READ        3
 
 #define CBUFFSIZE (2048)
 
@@ -668,7 +671,7 @@
             case SSL_ERROR_WANT_CONNECT:
                 BIO_printf(bio_err, "Waiting .. sleep(1)\n");
                 apr_sleep(apr_time_from_sec(1));
-                c->state = STATE_CONNECTING;
+                c->state = STATE_CONNECTED;
                 c->rwrite = 0;
                 break;
             case SSL_ERROR_ZERO_RETURN:
@@ -770,6 +773,7 @@
 
 #ifdef USE_SSL
         if (ssl != 1)
+#endif
 	if (e != APR_SUCCESS) {
 	    /*
 	     * Let's hope this traps EWOULDBLOCK too !
@@ -781,7 +785,6 @@
 	    }
 	    return;
 	}
-#endif
 	c->rwrote += l;
 	c->rwrite -= l;
     } while (1);
@@ -1256,7 +1259,7 @@
 	    c->state = STATE_CONNECTING;
 	    c->rwrite = 0;
             new_pollfd.desc_type = APR_POLL_SOCKET;
-            new_pollfd.reqevents = APR_POLLIN;
+            new_pollfd.reqevents = APR_POLLOUT;
             new_pollfd.desc.s = c->aprsock;
             new_pollfd.client_data = c;
 	    apr_pollset_add(readbits, &new_pollfd);
@@ -1281,6 +1284,7 @@
     }
 
     /* connected first time */
+    c->state = STATE_CONNECTED;
     started++;
     write_request(c);
 }
@@ -1729,8 +1733,34 @@
 		start_connect(c);
 		continue;
 	    }
-	    if (rv & APR_POLLOUT)
-		write_request(c);
+	    if (rv & APR_POLLOUT) {
+                if (c->state == STATE_CONNECTING) {
+                    apr_pollfd_t remove_pollfd;
+                    rv = apr_connect(c->aprsock, destsa);
+                    remove_pollfd.desc_type = APR_POLL_SOCKET;
+                    remove_pollfd.desc.s = c->aprsock;
+                    apr_pollset_remove(readbits, &remove_pollfd);
+                    if (rv != APR_SUCCESS) {
+                        apr_socket_close(c->aprsock);
+                        err_conn++;
+                        if (bad++ > 10) {
+                            fprintf(stderr,
+                                    "\nTest aborted after 10 failures\n\n");
+                            apr_err("apr_connect()", rv);
+                        }
+                        c->state = STATE_UNCONNECTED;
+                        start_connect(c);
+                        continue;
+                    }
+                    else {
+                        c->state = STATE_CONNECTED;
+                        write_request(c);
+                    }
+                }
+                else {
+                    write_request(c);
+                }
+            }
 
 	    /*
 	     * When using a select based poll every time we check the bits
@@ -1742,8 +1772,7 @@
 #ifdef USE_SSL
             if (ssl != 1)
 #endif
-	    if (c->state == STATE_READ ||
-                c->state == STATE_CONNECTING) {
+                if (c->state == STATE_READ) {
                     apr_pollfd_t new_pollfd;
                     new_pollfd.desc_type = APR_POLL_SOCKET;
                     new_pollfd.reqevents = APR_POLLIN;
@@ -1771,14 +1800,14 @@
 static void copyright(void)
 {
     if (!use_html) {
-	printf("This is ApacheBench, Version %s\n", AP_AB_BASEREVISION " <$Revision: 1.1.1.1 $> apache-2.0");
+	printf("This is ApacheBench, Version %s\n", AP_AB_BASEREVISION " <$Revision: 1.4 $> apache-2.0");
 	printf("Copyright (c) 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/\n");
 	printf("Copyright (c) 1998-2002 The Apache Software Foundation, http://www.apache.org/\n");
 	printf("\n");
     }
     else {
 	printf("<p>\n");
-	printf(" This is ApacheBench, Version %s <i>&lt;%s&gt;</i> apache-2.0<br>\n", AP_AB_BASEREVISION, "$Revision: 1.1.1.1 $");
+	printf(" This is ApacheBench, Version %s <i>&lt;%s&gt;</i> apache-2.0<br>\n", AP_AB_BASEREVISION, "$Revision: 1.4 $");
 	printf(" Copyright (c) 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/<br>\n");
 	printf(" Copyright (c) 1998-2002 The Apache Software Foundation, http://www.apache.org/<br>\n");
 	printf("</p>\n<p>\n");
Index: support/htdbm.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/support/htdbm.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- support/htdbm.c	29 Jul 2003 20:19:31 -0000	1.1.1.1
+++ support/htdbm.c	11 Apr 2006 21:21:20 -0000	1.2
@@ -90,6 +90,9 @@
 #include "apr_xlate.h"
 #endif /*APR_CHARSET_EBCDIC*/
 
+#if APR_HAVE_UNISTD_H
+#include <unistd.h>
+#endif
 #if APR_HAVE_CRYPT_H
 #include <crypt.h>
 #endif
Index: support/rotatelogs.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/support/rotatelogs.c,v
retrieving revision 1.1.1.1
retrieving revision 1.4
diff -u -u -r1.1.1.1 -r1.4
--- support/rotatelogs.c	29 Jul 2003 20:19:31 -0000	1.1.1.1
+++ support/rotatelogs.c	16 Jun 2004 21:30:45 -0000	1.4
@@ -62,6 +62,13 @@
  * Ported to APR by Mladen Turk <mturk@mappingsoft.com>
  *
  * 23 Sep 2001
+ *
+ * -l option added by Ken Coar <coar@apache.org>
+ *
+ * -l causes the use of local time rather than GMT as the base for the
+ * interval.  NB: Using -l in an environment which changes the GMT offset
+ * (such as for BST or DST) can lead to unpredictable results!
+ *
  */
 
 
@@ -99,19 +106,31 @@
     int nMessCount = 0;
     apr_size_t nRead, nWrite;
     int use_strftime = 0;
+    int use_localtime = 0;
     int now = 0;
     const char *szLogRoot;
     apr_file_t *f_stdin, *nLogFD = NULL, *nLogFDprev = NULL;
     apr_pool_t *pool;
     char *ptr = NULL;
+    int argBase = 0;
+    int argFile = 1;
+    int argIntv = 2;
+    int argOffset = 3;
 
     apr_app_initialize(&argc, &argv, NULL);
     atexit(apr_terminate);
 
     apr_pool_create(&pool, NULL);
-    if (argc < 3 || argc > 4) {
+    if ((argc > 2) && (strcmp(argv[1], "-l") == 0)) {
+        argBase++;
+        argFile += argBase;
+        argIntv += argBase;
+        argOffset += argBase;
+        use_localtime = 1;
+    }
+    if (argc < (argBase + 3) || argc > (argBase + 4)) {
         fprintf(stderr,
-                "Usage: %s <logfile> <rotation time in seconds> "
+                "Usage: %s [-l] <logfile> <rotation time in seconds> "
                 "[offset minutes from UTC] or <rotation size in megabytes>\n\n",
                 argv[0]);
 #ifdef OS2
@@ -135,12 +154,12 @@
         exit(1);
     }
 
-    szLogRoot = argv[1];
+    szLogRoot = argv[argFile];
 
-    ptr = strchr (argv[2], 'M');
+    ptr = strchr(argv[argIntv], 'M');
     if (ptr) {
         if (*(ptr+1) == '\0') {
-            sRotation = atoi(argv[2]) * 1048576;
+            sRotation = atoi(argv[argIntv]) * 1048576;
         }
         if (sRotation == 0) {
             fprintf(stderr, "Invalid rotation size parameter\n");
@@ -148,10 +167,10 @@
         }
     }
     else {
-        if (argc >= 4) {
-            utc_offset = atoi(argv[3]) * 60;
+        if (argc >= (argBase + 4)) {
+            utc_offset = atoi(argv[argOffset]) * 60;
         }
-        tRotation = atoi(argv[2]);
+        tRotation = atoi(argv[argIntv]);
         if (tRotation <= 0) {
             fprintf(stderr, "Rotation time must be > 0\n");
             exit(6);
@@ -166,9 +185,20 @@
 
     for (;;) {
         nRead = sizeof(buf);
-        if (apr_file_read(f_stdin, buf, &nRead) != APR_SUCCESS)
+        if (apr_file_read(f_stdin, buf, &nRead) != APR_SUCCESS) {
             exit(3);
+        }
         if (tRotation) {
+            /*
+             * Check for our UTC offset every time through the loop, since
+             * it might change if there's a switch between standard and
+             * daylight savings time.
+             */
+            if (use_localtime) {
+                apr_time_exp_t lt;
+                apr_time_exp_lt(&lt, apr_time_now());
+                utc_offset = lt.tm_gmtoff;
+            }
             now = (int)(apr_time_now() / APR_USEC_PER_SEC) + utc_offset;
             if (nLogFD != NULL && now >= tLogEnd) {
                 nLogFDprev = nLogFD;
@@ -197,10 +227,12 @@
         if (nLogFD == NULL) {
             int tLogStart;
                 
-            if (tRotation)
+            if (tRotation) {
                 tLogStart = (now / tRotation) * tRotation;
-            else
+            }
+            else {
                 tLogStart = (int)apr_time_sec(apr_time_now());
+            }
 
             if (use_strftime) {
                 apr_time_t tNow = apr_time_from_sec(tLogStart);
Index: support/suexec.c
===================================================================
RCS file: /m0xa/cvs/phoenix/2.0.47/support/suexec.c,v
retrieving revision 1.1.1.1
retrieving revision 1.2
diff -u -u -r1.1.1.1 -r1.2
--- support/suexec.c	29 Jul 2003 20:19:31 -0000	1.1.1.1
+++ support/suexec.c	26 May 2005 19:01:08 -0000	1.2
@@ -159,6 +159,7 @@
     "REMOTE_PORT=",
     "REMOTE_USER=",
     "REDIRECT_QUERY_STRING=",
+    "REDIRECT_REMOTE_USER=",
     "REDIRECT_STATUS=",
     "REDIRECT_URL=",
     "REQUEST_METHOD=",
Index: srclib/apr/network_io/unix/aprsockapi.c
===================================================================
/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

#include "apr_arch_networkio.h"
#include "apr_network_io.h"
#include "apr_portable.h"
#include "apr_strings.h"
#include "apr_arch_inherit.h"

/*
 * This file contains the common entry point, on all OSes, into APR for 
 * each apr_socket_* call
 */

/* Forward declarations for the native APR socket API. */
APR_DECLARE(apr_status_t)  uapr_shutdown(apr_socket_t *sock, apr_shutdown_how_e how);
APR_DECLARE(apr_status_t)  uapr_socket_shutdown(apr_socket_t *sock, apr_shutdown_how_e how);
APR_DECLARE(apr_status_t)  uapr_socket_close(apr_socket_t *sock);
APR_DECLARE(apr_status_t)  uapr_bind(apr_socket_t *sock, apr_sockaddr_t *sa);
APR_DECLARE(apr_status_t)  uapr_socket_bind(apr_socket_t *sock, apr_sockaddr_t *sa);
APR_DECLARE(apr_status_t)  uapr_listen(apr_socket_t *sock, apr_int32_t backlog);
APR_DECLARE(apr_status_t)  uapr_socket_listen(apr_socket_t *sock, apr_int32_t backlog);
APR_DECLARE(apr_status_t)  uapr_accept(apr_socket_t **new_sock, apr_socket_t *sock, apr_pool_t *p);
APR_DECLARE(apr_status_t)  uapr_socket_accept(apr_socket_t **new_sock, apr_socket_t *sock, apr_pool_t *p);
APR_DECLARE(apr_status_t)  uapr_connect(apr_socket_t *sock, apr_sockaddr_t *sa);
APR_DECLARE(apr_status_t)  uapr_socket_connect(apr_socket_t *sock, apr_sockaddr_t *sa);
APR_DECLARE(apr_status_t)  uapr_socket_data_get(void **data, const char *key,
                                                apr_socket_t *sock);
APR_DECLARE(apr_status_t)  uapr_socket_data_set(apr_socket_t *sock, void *data,
                                                const char *key,
                                                apr_status_t (*cleanup)(void*));
APR_DECLARE(apr_status_t)  uapr_send(apr_socket_t *sock, const char *buf, apr_size_t *len);
APR_DECLARE(apr_status_t)  uapr_socket_send(apr_socket_t *sock, const char *buf, apr_size_t *len);
APR_DECLARE(apr_status_t)  uapr_sendv(apr_socket_t *sock, const struct iovec *vec,
                                      apr_int32_t nvec, apr_size_t *len);
APR_DECLARE(apr_status_t)  uapr_socket_sendv(apr_socket_t *sock, 
                                             const struct iovec *vec,
                                             apr_int32_t nvec, apr_size_t *len);
APR_DECLARE(apr_status_t)  uapr_sendto(apr_socket_t *sock, apr_sockaddr_t *where,
                                       apr_int32_t flags, const char *buf, 
                                       apr_size_t *len);
APR_DECLARE(apr_status_t)  uapr_socket_sendto(apr_socket_t *sock, apr_sockaddr_t *where,
                                              apr_int32_t flags, const char *buf, 
                                              apr_size_t *len);
APR_DECLARE(apr_status_t)  uapr_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock,
                                         apr_int32_t flags, char *buf, 
                                         apr_size_t *len);
APR_DECLARE(apr_status_t)  uapr_socket_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock,
                                                apr_int32_t flags, char *buf, 
                                                apr_size_t *len);
#if APR_HAS_SENDFILE
APR_DECLARE(apr_status_t)  uapr_sendfile(apr_socket_t *sock, apr_file_t *file,
                                         apr_hdtr_t *hdtr, apr_off_t *offset,
                                         apr_size_t *len, apr_int32_t flags);
APR_DECLARE(apr_status_t)  uapr_socket_sendfile(apr_socket_t *sock, apr_file_t *file,
                                                apr_hdtr_t *hdtr, apr_off_t *offset,
                                                apr_size_t *len, apr_int32_t flags);
#endif /* APR_HAS_SENDFILE */
APR_DECLARE(apr_status_t)  uapr_recv(apr_socket_t *sock, char *buf, apr_size_t *len);
APR_DECLARE(apr_status_t)  uapr_socket_recv(apr_socket_t *sock, char *buf, apr_size_t *len);
APR_DECLARE(apr_status_t)  uapr_setsocketopt(apr_socket_t *sock, apr_int32_t opt, apr_int32_t on);
APR_DECLARE(apr_status_t)  uapr_getsocketopt(apr_socket_t *sock, apr_int32_t opt, apr_int32_t *on);
APR_DECLARE(apr_status_t)  uapr_socket_opt_set(apr_socket_t *sock, apr_int32_t opt, apr_int32_t on);
APR_DECLARE(apr_status_t)  uapr_socket_opt_get(apr_socket_t *sock, apr_int32_t opt, apr_int32_t *on);
APR_DECLARE(apr_status_t)  uapr_socket_timeout_set(apr_socket_t *sock, apr_interval_time_t t);
APR_DECLARE(apr_status_t)  uapr_socket_timeout_get(apr_socket_t *sock, apr_interval_time_t *t);
APR_DECLARE(apr_status_t)  uapr_socket_addr_get(apr_sockaddr_t **sa, apr_interface_e which,
                                                apr_socket_t *sock);
#if APR_HAS_SO_ACCEPTFILTER
APR_DECLARE(apr_status_t)  uapr_socket_accept_filter(apr_socket_t *sock, char *name, char *args);
#endif
void socket_set_inherit(apr_socket_t *sock);
void socket_unset_inherit(apr_socket_t *sock);

/* The APR IOL (rarely used) can't reference the uapr_ routines directly
 * because those routines have external API linkage.  These shims are
 * referenced from the APR IOL.
 */

static apr_status_t call_shutdown(apr_socket_t *sock, apr_shutdown_how_e how)
{
    return uapr_socket_shutdown(sock, how);
}

static apr_status_t call_socket_close(apr_socket_t *sock)
{
    return uapr_socket_close(sock);
}

static apr_status_t call_bind(apr_socket_t *sock, apr_sockaddr_t *sa)
{
    return uapr_socket_bind(sock, sa);
}

static apr_status_t call_listen(apr_socket_t *sock, apr_int32_t backlog)
{
    return uapr_socket_listen(sock, backlog);
}

static apr_status_t call_accept(apr_socket_t **new_sock, apr_socket_t *sock,
                                apr_pool_t *p)
{
    return uapr_socket_accept(new_sock, sock, p);
}

static apr_status_t call_connect(apr_socket_t *sock, apr_sockaddr_t *sa)
{
    return uapr_socket_connect(sock, sa);
}

static apr_status_t call_socket_data_get(void **data, const char *key,
                                         apr_socket_t *sock)
{
    return uapr_socket_data_get(data, key, sock);
}

static apr_status_t call_socket_data_set(apr_socket_t *sock, void *data,
                                         const char *key,
                                         apr_status_t (*cleanup)(void *))
{
    return uapr_socket_data_set(sock, data, key, cleanup);
}

static apr_status_t call_send(apr_socket_t *sock, const char *buf, apr_size_t *len)
{
    return uapr_socket_send(sock, buf, len);
}

static apr_status_t call_sendv(apr_socket_t *sock, const struct iovec *vec,
                               apr_int32_t nvec, apr_size_t *len)
{
    return uapr_socket_sendv(sock, vec, nvec, len);
}

static apr_status_t call_sendto(apr_socket_t *sock, apr_sockaddr_t *where,
                                apr_int32_t flags, const char *buf,
                                apr_size_t *len)
{
    return uapr_socket_sendto(sock, where, flags, buf, len);
}

static apr_status_t call_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock,
                                  apr_int32_t flags, char *buf, apr_size_t *len)
{
    return uapr_socket_recvfrom(from, sock, flags, buf, len);
}

#if APR_HAS_SENDFILE
static apr_status_t call_sendfile(apr_socket_t *sock, apr_file_t *file,
                                  apr_hdtr_t *hdtr, apr_off_t *offset,
                                  apr_size_t *len, apr_int32_t flags)
{
    return uapr_socket_sendfile(sock, file, hdtr, offset, len, flags);
}
#endif

static apr_status_t call_recv(apr_socket_t *sock, char *buf, apr_size_t *len)
{
    return uapr_socket_recv(sock, buf, len);
}

/* Do we really need call_set/getsocketopt? */
static apr_status_t call_setsocketopt(apr_socket_t *sock, apr_int32_t opt,
                                      apr_int32_t on)
{
    return uapr_setsocketopt(sock, opt, on);
}

static apr_status_t call_getsocketopt(apr_socket_t *sock, apr_int32_t opt,
                                      apr_int32_t *on)
{
    return uapr_getsocketopt(sock, opt, on);
}

static apr_status_t call_socket_opt_set(apr_socket_t *sock, apr_int32_t opt,
                                        apr_int32_t on)
{
    return uapr_socket_opt_set(sock, opt, on);
}

static apr_status_t call_socket_opt_get(apr_socket_t *sock, apr_int32_t opt,
                                        apr_int32_t *on)
{
    return uapr_socket_opt_get(sock, opt, on);
}

static apr_status_t call_socket_timeout_set(apr_socket_t *sock, 
                                            apr_interval_time_t t)
{
    return uapr_socket_timeout_set(sock, t);
}

static apr_status_t call_socket_timeout_get(apr_socket_t *sock, 
                                            apr_interval_time_t *t)
{
    return uapr_socket_timeout_get(sock, t);
}

static apr_status_t call_socket_addr_get(apr_sockaddr_t **sa,
                                         apr_interface_e which,
                                         apr_socket_t *sock)
{
    return uapr_socket_addr_get(sa, which, sock);
}

static const apr_socket_iol_t apr_iol =
{
    0,
    "APR",
    call_shutdown,
    call_socket_close,
    call_bind,
    call_listen,
    call_accept,
    call_connect,
    call_socket_data_get,
    call_socket_data_set,
    call_send,
    call_sendv,
    call_sendto,
    call_recvfrom,
#if APR_HAS_SENDFILE
    call_sendfile,
#endif
    call_recv,
    call_setsocketopt,
    call_getsocketopt,
    call_socket_opt_set,
    call_socket_opt_get,
    call_socket_timeout_set,
    call_socket_timeout_get,
    call_socket_addr_get,
    0, /* what about this???  there is no uapr_socket_set_inherit, */
    0, /* what about this???  there is no uapr_socket_unset_inherit */
#if APR_HAS_SO_ACCEPTFILTER
    ,call_socket_accept_filter
#endif
};

/*
 * APR network API 
 */

APR_DECLARE(apr_status_t) apr_shutdown(apr_socket_t *sock,
                                       apr_shutdown_how_e how)
{
    if (!sock->iol || !sock->iol->iol_socket_shutdown) {
        return uapr_socket_shutdown(sock, how);
    }
    return sock->iol->iol_socket_shutdown(sock, how);
}

APR_DECLARE(apr_status_t) apr_socket_shutdown(apr_socket_t *sock,
                                              apr_shutdown_how_e how)
{
    if (!sock->iol || !sock->iol->iol_socket_shutdown) {
        return uapr_socket_shutdown(sock, how);
    }
    return sock->iol->iol_socket_shutdown(sock, how);
}

APR_DECLARE(apr_status_t) apr_socket_close(apr_socket_t *sock)
{
    if (!sock->iol || !sock->iol->iol_socket_close) {
        return uapr_socket_close(sock);
    }
    return sock->iol->iol_socket_close(sock);
}

APR_DECLARE(apr_status_t) apr_bind(apr_socket_t *sock, apr_sockaddr_t *sa)
{
    if (!sock->iol || !sock->iol->iol_socket_bind) {
        return uapr_socket_bind(sock, sa);
    }
    return sock->iol->iol_socket_bind(sock, sa);
}

APR_DECLARE(apr_status_t) apr_socket_bind(apr_socket_t *sock, apr_sockaddr_t *sa)
{
    if (!sock->iol || !sock->iol->iol_socket_bind) {
        return uapr_socket_bind(sock, sa);
    }
    return sock->iol->iol_socket_bind(sock, sa);
}

APR_DECLARE(apr_status_t) apr_listen(apr_socket_t *sock, apr_int32_t backlog)
{
    if (!sock->iol || !sock->iol->iol_socket_listen) {
        return uapr_socket_listen(sock, backlog);
    }
    return sock->iol->iol_socket_listen(sock, backlog);
}

APR_DECLARE(apr_status_t) apr_socket_listen(apr_socket_t *sock, apr_int32_t backlog)
{
    if (!sock->iol || !sock->iol->iol_socket_listen) {
        return uapr_socket_listen(sock, backlog);
    }
    return sock->iol->iol_socket_listen(sock, backlog);
}

APR_DECLARE(apr_status_t) apr_accept(apr_socket_t **new_sock, 
                                     apr_socket_t *sock,
                                     apr_pool_t *p)
{
    if (!sock->iol || !sock->iol->iol_socket_accept) {
        return uapr_socket_accept(new_sock, sock, p);
    }
    return sock->iol->iol_socket_accept(new_sock, sock, p);
}
APR_DECLARE(apr_status_t) apr_socket_accept(apr_socket_t **new_sock, 
                                            apr_socket_t *sock,
                                            apr_pool_t *p)
{
    if (!sock->iol || !sock->iol->iol_socket_accept) {
        return uapr_socket_accept(new_sock, sock, p);
    }
    return sock->iol->iol_socket_accept(new_sock, sock, p);
}
APR_DECLARE(apr_status_t) apr_connect(apr_socket_t *sock, apr_sockaddr_t *sa)
{
    if (!sock->iol || !sock->iol->iol_socket_connect) {
        return uapr_socket_connect(sock, sa);
    }
    return sock->iol->iol_socket_connect(sock, sa);
}

APR_DECLARE(apr_status_t) apr_socket_connect(apr_socket_t *sock, apr_sockaddr_t *sa)
{
    if (!sock->iol || !sock->iol->iol_socket_connect) {
        return uapr_socket_connect(sock, sa);
    }
    return sock->iol->iol_socket_connect(sock, sa);
}

APR_DECLARE(apr_status_t) apr_socket_data_get(void **data, const char *key,
                                             apr_socket_t *sock)
{
    if (!sock->iol || !sock->iol->iol_socket_data_get) {
        return uapr_socket_data_get(data, key, sock);
    }
    return sock->iol->iol_socket_data_get(data, key, sock);
}

APR_DECLARE(apr_status_t) apr_socket_data_set(apr_socket_t *sock, void *data,
                                             const char *key,
                                             apr_status_t (*cleanup)(void*))
{
    if (!sock->iol || !sock->iol->iol_socket_data_set) {
        return uapr_socket_data_set(sock, data, key, cleanup);
    }
    return sock->iol->iol_socket_data_set(sock, data, key, cleanup);
}

APR_DECLARE(apr_status_t) apr_send(apr_socket_t *sock, const char *buf, 
                                   apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_send) {
        return uapr_socket_send(sock, buf, len);
    }
    return sock->iol->iol_socket_send(sock, buf, len);
}

APR_DECLARE(apr_status_t) apr_socket_send(apr_socket_t *sock, const char *buf, 
                                          apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_send) {
        return uapr_socket_send(sock, buf, len);
    }
    return sock->iol->iol_socket_send(sock, buf, len);
}

APR_DECLARE(apr_status_t) apr_sendv(apr_socket_t *sock, 
                                    const struct iovec *vec,
                                    apr_int32_t nvec, apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_sendv) {
        return uapr_socket_sendv(sock, vec, nvec, len);
    }
    return sock->iol->iol_socket_sendv(sock, vec, nvec, len);
}
APR_DECLARE(apr_status_t) apr_socket_sendv(apr_socket_t *sock, 
                                    const struct iovec *vec,
                                    apr_int32_t nvec, apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_sendv) {
        return uapr_socket_sendv(sock, vec, nvec, len);
    }
    return sock->iol->iol_socket_sendv(sock, vec, nvec, len);
}

APR_DECLARE(apr_status_t) apr_sendto(apr_socket_t *sock, apr_sockaddr_t *where,
                                     apr_int32_t flags, const char *buf, 
                                     apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_sendto) {
        return uapr_socket_sendto(sock, where, flags, buf, len);
    }
    return sock->iol->iol_socket_sendto(sock, where, flags, buf, len);
}
APR_DECLARE(apr_status_t) apr_socket_sendto(apr_socket_t *sock, apr_sockaddr_t *where,
                                            apr_int32_t flags, const char *buf, 
                                            apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_sendto) {
        return uapr_socket_sendto(sock, where, flags, buf, len);
    }
    return sock->iol->iol_socket_sendto(sock, where, flags, buf, len);
}
APR_DECLARE(apr_status_t) apr_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock,
                                       apr_int32_t flags, char *buf, 
                                       apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_recvfrom) {
        return uapr_socket_recvfrom(from, sock, flags, buf, len);
    }
    return sock->iol->iol_socket_recvfrom(from, sock, flags, buf, len);
}
APR_DECLARE(apr_status_t) apr_socket_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock,
                                       apr_int32_t flags, char *buf, 
                                       apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_recvfrom) {
        return uapr_socket_recvfrom(from, sock, flags, buf, len);
    }
    return sock->iol->iol_socket_recvfrom(from, sock, flags, buf, len);
}
 
#if APR_HAS_SENDFILE
APR_DECLARE(apr_status_t) apr_sendfile(apr_socket_t *sock, apr_file_t *file,
                                       apr_hdtr_t *hdtr, apr_off_t *offset,
                                       apr_size_t *len, apr_int32_t flags)
{
    if (!sock->iol || !sock->iol->iol_socket_sendfile) {
        return uapr_socket_sendfile(sock, file, hdtr, offset, len, flags);
    }
    return sock->iol->iol_socket_sendfile(sock, file, hdtr, offset, len, flags);
}
APR_DECLARE(apr_status_t) apr_socket_sendfile(apr_socket_t *sock, apr_file_t *file,
                                              apr_hdtr_t *hdtr, apr_off_t *offset,
                                              apr_size_t *len, apr_int32_t flags)
{
    if (!sock->iol || !sock->iol->iol_socket_sendfile) {
        return uapr_socket_sendfile(sock, file, hdtr, offset, len, flags);
    }
    return sock->iol->iol_socket_sendfile(sock, file, hdtr, offset, len, flags);
}
#endif /* APR_HAS_SENDFILE */

APR_DECLARE(apr_status_t) apr_recv(apr_socket_t *sock, 
                                   char *buf, apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_recv) {
        return uapr_socket_recv(sock, buf, len);
    }
    return sock->iol->iol_socket_recv(sock, buf, len);
}
APR_DECLARE(apr_status_t) apr_socket_recv(apr_socket_t *sock, 
                                          char *buf, apr_size_t *len)
{
    if (!sock->iol || !sock->iol->iol_socket_recv) {
        return uapr_socket_recv(sock, buf, len);
    }
    return sock->iol->iol_socket_recv(sock, buf, len);
}

APR_DECLARE(apr_status_t) apr_setsocketopt(apr_socket_t *sock,
                                           apr_int32_t opt, apr_int32_t on)
{
    if (!sock->iol || !sock->iol->iol_socket_setsocketopt) {
        return uapr_setsocketopt(sock, opt, on);
    }
    return sock->iol->iol_socket_setsocketopt(sock, opt, on);
}
APR_DECLARE(apr_status_t) apr_getsocketopt(apr_socket_t *sock, 
                                           apr_int32_t opt, apr_int32_t *on)
{
    if (!sock->iol || !sock->iol->iol_socket_getsocketopt) {
        return uapr_getsocketopt(sock, opt, on);
    }
    return sock->iol->iol_socket_getsocketopt(sock, opt, on);
}

APR_DECLARE(apr_status_t) apr_socket_opt_set(apr_socket_t *sock,
                                             apr_int32_t opt, apr_int32_t on)
{
    if (!sock->iol || !sock->iol->iol_socket_opt_set) {
        return uapr_socket_opt_set(sock, opt, on);
    }
    return sock->iol->iol_socket_opt_set(sock, opt, on);
}

APR_DECLARE(apr_status_t) apr_socket_opt_get(apr_socket_t *sock, 
                                             apr_int32_t opt, apr_int32_t *on)
{
    if (!sock->iol || !sock->iol->iol_socket_opt_get) {
        return uapr_socket_opt_get(sock, opt, on);
    }
    return sock->iol->iol_socket_opt_get(sock, opt, on);
}

APR_DECLARE(apr_status_t) apr_socket_timeout_set(apr_socket_t *sock, apr_interval_time_t t)
{
    if (!sock->iol || !sock->iol->iol_socket_timeout_set) {
        return uapr_socket_timeout_set(sock, t);
    }
    return sock->iol->iol_socket_timeout_set(sock, t);
}

APR_DECLARE(apr_status_t) apr_socket_timeout_get(apr_socket_t *sock, apr_interval_time_t *t)
{
    if (!sock->iol || !sock->iol->iol_socket_timeout_get) {
        return uapr_socket_timeout_get(sock, t);
    }
    return sock->iol->iol_socket_timeout_get(sock, t);
}

/* XXX: Do we really need this function to be iol'ized */
APR_DECLARE(apr_status_t) apr_socket_addr_get(apr_sockaddr_t **sa,
                                              apr_interface_e which,
                                              apr_socket_t *sock)
{
    if (!sock->iol || !sock->iol->iol_socket_addr_get) {
        return uapr_socket_addr_get(sa, which, sock);
    }
    return sock->iol->iol_socket_addr_get(sa, which, sock);
}

#if APR_HAS_SO_ACCEPTFILTER
APR_DECLARE(apr_status_t) apr_socket_accept_filter(apr_socket_t *sock, char *name,
                                      char *args)
{
    if (!sock->iol || !sock->iol->iol_socket_accept_filter) {
        return uapr_socket_accept_filter(sock, name, args);
    }
    return sock->iol->iol_socket_accept_filter(sock, name, args);
}
#endif

APR_DECLARE(apr_status_t) apr_socket_iol_push(apr_socket_iol_t **newiol,
                                              apr_socket_t *sock,
                                              apr_socket_iol_t *iol,
                                              const char *name)
{
    apr_pool_t *p = sock->cntxt;

    if (!sock->iol) {
        /* didn't need this before this call because there were no iols...
         * also, it keeps the patch smaller to initialize it here :)
         */
        sock->iol = (apr_socket_iol_t *)&apr_iol;
    }
    
    *newiol = apr_palloc(p, sizeof(*iol));
    memcpy(*newiol, iol, sizeof(*iol));
    (*newiol)->name = apr_pstrdup(p, name);
    (*newiol)->next = sock->iol; /* last one to push gets called first */
    sock->iol = *newiol;
    return APR_SUCCESS;
}

Index: srclib/apr/include/arch/rename.h
===================================================================
#define apr_shutdown              uapr_shutdown
#define apr_socket_shutdown       uapr_socket_shutdown
#define apr_socket_close          uapr_socket_close
#define apr_bind                  uapr_bind
#define apr_socket_bind           uapr_socket_bind
#define apr_listen                uapr_listen
#define apr_socket_listen         uapr_socket_listen
#define apr_accept                uapr_accept
#define apr_socket_accept         uapr_socket_accept
#define apr_connect               uapr_connect
#define apr_socket_connect        uapr_socket_connect
#define apr_socket_data_get       uapr_socket_data_get
#define apr_socket_data_set       uapr_socket_data_set
#define apr_send                  uapr_send
#define apr_socket_send           uapr_socket_send
#define apr_sendv                 uapr_sendv
#define apr_socket_sendv          uapr_socket_sendv
#define apr_sendto                uapr_sendto
#define apr_socket_sendto         uapr_socket_sendto
#define apr_recvfrom              uapr_recvfrom
#define apr_socket_recvfrom       uapr_socket_recvfrom
#define apr_sendfile              uapr_sendfile
#define apr_socket_sendfile       uapr_socket_sendfile
#define apr_recv                  uapr_recv
#define apr_socket_recv           uapr_socket_recv
#define apr_setsocketopt          uapr_setsocketopt
#define apr_getsocketopt          uapr_getsocketopt
#define apr_socket_opt_set        uapr_socket_opt_set
#define apr_socket_opt_get        uapr_socket_opt_get
#define apr_socket_timeout_set    uapr_socket_timeout_set
#define apr_socket_timeout_get    uapr_socket_timeout_get
#define apr_socket_addr_get       uapr_socket_addr_get
#define apr_socket_accept_filter  uapr_socket_accept_filter
#define apr_socket_iol_push       uapr_socket_iol_push

APR_DECLARE(apr_status_t) uapr_shutdown(apr_socket_t *thesocket,
                                        apr_shutdown_how_e how);
APR_DECLARE(apr_status_t) uapr_socket_shutdown(apr_socket_t *thesocket,
                                               apr_shutdown_how_e how);
APR_DECLARE(apr_status_t) uapr_socket_close(apr_socket_t *thesocket);
APR_DECLARE(apr_status_t) uapr_bind(apr_socket_t *sock, apr_sockaddr_t *sa);
APR_DECLARE(apr_status_t) uapr_socket_bind(apr_socket_t *sock, apr_sockaddr_t *sa);
APR_DECLARE(apr_status_t) uapr_listen(apr_socket_t *sock, apr_int32_t backlog);
APR_DECLARE(apr_status_t) uapr_socket_listen(apr_socket_t *sock, apr_int32_t backlog);
APR_DECLARE(apr_status_t) uapr_accept(apr_socket_t **new_sock, 
                                      apr_socket_t *sock,
                                      apr_pool_t *connection_pool);
APR_DECLARE(apr_status_t) uapr_socket_accept(apr_socket_t **new_sock, 
                                      apr_socket_t *sock,
                                      apr_pool_t *connection_pool);
APR_DECLARE(apr_status_t) uapr_connect(apr_socket_t *sock, apr_sockaddr_t *sa);
APR_DECLARE(apr_status_t) uapr_socket_connect(apr_socket_t *sock, apr_sockaddr_t *sa);
APR_DECLARE(apr_status_t) uapr_socket_data_get(void **data, const char *key,
                                               apr_socket_t *sock);
APR_DECLARE(apr_status_t) uapr_socket_data_set(apr_socket_t *sock, void *data,
                                               const char *key,
                                               apr_status_t (*cleanup)(void*));
APR_DECLARE(apr_status_t) uapr_send(apr_socket_t *sock, const char *buf, 
                                    apr_size_t *len);
APR_DECLARE(apr_status_t) uapr_socket_send(apr_socket_t *sock, const char *buf, 
                                    apr_size_t *len);
APR_DECLARE(apr_status_t) uapr_sendv(apr_socket_t *sock, 
                                     const struct iovec *vec,
                                     apr_int32_t nvec, apr_size_t *len);
APR_DECLARE(apr_status_t) uapr_socket_sendv(apr_socket_t *sock, 
                                     const struct iovec *vec,
                                     apr_int32_t nvec, apr_size_t *len);
APR_DECLARE(apr_status_t) uapr_sendto(apr_socket_t *sock, apr_sockaddr_t *where,
                                      apr_int32_t flags, const char *buf, 
                                      apr_size_t *len);
APR_DECLARE(apr_status_t) uapr_socket_sendto(apr_socket_t *sock, apr_sockaddr_t *where,
                                      apr_int32_t flags, const char *buf, 
                                      apr_size_t *len);
APR_DECLARE(apr_status_t) uapr_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock,
                                        apr_int32_t flags, char *buf, 
                                        apr_size_t *len);
APR_DECLARE(apr_status_t) uapr_socket_recvfrom(apr_sockaddr_t *from, apr_socket_t *sock,
                                        apr_int32_t flags, char *buf, 
                                        apr_size_t *len);
#if APR_HAS_SENDFILE
APR_DECLARE(apr_status_t) uapr_sendfile(apr_socket_t *sock, apr_file_t *file,
                                        apr_hdtr_t *hdtr, apr_off_t *offset,
                                        apr_size_t *len, apr_int32_t flags);
APR_DECLARE(apr_status_t) uapr_socket_sendfile(apr_socket_t *sock, apr_file_t *file,
                                        apr_hdtr_t *hdtr, apr_off_t *offset,
                                        apr_size_t *len, apr_int32_t flags);
#endif
APR_DECLARE(apr_status_t) uapr_recv(apr_socket_t *sock, 
                                    char *buf, apr_size_t *len);
APR_DECLARE(apr_status_t) uapr_socket_recv(apr_socket_t *sock, 
                                    char *buf, apr_size_t *len);
APR_DECLARE(apr_status_t) uapr_setsocketopt(apr_socket_t *sock,
                                            apr_int32_t opt, apr_int32_t on);
APR_DECLARE(apr_status_t) uapr_getsocketopt(apr_socket_t *sock,
                                            apr_int32_t opt, apr_int32_t *on);
APR_DECLARE(apr_status_t) uapr_socket_opt_set(apr_socket_t *sock,
                                              apr_int32_t opt, apr_int32_t on);
APR_DECLARE(apr_status_t) uapr_socket_opt_get(apr_socket_t *sock, 
                                              apr_int32_t opt, apr_int32_t *on);
APR_DECLARE(apr_status_t) uapr_socket_timeout_set(apr_socket_t *sock,
                                                  apr_interval_time_t t);
APR_DECLARE(apr_status_t) uapr_socket_timeout_get(apr_socket_t *sock, 
                                                  apr_interval_time_t *t);
APR_DECLARE(apr_status_t) uapr_socket_addr_get(apr_sockaddr_t **sa,
                                               apr_interface_e which,
                                               apr_socket_t *sock);
Index: server/ihs_hooks.c
===================================================================
/* Copyright 1999-2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "apr.h"
#include "apr_strings.h"

#define CORE_PRIVATE
#include "httpd.h"
#include "http_config.h"
#include "http_protocol.h"
#include "http_request.h"
#include "scoreboard.h"

static unsigned char *handler_modindexes;
static unsigned char *access_checker_modindexes;
static unsigned char *check_user_id_modindexes;
static unsigned char *log_transaction_modindexes;
static const char *modnames[256];

/* NB: This must echo the LINK_##name structure */
/* copied from apr_hooks.c, which also has private definition */
typedef struct
{
    int (*dummy)();
    const char *szName;
    const char * const *aszPredecessors;
    const char * const *aszSuccessors;
    int nOrder;
} TSortData;

struct ap_sb_handle_t { /* copied from scoreboard.c */
    int child_num;
    int thread_num;
};

#define REQUEST_ENVVAR "RH" /* RH stands for "request handler" */

static unsigned char get_modindex(const char *szName)
{
    module *modp = ap_find_linked_module(szName);

    if (modp) {
        if (modp->module_index >= 255) {
            return 255;
        }
        else {
            return modp->module_index;
        }
    }
    else {
        return 0;
    }
}

static void build_index_array(apr_array_header_t *hook_array,
                              unsigned char **hook_modindexes)
{
    TSortData *pHook;
    int n;
    unsigned char *modindexes = NULL;

    /* ihs_save_hook_info() is called several times on initial
     * startup and more as the server has restarted;
     * if the array was allocated previously, free it before
     * we build a new one
     */
    if (*hook_modindexes) {
        free(*hook_modindexes);
    }

    if (hook_array) {
        modindexes =
            (unsigned char *)malloc(sizeof(unsigned char) * hook_array->nelts);
        pHook = (TSortData *)hook_array->elts;
        for (n = 0; n < hook_array->nelts; ++n) {
            modindexes[n] = get_modindex(pHook[n].szName);
        }
    }
    *hook_modindexes = modindexes;
}

AP_DECLARE(void) ihs_save_hook_info(void)
{
    module *modp;
    int i;

    for (i = 0; i < 256; i++) {
        modnames[i] = "unknown";
    }
    for (modp = ap_top_module; modp; modp = modp->next) {
        if (modp->module_index < 255) {
            modnames[modp->module_index] = modp->name;
        }
    }
    /* special entries in the modnames[] array:
     *   0:  for mod_status, a value of 0 in scoreboard means
     *       "not in non-core module"; for the purposes of modnames[]
     *       (indicating which module failed/handled a request),
     *       0 really does mean "core.c" (e.g., default_handler)
     * 255:  in modnames[] as well as in the scoreboard, index 255
     *       indicates that there was an overflow caused by some
     *       module with index > 255; so the actual module name is
     *       unknown (unthinkable to have that many modules loaded)
     */

    build_index_array(ap_hook_get_handler(),        &handler_modindexes);
    build_index_array(ap_hook_get_access_checker(), &access_checker_modindexes);
    build_index_array(ap_hook_get_check_user_id(),  &check_user_id_modindexes);
    build_index_array(ap_hook_get_log_transaction(), &log_transaction_modindexes);
}

/* RUN_FIRST - compare with APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST() */
AP_DECLARE(int) ihs_run_handler(request_rec *r)
{
    apr_array_header_t *hook_array = ap_hook_get_handler();
    TSortData *pHook;
    int n, rv;
    struct ap_sb_handle_t *sbh;
    worker_score *ws;

    if (!ap_extended_status) {
        return ap_run_handler(r);
    }

    if (!hook_array) {
        return DECLINED;
    }

    sbh = r->connection->sbh;
    ws = &ap_scoreboard_image->servers[sbh->child_num][sbh->thread_num];
    pHook = (TSortData *)hook_array->elts;
    for (n = 0; n < hook_array->nelts; ++n) {
        ws->short_module_index = handler_modindexes[n];
        rv = pHook[n].dummy(r);
        if (rv != DECLINED) {
            ws->short_module_index = 0;
            apr_table_set(r->subprocess_env,
                          REQUEST_ENVVAR,
                          apr_psprintf(r->pool,
                                       "(%s/%d/handler)",
                                       modnames[handler_modindexes[n]],
                                       rv));
            return rv;
        }
    }
    ws->short_module_index = 0;
    return DECLINED;
}

/* RUN_ALL - compare with APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL() */
AP_DECLARE(int) ihs_run_access_checker(request_rec *r)
{
    apr_array_header_t *hook_array = ap_hook_get_access_checker();
    TSortData *pHook;
    int n, rv;
    struct ap_sb_handle_t *sbh;
    worker_score *ws;

    if (!ap_extended_status) {
        return ap_run_access_checker(r);
    }

    if (!hook_array) {
        return OK;
    }

    sbh = r->connection->sbh;
    ws = &ap_scoreboard_image->servers[sbh->child_num][sbh->thread_num];
    pHook = (TSortData *)hook_array->elts;
    for (n = 0; n < hook_array->nelts; ++n) {
        ws->short_module_index = access_checker_modindexes[n];
        rv = pHook[n].dummy(r);
        if (rv != OK && rv != DECLINED) {
            ws->short_module_index = 0;
            apr_table_set(r->subprocess_env,
                          REQUEST_ENVVAR,
                          apr_psprintf(r->pool,
                                       "(%s/%d/access_checker)",
                                       modnames[access_checker_modindexes[n]],
                                       rv));
            return rv;
        }
    }
    ws->short_module_index = 0;
    return OK;
}

/* RUN_FIRST - compare with APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST() */
AP_DECLARE(int) ihs_run_check_user_id(request_rec *r)
{
    apr_array_header_t *hook_array = ap_hook_get_check_user_id();
    TSortData *pHook;
    int n, rv;
    struct ap_sb_handle_t *sbh;
    worker_score *ws;

    if (!ap_extended_status) {
        return ap_run_check_user_id(r);
    }

    if (!hook_array) {
        return DECLINED;
    }

    sbh = r->connection->sbh;
    ws = &ap_scoreboard_image->servers[sbh->child_num][sbh->thread_num];
    pHook = (TSortData *)hook_array->elts;
    for (n = 0; n < hook_array->nelts; ++n) {
        ws->short_module_index = check_user_id_modindexes[n];
        rv = pHook[n].dummy(r);
        if (rv != DECLINED) {
            ws->short_module_index = 0;
            apr_table_set(r->subprocess_env,
                          REQUEST_ENVVAR,
                          apr_psprintf(r->pool,
                                       "(%s/%d/check_user_id)",
                                       modnames[check_user_id_modindexes[n]],
                                       rv));
            return rv;
        }
    }
    ws->short_module_index = 0;
    return DECLINED;
}

/* RUN_ALL - compare with APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL() */
AP_DECLARE(int) ihs_run_log_transaction(request_rec *r)
{
    apr_array_header_t *hook_array = ap_hook_get_log_transaction();
    TSortData *pHook;
    int n, rv;
    struct ap_sb_handle_t *sbh;
    worker_score *ws;

    if (!ap_extended_status) {
        return ap_run_log_transaction(r);
    }

    if (!hook_array) {
        return OK;
    }

    sbh = r->connection->sbh;
    ws = &ap_scoreboard_image->servers[sbh->child_num][sbh->thread_num];
    pHook = (TSortData *)hook_array->elts;
    for (n = 0; n < hook_array->nelts; ++n) {
        ws->short_module_index = log_transaction_modindexes[n];
        rv = pHook[n].dummy(r);
        if (rv != OK && rv != DECLINED) {
            ws->short_module_index = 0;
            /* REQUEST_ENVVAR isn't set for this path, since the
             * processing of this hook doesn't affect how the
             * request was handled.
             * Also, if a logging hook has returned an error code
             * and bypasses mod_log_config, there's no way to get
             * the value of an envvar in the access log anyway.
             */
            return rv;
        }
    }
    ws->short_module_index = 0;
    return OK;
}
