]> granicus.if.org Git - apache/blobdiff - modules/aaa/mod_auth_digest.c
Clean up some of the includes:
[apache] / modules / aaa / mod_auth_digest.c
index 0d5671b3811ffcfc4d34b8834c397f90a7ca8bc3..a22614546f78cad1099eca73ee96cd9dee328001 100644 (file)
@@ -64,9 +64,9 @@
  * based on mod_auth, by Rob McCool and Robert S. Thau
  *
  * This module an updated version of modules/standard/mod_digest.c
- * However, it has not been extensively tested yet, and is therefore
- * currently marked experimental. Send problem reports to me
- * (ronald@innovation.ch)
+ * It is still fairly new and problems may turn up - submit problem
+ * reports to the Apache bug-database, or send them directly to me
+ * at ronald@innovation.ch.
  *
  * Requires either /dev/random (or equivalent) or the truerand library,
  * available for instance from
  *     currently ignored by mod_proxy (needs patch to mod_proxy)
  *   - generating the secret takes a while (~ 8 seconds) if using the
  *     truerand library
+ *   - The source of the secret should be run-time directive (with server
+ *     scope: RSRC_CONF). However, that could be tricky when trying to
+ *     choose truerand vs. file...
  *   - shared-mem not completely tested yet. Seems to work ok for me,
  *     but... (definitely won't work on Windoze)
+ *   - Sharing a realm among multiple servers has following problems:
+ *     o Server name and port can't be included in nonce-hash
+ *       (we need two nonce formats, which must be configured explicitly)
+ *     o Nonce-count check can't be for equal, or then nonce-count checking
+ *       must be disabled. What we could do is the following:
+ *       (expected < received) ? set expected = received : issue error
+ *       The only problem is that it allows replay attacks when somebody
+ *       captures a packet sent to one server and sends it to another
+ *       one. Should we add "AuthDigestNcCheck Strict"?
  *   - expired nonces give amaya fits.  
  */
 
 #endif
 #include "httpd.h"
 #include "http_config.h"
-#include "http_conf_globals.h"
 #include "http_core.h"
 #include "http_request.h"
 #include "http_log.h"
 #include "http_protocol.h"
-#include "ap.h"
-#include "ap_ctype.h"
 #include "util_uri.h"
 #include "util_md5.h"
-#include "ap_sha1.h"
+#include "apr_sha1.h"
+#include "apr_base64.h"
+#include "apr_lib.h"
 #include "apr_time.h"
 #include "apr_errno.h"
+#include "apr_lock.h"
+#include "apr_strings.h"
 
-#ifdef HAVE_SHMEM_MM
-#include "mm.h"
-#endif /* HAVE_SHMEM_MM */
+
+#if APR_HAS_SHARED_MEMORY
+#include "apr_shmem.h"
+#else
+/* just provide dummies - the code does run-time checks anyway */
+typedef   void apr_shmem_t;
+typedef   void apr_shm_name_t;
+
+apr_status_t apr_shm_init(apr_shmem_t **m, apr_size_t reqsize, const char *file, apr_pool_t *cont) {
+    return APR_ENOTIMPL;
+}
+apr_status_t apr_shm_destroy(apr_shmem_t *m) {
+    return APR_ENOTIMPL;
+}
+void *apr_shm_malloc(apr_shmem_t *c, apr_size_t reqsize) {
+    return NULL;
+}
+void *apr_shm_calloc(apr_shmem_t *shared, apr_size_t size) {
+    return NULL;
+}
+apr_status_t apr_shm_free(apr_shmem_t *shared, void *free) {
+    return APR_ENOTIMPL;
+}
+apr_status_t apr_shm_name_get(apr_shmem_t *c, apr_shm_name_t **name) {
+    return APR_ENOTIMPL;
+}
+apr_status_t apr_shm_name_set(apr_shmem_t *c, apr_shm_name_t *name) {
+    return APR_ENOTIMPL;
+}
+apr_status_t apr_shm_open(apr_shmem_t *c) {
+    return APR_ENOTIMPL;
+}
+apr_status_t apr_shm_avail(apr_shmem_t *c, apr_size_t *avail) {
+    return APR_ENOTIMPL;
+}
+#endif
 
 
 /* struct to hold the configuration info */
@@ -115,8 +161,8 @@ typedef struct digest_config_struct {
     const char  *grpfile;
     const char  *realm;
     const char **qop_list;
-    AP_SHA1_CTX  nonce_ctx;
-    long         nonce_lifetime;
+    apr_sha1_ctx_t  nonce_ctx;
+    apr_time_t    nonce_lifetime;
     const char  *nonce_format;
     int          check_nc;
     const char  *algorithm;
@@ -127,12 +173,12 @@ typedef struct digest_config_struct {
 
 #define        DFLT_ALGORITHM  "MD5"
 
-#define        DFLT_NONCE_LIFE 300000L /* millis */
-#define NEXTNONCE_DELTA        30000   /* millis */
+#define        DFLT_NONCE_LIFE (300*APR_USEC_PER_SEC)
+#define NEXTNONCE_DELTA        (30*APR_USEC_PER_SEC)
 
 
-#define NONCE_TIME_LEN (((sizeof(ap_time_t)+2)/3)*4)
-#define NONCE_HASH_LEN (2*SHA_DIGESTSIZE)
+#define NONCE_TIME_LEN (((sizeof(apr_time_t)+2)/3)*4)
+#define NONCE_HASH_LEN (2*APR_SHA1_DIGESTSIZE)
 #define NONCE_LEN      (NONCE_TIME_LEN + NONCE_HASH_LEN)
 
 #define        SECRET_LEN      20
@@ -149,7 +195,7 @@ typedef struct hash_entry {
 } client_entry;
 
 static struct hash_table {
-    client_entry  **ap_table_t;
+    client_entry  **table;
     unsigned long   tbl_len;
     unsigned long   num_entries;
     unsigned long   num_created;
@@ -176,9 +222,10 @@ typedef struct digest_header_struct {
     const char           *message_qop;
     const char           *nonce_count;
     /* the following fields are not (directly) from the header */
-    ap_time_t             nonce_time;
+    apr_time_t             nonce_time;
     enum hdr_sts          auth_hdr_sts;
-    uri_components       *request_uri;
+    const char           *raw_request_uri;
+    uri_components       *psd_request_uri;
     int                   needed_auth;
     client_entry         *client;
 } digest_header_rec;
@@ -187,8 +234,8 @@ typedef struct digest_header_struct {
 /* (mostly) nonce stuff */
 
 typedef union time_union {
-    ap_time_t    time;
-    unsigned char arr[sizeof(ap_time_t)];
+    apr_time_t   time;
+    unsigned char arr[sizeof(apr_time_t)];
 } time_rec;
 
 
@@ -196,164 +243,156 @@ static unsigned char secret[SECRET_LEN];
 static int call_cnt = 0;
 
 
-#ifdef HAVE_SHMEM_MM
-/* opaque stuff */
+/* client-list, opaque, and one-time-nonce stuff */
 
-static MM            *opaque_mm;
+static apr_shmem_t    *client_shm = NULL;
 static unsigned long *opaque_cntr;
+static apr_time_t     *otn_counter;    /* one-time-nonce counter */
+static apr_lock_t     *client_lock = NULL;
+static apr_lock_t     *opaque_lock = NULL;
+static char           client_lock_name[L_tmpnam];
+static char           opaque_lock_name[L_tmpnam];
 
-static MM            *client_mm;
-
-static MM            *otn_count_mm;
-static ap_time_t     *otn_counter;     /* one-time-nonce counter */
+#define        DEF_SHMEM_SIZE  1000L           /* ~ 12 entries */
+#define        DEF_NUM_BUCKETS 15L
+#define        HASH_DEPTH      5
 
-#define        SHMEM_SIZE      1000            /* ~ 12 entries */
-#define        NUM_BUCKETS     15UL
+static long shmem_size  = DEF_SHMEM_SIZE;
+static long num_buckets = DEF_NUM_BUCKETS;
 
-#else  /* HAVE_SHMEM_MM */
-static void          *client_mm = NULL;
-#endif /* HAVE_SHMEM_MM */
 
-module MODULE_VAR_EXPORT auth_digest_module;
+module AP_MODULE_DECLARE_DATA digest_auth_module;
 
 /*
  * initialization code
  */
 
-#ifdef HAVE_SHMEM_MM
-static ap_status_t cleanup_tables(void *not_used)
+static apr_status_t cleanup_tables(void *not_used)
 {
     ap_log_rerror(APLOG_MARK, APLOG_STARTUP | APLOG_NOERRNO, 0, NULL, 
                  "Digest: cleaning up shared memory");
     fflush(stderr);
 
-    if (client_mm) {
-       mm_destroy(client_mm);
-       client_mm = NULL;
+    if (client_shm) {
+       apr_shm_destroy(client_shm);
+       client_shm = NULL;
     }
 
-    if (opaque_mm) {
-       mm_destroy(opaque_mm);
-       opaque_mm = NULL;
+    if (client_lock) {
+       apr_lock_destroy(client_lock);
+       client_lock = NULL;
     }
 
-    if (otn_count_mm) {
-       mm_destroy(otn_count_mm);
-       otn_count_mm = NULL;
+    if (opaque_lock) {
+       apr_lock_destroy(opaque_lock);
+       opaque_lock = NULL;
     }
 
     return APR_SUCCESS;
 }
-#endif /* HAVE_SHMEM_MM */
 
 static void initialize_secret(server_rec *s)
 {
-    ap_status_t status;
+    apr_status_t status;
 
     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, s,
                 "Digest: generating secret for digest authentication ...");
 
-    /* TODO - make sure this func works (compiles?) on win32 */
-    status = ap_generate_random_bytes(secret, sizeof(secret));
+#if APR_HAS_RANDOM
+    status = apr_generate_random_bytes(secret, sizeof(secret));
+#else
+#error APR random number support is missing; you probably need to install the truerand library.
+#endif
 
     if(!(status == APR_SUCCESS)) {
+        char buf[120];
        ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_CRIT, 0, s,
                     "Digest: error generating secret: %s", 
-                    /*ap_strerror(status)*/ "need ap_strerror here");
+                    apr_strerror(status, buf, sizeof(buf)));
        exit(1);
     }
 
     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_NOTICE, 0, s, "Digest: done");
 }
 
-#ifdef HAVE_SHMEM_MM
-static void initialize_tables(server_rec *s)
+static void log_error_and_cleanup(char *msg, apr_status_t sts, server_rec *s)
+{
+    ap_log_error(APLOG_MARK, APLOG_ERR, sts, s,
+                "Digest: %s - all nonce-count checking, one-time nonces, and "
+                "MD5-sess algorithm disabled", msg);
+
+    cleanup_tables(NULL);
+}
+
+static void initialize_tables(server_rec *s, apr_pool_t *ctx)
 {
     unsigned long idx;
+    apr_status_t   sts;
 
     /* set up client list */
 
-    client_mm = mm_create(SHMEM_SIZE, tmpnam(NULL));
-    if (client_mm == NULL)
-       goto failed;
-#ifdef MPE
-    if (geteuid() == 1) {
-#else
-    if (geteuid() == 0) {
-#endif
-       if (mm_permission(client_mm, 0600, ap_user_id, ap_group_id))
-           goto failed;
+    sts = apr_shm_init(&client_shm, shmem_size, tmpnam(NULL), ctx);
+    if (sts != APR_SUCCESS) {
+       log_error_and_cleanup("failed to create shared memory segments", sts, s);
+       return;
+    }
+
+    client_list = apr_shm_malloc(client_shm, sizeof(*client_list) +
+                                           sizeof(client_entry*)*num_buckets);
+    if (!client_list) {
+       log_error_and_cleanup("failed to allocate shared memory", -1, s);
+       return;
     }
-    client_list = mm_malloc(client_mm, sizeof(*client_list) +
-                                      sizeof(client_entry*)*NUM_BUCKETS);
-    if (!client_list)  goto failed;
     client_list->table = (client_entry**) (client_list + 1);
-    for (idx=0; idx<NUM_BUCKETS; idx++)
+    for (idx=0; idx<num_buckets; idx++)
        client_list->table[idx] = NULL;
-    client_list->tbl_len     = NUM_BUCKETS;
+    client_list->tbl_len     = num_buckets;
     client_list->num_entries = 0;
 
+    tmpnam(client_lock_name);
+    sts = apr_lock_create(&client_lock, APR_READWRITE, APR_LOCKALL,
+                        client_lock_name, ctx);
+    if (sts != APR_SUCCESS) {
+       log_error_and_cleanup("failed to create lock", sts, s);
+       return;
+    }
+
 
     /* setup opaque */
 
-    opaque_mm = mm_create(sizeof(*opaque_cntr), tmpnam(NULL));
-    if (opaque_mm == NULL)
-       goto failed;
-#ifdef MPE
-    if (geteuid() == 1) {
-#else
-    if (geteuid() == 0) {
-#endif
-       if (mm_permission(opaque_mm, 0600, ap_user_id, ap_group_id))
-           goto failed;
+    opaque_cntr = apr_shm_malloc(client_shm, sizeof(*opaque_cntr));
+    if (opaque_cntr == NULL) {
+       log_error_and_cleanup("failed to allocate shared memory", -1, s);
+       return;
     }
-    opaque_cntr = mm_malloc(opaque_mm, sizeof(*opaque_cntr));
-    if (opaque_cntr == NULL)
-       goto failed;
     *opaque_cntr = 1UL;
 
+    tmpnam(opaque_lock_name);
+    sts = apr_lock_create(&opaque_lock, APR_MUTEX, APR_LOCKALL,
+                        opaque_lock_name, ctx);
+    if (sts != APR_SUCCESS) {
+       log_error_and_cleanup("failed to create lock", sts, s);
+       return;
+    }
+
 
     /* setup one-time-nonce counter */
 
-    otn_count_mm = mm_create(sizeof(*otn_counter), tmpnam(NULL));
-    if (otn_count_mm == NULL)
-       goto failed;
-#ifdef MPE
-    if (geteuid() == 1) {
-#else
-    if (geteuid() == 0) {
-#endif
-       if (mm_permission(otn_count_mm, 0600, ap_user_id, ap_group_id))
-           goto failed;
+    otn_counter = apr_shm_malloc(client_shm, sizeof(*otn_counter));
+    if (otn_counter == NULL) {
+       log_error_and_cleanup("failed to allocate shared memory", -1, s);
+       return;
     }
-    otn_counter = mm_malloc(otn_count_mm, sizeof(*otn_counter));
-    if (otn_counter == NULL)
-       goto failed;
     *otn_counter = 0;
+       /* no lock here */
 
 
     /* success */
     return;
-
-failed:
-    if (!client_mm || (client_list && client_list->table && !opaque_mm)
-       || (opaque_cntr && !otn_count_mm))
-       ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, s,
-                    "Digest: failed to create shared memory segments; reason "
-                    "was `%s' - all nonce-count checking, one-time nonces, "
-                    "and MD5-sess algorithm disabled", mm_error());
-    else
-       ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, s,
-                    "Digest: failed to allocate shared mem; reason was `%s' "
-                    "- all nonce-count checking, one-time nonces, and "
-                    "MD5-sess algorithm disabled", mm_error());
-
-    cleanup_tables(NULL);
 }
-#endif /* HAVE_SHMEM_MM */
 
-static void initialize_module(ap_pool_t *p, ap_pool_t *plog,
-                             ap_pool_t *ptemp, server_rec *s)
+static void initialize_module(apr_pool_t *p, apr_pool_t *plog,
+                             apr_pool_t *ptemp, server_rec *s)
 {
     /* keep from doing the init more than once at startup, and delay
      * the init until the second round
@@ -365,39 +404,58 @@ static void initialize_module(ap_pool_t *p, ap_pool_t *plog,
     if (call_cnt == 2)
        initialize_secret(s);
 
-#ifdef HAVE_SHMEM_MM
+/* Disable shmem until pools/init gets sorted out - remove next line when fixed */
+#undef APR_HAS_SHARED_MEMORY
+#define APR_HAS_SHARED_MEMORY 0
+
+#if APR_HAS_SHARED_MEMORY
     /* Note: this stuff is currently fixed for the lifetime of the server,
      * i.e. even across restarts. This means that A) any shmem-size
      * configuration changes are ignored, and B) certain optimizations,
      * such as only allocating the smallest necessary entry for each
      * client, can't be done. However, the alternative is a nightmare:
-     * we can't call mm_destroy on a graceful restart because there will
-     * be children using the tables, and we also don't know when the
+     * we can't call apr_shm_destroy on a graceful restart because there
+     * will be children using the tables, and we also don't know when the
      * last child dies. Therefore we can never clean up the old stuff,
      * creating a creeping memory leak.
      */
-    initialize_tables(s);
-    ap_register_cleanup(p, NULL, cleanup_tables, ap_null_cleanup);
-#endif /* HAVE_SHMEM_MM */
+    initialize_tables(s, p);
+    apr_pool_cleanup_register(p, NULL, cleanup_tables, apr_pool_cleanup_null);
+#endif /* APR_HAS_SHARED_MEMORY */
 }
 
+static void initialize_child(apr_pool_t *p, server_rec *s)
+{
+    apr_status_t sts;
+
+    if (!client_shm)
+       return;
+
+    if ((sts = apr_lock_child_init(&client_lock, client_lock_name, p))
+           != APR_SUCCESS
+       ||  (sts = apr_lock_child_init(&opaque_lock, opaque_lock_name, p))
+           != APR_SUCCESS) {
+       log_error_and_cleanup("failed to create lock", sts, s);
+       return;
+    }
+}
 
 /*
  * configuration code
  */
 
-static void *create_digest_dir_config(ap_pool_t *p, char *dir)
+static void *create_digest_dir_config(apr_pool_t *p, char *dir)
 {
     digest_config_rec *conf;
 
     if (dir == NULL)  return NULL;
 
-    conf = (digest_config_rec *) ap_pcalloc(p, sizeof(digest_config_rec));
+    conf = (digest_config_rec *) apr_pcalloc(p, sizeof(digest_config_rec));
     if (conf) {
-       conf->qop_list       = ap_palloc(p, sizeof(char*));
+       conf->qop_list       = apr_palloc(p, sizeof(char*));
        conf->qop_list[0]    = NULL;
        conf->nonce_lifetime = DFLT_NONCE_LIFE;
-       conf->dir_name       = ap_pstrdup(p, dir);
+       conf->dir_name       = apr_pstrdup(p, dir);
        conf->algorithm      = DFLT_ALGORITHM;
     }
 
@@ -419,10 +477,10 @@ static const char *set_realm(cmd_parms *cmd, void *config, const char *realm)
      * the host:port would be too, but that varies for .htaccess files
      * and directives outside a virtual host section)
      */
-    ap_SHA1Init(&conf->nonce_ctx);
-    ap_SHA1Update_binary(&conf->nonce_ctx, (const unsigned char *) realm,
+    apr_sha1_init(&conf->nonce_ctx);
+    apr_sha1_update_binary(&conf->nonce_ctx, secret, sizeof(secret));
+    apr_sha1_update_binary(&conf->nonce_ctx, (const unsigned char *) realm,
                         strlen(realm));
-    ap_SHA1Update_binary(&conf->nonce_ctx, secret, sizeof(secret));
 
     return DECLINE_CMD;
 }
@@ -449,7 +507,7 @@ static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
 
     if (!strcasecmp(op, "none")) {
        if (conf->qop_list[0] == NULL) {
-           conf->qop_list = ap_palloc(cmd->pool, 2 * sizeof(char*));
+           conf->qop_list = apr_palloc(cmd->pool, 2 * sizeof(char*));
            conf->qop_list[1] = NULL;
        }
        conf->qop_list[0] = "none";
@@ -461,13 +519,13 @@ static const char *set_qop(cmd_parms *cmd, void *config, const char *op)
                     "Digest: WARNING: qop `auth-int' currently only works "
                     "correctly for responses with no entity");
     else if (strcasecmp(op, "auth"))
-       return ap_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
+       return apr_pstrcat(cmd->pool, "Unrecognized qop: ", op, NULL);
 
     for (cnt=0; conf->qop_list[cnt] != NULL; cnt++)
        ;
-    tmp = ap_palloc(cmd->pool, (cnt+2)*sizeof(char*));
+    tmp = apr_palloc(cmd->pool, (cnt+2)*sizeof(char*));
     memcpy(tmp, conf->qop_list, cnt*sizeof(char*));
-    tmp[cnt]   = ap_pstrdup(cmd->pool, op);
+    tmp[cnt]   = apr_pstrdup(cmd->pool, op);
     tmp[cnt+1] = NULL;
     conf->qop_list = tmp;
 
@@ -479,12 +537,12 @@ static const char *set_nonce_lifetime(cmd_parms *cmd, void *config,
 {
     char *endptr;
     long  lifetime;
-                               /* convert from seconds to millis */
-    lifetime = 1000*strtol(t, &endptr, 10); 
-    if (endptr < (t+strlen(t)) && !ap_isspace(*endptr))
-       return ap_pstrcat(cmd->pool, "Invalid time in AuthDigestNonceLifetime: ", t, NULL);
 
-    ((digest_config_rec *) config)->nonce_lifetime = lifetime;
+    lifetime = strtol(t, &endptr, 10); 
+    if (endptr < (t+strlen(t)) && !apr_isspace(*endptr))
+       return apr_pstrcat(cmd->pool, "Invalid time in AuthDigestNonceLifetime: ", t, NULL);
+
+    ((digest_config_rec *) config)->nonce_lifetime = lifetime * APR_USEC_PER_SEC;
     return NULL;
 }
 
@@ -497,22 +555,29 @@ static const char *set_nonce_format(cmd_parms *cmd, void *config,
 
 static const char *set_nc_check(cmd_parms *cmd, void *config, int flag)
 {
+    if (flag && !client_shm)
+       ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0,
+                    cmd->server, "Digest: WARNING: nonce-count checking "
+                    "is not supported on platforms without shared-memory "
+                    "support - disabling check");
+
     ((digest_config_rec *) config)->check_nc = flag;
     return NULL;
 }
 
 static const char *set_algorithm(cmd_parms *cmd, void *config, const char *alg)
 {
-    if (!strcasecmp(alg, "MD5-sess"))
-#ifdef HAVE_SHMEM_MM
-       ;
-#else  /* HAVE_SHMEM_MM */
-       ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0, cmd->server,
-                    "Digest: WARNING: algorithm `MD5-sess' is currently not "
-                    "correctly implemented");
-#endif /* HAVE_SHMEM_MM */
+    if (!strcasecmp(alg, "MD5-sess")) {
+       if (!client_shm) {
+           ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_WARNING, 0,
+                        cmd->server, "Digest: WARNING: algorithm `MD5-sess' "
+                        "is not supported on platforms without shared-memory "
+                        "support - reverting to MD5");
+           alg = "MD5";
+       }
+    }
     else if (strcasecmp(alg, "MD5"))
-       return ap_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
+       return apr_pstrcat(cmd->pool, "Invalid algorithm in AuthDigestAlgorithm: ", alg, NULL);
 
     ((digest_config_rec *) config)->algorithm = alg;
     return NULL;
@@ -523,38 +588,74 @@ static const char *set_uri_list(cmd_parms *cmd, void *config, const char *uri)
     digest_config_rec *c = (digest_config_rec *) config;
     if (c->uri_list) {
        c->uri_list[strlen(c->uri_list)-1] = '\0';
-       c->uri_list = ap_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
+       c->uri_list = apr_pstrcat(cmd->pool, c->uri_list, " ", uri, "\"", NULL);
     }
     else
-       c->uri_list = ap_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
+       c->uri_list = apr_pstrcat(cmd->pool, ", domain=\"", uri, "\"", NULL);
+    return NULL;
+}
+
+static const char *set_shmem_size(cmd_parms *cmd, void *config,
+                                 const char *size_str)
+{
+    char *endptr;
+    long  size, min;
+
+    size = strtol(size_str, &endptr, 10); 
+    while (apr_isspace(*endptr)) endptr++;
+    if (*endptr == '\0' || *endptr == 'b' || *endptr == 'B')
+       ;
+    else if (*endptr == 'k' || *endptr == 'K')
+       size *= 1024;
+    else if (*endptr == 'm' || *endptr == 'M')
+       size *= 1048576;
+    else
+       return apr_pstrcat(cmd->pool, "Invalid size in AuthDigestShmemSize: ",
+                         size_str, NULL);
+
+    min = sizeof(*client_list) + sizeof(client_entry*) + sizeof(client_entry);
+    if (size < min)
+       return apr_psprintf(cmd->pool, "size in AuthDigestShmemSize too small: "
+                          "%ld < %ld", size, min, NULL);
+
+    shmem_size  = size;
+    num_buckets = (size - sizeof(*client_list)) /
+                 (sizeof(client_entry*) + HASH_DEPTH * sizeof(client_entry));
+    if (num_buckets == 0)
+       num_buckets = 1;
+    ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, 0, cmd->server,
+                "Digest: Set shmem-size: %ld, num-buckets: %ld", shmem_size,
+                num_buckets);
+
     return NULL;
 }
 
 static const command_rec digest_cmds[] =
 {
-    {"AuthName", set_realm, NULL, OR_AUTHCFG, TAKE1,
-     "The authentication realm (e.g. \"Members Only\")"},
-    {"AuthDigestFile", set_digest_file, NULL, OR_AUTHCFG, TAKE1,
-     "The name of the file containing the usernames and password hashes"},
-    {"AuthDigestGroupFile", set_group_file, NULL, OR_AUTHCFG, TAKE1,
-     "The name of the file containing the group names and members"},
-    {"AuthDigestQop", set_qop, NULL, OR_AUTHCFG, ITERATE,
-     "A list of quality-of-protection options"},
-    {"AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG, TAKE1,
-     "Maximum lifetime of the server nonce (seconds)"},
-    {"AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG, TAKE1,
-     "The format to use when generating the server nonce"},
-    {"AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG, FLAG,
-     "Whether or not to check the nonce-count sent by the client"},
-    {"AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG, TAKE1,
-     "The algorithm used for the hash calculation"},
-    {"AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG, ITERATE,
-     "A list of URI's which belong to the same protection space as the current URI"},
+    AP_INIT_TAKE1("AuthName", set_realm, NULL, OR_AUTHCFG, 
+     "The authentication realm (e.g. \"Members Only\")"),
+    AP_INIT_TAKE1("AuthDigestFile", set_digest_file, NULL, OR_AUTHCFG, 
+     "The name of the file containing the usernames and password hashes"),
+    AP_INIT_TAKE1("AuthDigestGroupFile", set_group_file, NULL, OR_AUTHCFG, 
+     "The name of the file containing the group names and members"),
+    AP_INIT_ITERATE("AuthDigestQop", set_qop, NULL, OR_AUTHCFG, 
+     "A list of quality-of-protection options"),
+    AP_INIT_TAKE1("AuthDigestNonceLifetime", set_nonce_lifetime, NULL, OR_AUTHCFG, 
+     "Maximum lifetime of the server nonce (seconds)"),
+    AP_INIT_TAKE1("AuthDigestNonceFormat", set_nonce_format, NULL, OR_AUTHCFG, 
+     "The format to use when generating the server nonce"),
+    AP_INIT_FLAG("AuthDigestNcCheck", set_nc_check, NULL, OR_AUTHCFG, 
+     "Whether or not to check the nonce-count sent by the client"),
+    AP_INIT_TAKE1("AuthDigestAlgorithm", set_algorithm, NULL, OR_AUTHCFG, 
+     "The algorithm used for the hash calculation"),
+    AP_INIT_ITERATE("AuthDigestDomain", set_uri_list, NULL, OR_AUTHCFG, 
+     "A list of URI's which belong to the same protection space as the current URI"),
+    AP_INIT_TAKE1("AuthDigestShmemSize", set_shmem_size, NULL, RSRC_CONF, 
+     "The amount of shared memory to allocate for keeping track of clients"),
     {NULL}
 };
 
 
-#ifdef HAVE_SHMEM_MM
 /*
  * client list code
  *
@@ -617,12 +718,12 @@ static client_entry *get_client(unsigned long key, const request_rec *r)
     client_entry *entry, *prev = NULL;
 
 
-    if (!key || !client_mm)  return NULL;
+    if (!key || !client_shm)  return NULL;
 
     bucket = key % client_list->tbl_len;
     entry  = client_list->table[bucket];
 
-    mm_lock(client_mm, MM_LOCK_RD);
+    apr_lock_aquire(client_lock /*, MM_LOCK_RD */);
 
     while(entry && key != entry->key) {
        prev  = entry;
@@ -635,7 +736,7 @@ static client_entry *get_client(unsigned long key, const request_rec *r)
        client_list->table[bucket] = entry;
     }
 
-    mm_unlock(client_mm);
+    apr_lock_release(client_lock);
 
     if (entry)
        ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, 0, r,
@@ -669,7 +770,7 @@ static long gc(void)
        if (prev)  prev->next = NULL;   /* cut list */
        else       client_list->table[idx] = NULL;
        if (entry) {                    /* remove entry */
-           mm_free(client_mm, entry);
+           apr_shm_free(client_shm, entry);
            num_removed++;
        }
     }
@@ -685,25 +786,25 @@ static long gc(void)
 
 /*
  * Add a new client to the list. Returns the entry if successful, NULL
- * otherwise. This triggers the garbage collection is memory is low.
+ * otherwise. This triggers the garbage collection if memory is low.
  */
-static client_entry *add_client(unsigned long key, client_entry *new,
+static client_entry *add_client(unsigned long key, client_entry *info,
                                server_rec *s)
 {
     int bucket;
     client_entry *entry;
 
 
-    if (!key || !client_mm)  return NULL;
+    if (!key || !client_shm)  return NULL;
 
     bucket = key % client_list->tbl_len;
     entry  = client_list->table[bucket];
 
-    mm_lock(client_mm, MM_LOCK_RW);
+    apr_lock_aquire(client_lock /*, MM_LOCK_RW */);
 
     /* try to allocate a new entry */
 
-    entry = mm_malloc(client_mm, sizeof(client_entry));
+    entry = apr_shm_malloc(client_shm, sizeof(client_entry));
     if (!entry) {
        long num_removed = gc();
        ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0, s,
@@ -712,32 +813,26 @@ static client_entry *add_client(unsigned long key, client_entry *new,
                     "%ld", num_removed,
                     client_list->num_created - client_list->num_renewed,
                     client_list->num_removed, client_list->num_renewed);
-       entry = mm_malloc(client_mm, sizeof(client_entry));
+       entry = apr_shm_malloc(client_shm, sizeof(client_entry));
        if (!entry)  return NULL;       /* give up */
     }
 
     /* now add the entry */
 
-    memcpy(entry, new, sizeof(client_entry));
+    memcpy(entry, info, sizeof(client_entry));
     entry->key  = key;
     entry->next = client_list->table[bucket];
     client_list->table[bucket] = entry;
     client_list->num_created++;
     client_list->num_entries++;
 
-    mm_unlock(client_mm);
+    apr_lock_release(client_lock);
 
     ap_log_error(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, 0, s,
                 "allocated new client %lu", key);
 
     return entry;
 }
-#else  /* HAVE_SHMEM_MM */
-static client_entry *get_client(unsigned long key, const request_rec *r)
-{
-    return NULL;
-}
-#endif /* HAVE_SHMEM_MM */
 
 
 /*
@@ -747,14 +842,14 @@ static client_entry *get_client(unsigned long key, const request_rec *r)
 /* Parse the Authorization header, if it exists */
 static int get_digest_rec(request_rec *r, digest_header_rec *resp)
 {
-    const char *auth_line = ap_table_get(r->headers_in,
-                                        r->proxyreq ? "Proxy-Authorization"
-                                                    : "Authorization");
+    const char *auth_line;
     size_t l;
     int vk = 0, vv = 0;
     char *key, *value;
 
-
+    auth_line = apr_table_get(r->headers_in,
+                            r->proxyreq ? "Proxy-Authorization"
+                                        : "Authorization");
     if (!auth_line) {
        resp->auth_hdr_sts = NO_HEADER;
        return !OK;
@@ -768,26 +863,26 @@ static int get_digest_rec(request_rec *r, digest_header_rec *resp)
 
     l = strlen(auth_line);
 
-    key   = ap_palloc(r->pool, l+1);
-    value = ap_palloc(r->pool, l+1);
+    key   = apr_palloc(r->pool, l+1);
+    value = apr_palloc(r->pool, l+1);
 
     while (auth_line[0] != '\0') {
 
        /* find key */
 
-       while (ap_isspace(auth_line[0])) auth_line++;
+       while (apr_isspace(auth_line[0])) auth_line++;
        vk = 0;
        while (auth_line[0] != '=' && auth_line[0] != ','
-              && auth_line[0] != '\0' && !ap_isspace(auth_line[0]))
+              && auth_line[0] != '\0' && !apr_isspace(auth_line[0]))
            key[vk++] = *auth_line++;
        key[vk] = '\0';
-       while (ap_isspace(auth_line[0])) auth_line++;
+       while (apr_isspace(auth_line[0])) auth_line++;
 
        /* find value */
 
        if (auth_line[0] == '=') {
            auth_line++;
-           while (ap_isspace(auth_line[0])) auth_line++;
+           while (apr_isspace(auth_line[0])) auth_line++;
 
            vv = 0;
            if (auth_line[0] == '\"') {         /* quoted string */
@@ -801,7 +896,7 @@ static int get_digest_rec(request_rec *r, digest_header_rec *resp)
            }
            else {                               /* token */
                while (auth_line[0] != ',' && auth_line[0] != '\0'
-                      && !ap_isspace(auth_line[0]))
+                      && !apr_isspace(auth_line[0]))
                    value[vv++] = *auth_line++;
            }
            value[vv] = '\0';
@@ -811,29 +906,30 @@ static int get_digest_rec(request_rec *r, digest_header_rec *resp)
        if (auth_line[0] != '\0') auth_line++;
 
        if (!strcasecmp(key, "username"))
-           resp->username = ap_pstrdup(r->pool, value);
+           resp->username = apr_pstrdup(r->pool, value);
        else if (!strcasecmp(key, "realm"))
-           resp->realm = ap_pstrdup(r->pool, value);
+           resp->realm = apr_pstrdup(r->pool, value);
        else if (!strcasecmp(key, "nonce"))
-           resp->nonce = ap_pstrdup(r->pool, value);
+           resp->nonce = apr_pstrdup(r->pool, value);
        else if (!strcasecmp(key, "uri"))
-           resp->uri = ap_pstrdup(r->pool, value);
+           resp->uri = apr_pstrdup(r->pool, value);
        else if (!strcasecmp(key, "response"))
-           resp->digest = ap_pstrdup(r->pool, value);
+           resp->digest = apr_pstrdup(r->pool, value);
        else if (!strcasecmp(key, "algorithm"))
-           resp->algorithm = ap_pstrdup(r->pool, value);
+           resp->algorithm = apr_pstrdup(r->pool, value);
        else if (!strcasecmp(key, "cnonce"))
-           resp->cnonce = ap_pstrdup(r->pool, value);
+           resp->cnonce = apr_pstrdup(r->pool, value);
        else if (!strcasecmp(key, "opaque"))
-           resp->opaque = ap_pstrdup(r->pool, value);
+           resp->opaque = apr_pstrdup(r->pool, value);
        else if (!strcasecmp(key, "qop"))
-           resp->message_qop = ap_pstrdup(r->pool, value);
+           resp->message_qop = apr_pstrdup(r->pool, value);
        else if (!strcasecmp(key, "nc"))
-           resp->nonce_count = ap_pstrdup(r->pool, value);
+           resp->nonce_count = apr_pstrdup(r->pool, value);
     }
 
     if (!resp->username || !resp->realm || !resp->nonce || !resp->uri
-       || !resp->digest) {
+       || !resp->digest
+       || (resp->message_qop && (!resp->cnonce || !resp->nonce_count))) {
        resp->auth_hdr_sts = INVALID;
        return !OK;
     }
@@ -865,10 +961,11 @@ static int parse_hdr_and_update_nc(request_rec *r)
     if (!ap_is_initial_req(r))
        return DECLINED;
 
-    resp = ap_pcalloc(r->pool, sizeof(digest_header_rec));
-    resp->request_uri = &r->parsed_uri;
+    resp = apr_pcalloc(r->pool, sizeof(digest_header_rec));
+    resp->raw_request_uri = r->unparsed_uri;
+    resp->psd_request_uri = &r->parsed_uri;
     resp->needed_auth = 0;
-    ap_set_module_config(r->request_config, &auth_digest_module, resp);
+    ap_set_module_config(r->request_config, &digest_auth_module, resp);
 
     res = get_digest_rec(r, resp);
     resp->client = get_client(resp->opaque_num, r);
@@ -883,30 +980,32 @@ static int parse_hdr_and_update_nc(request_rec *r)
  * Nonce generation code
  */
 
-/* The hash part of the nonce is a SHA-1 hash of the time, realm, opaque,
- * and our secret.
+/* The hash part of the nonce is a SHA-1 hash of the time, realm, server host
+ * and port, opaque, and our secret.
  */
 static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
                           const server_rec *server,
                           const digest_config_rec *conf)
 {
     const char *hex = "0123456789abcdef";
-    unsigned char sha1[SHA_DIGESTSIZE];
-    AP_SHA1_CTX ctx;
+    unsigned char sha1[APR_SHA1_DIGESTSIZE];
+    apr_sha1_ctx_t ctx;
     int idx;
 
     memcpy(&ctx, &conf->nonce_ctx, sizeof(ctx));
-    ap_SHA1Update_binary(&ctx, (const unsigned char *) server->server_hostname,
+    /*
+    apr_sha1_update_binary(&ctx, (const unsigned char *) server->server_hostname,
                         strlen(server->server_hostname));
-    ap_SHA1Update_binary(&ctx, (const unsigned char *) &server->port,
+    apr_sha1_update_binary(&ctx, (const unsigned char *) &server->port,
                         sizeof(server->port));
-    ap_SHA1Update_binary(&ctx, (const unsigned char *) timestr, strlen(timestr));
+     */
+    apr_sha1_update_binary(&ctx, (const unsigned char *) timestr, strlen(timestr));
     if (opaque)
-       ap_SHA1Update_binary(&ctx, (const unsigned char *) opaque,
+       apr_sha1_update_binary(&ctx, (const unsigned char *) opaque,
                             strlen(opaque));
-    ap_SHA1Final(sha1, &ctx);
+    apr_sha1_final(sha1, &ctx);
 
-    for (idx=0; idx<SHA_DIGESTSIZE; idx++) {
+    for (idx=0; idx<APR_SHA1_DIGESTSIZE; idx++) {
        *hash++ = hex[sha1[idx] >> 4];
        *hash++ = hex[sha1[idx] & 0xF];
     }
@@ -917,25 +1016,24 @@ static void gen_nonce_hash(char *hash, const char *timestr, const char *opaque,
 
 /* The nonce has the format b64(time)+hash .
  */
-static const char *gen_nonce(ap_pool_t *p, ap_time_t now, const char *opaque,
+static const char *gen_nonce(apr_pool_t *p, apr_time_t now, const char *opaque,
                             const server_rec *server,
                             const digest_config_rec *conf)
 {
-    char *nonce = ap_palloc(p, NONCE_LEN+1);
+    char *nonce = apr_palloc(p, NONCE_LEN+1);
+    int len;
     time_rec t;
 
     if (conf->nonce_lifetime != 0)
        t.time = now;
-    else
-#ifdef HAVE_SHMEM_MM
+    else if (otn_counter)
        /* this counter is not synch'd, because it doesn't really matter
         * if it counts exactly.
         */
        t.time = (*otn_counter)++;
-#else  /* HAVE_SHMEM_MM */
+    else
        t.time = 42;
-#endif /* HAVE_SHMEM_MM */
-    ap_base64encode_binary(nonce, t.arr, sizeof(t.arr));
+    len = apr_base64_encode_binary(nonce, t.arr, sizeof(t.arr));
     gen_nonce_hash(nonce+NONCE_TIME_LEN, nonce, opaque, server, conf);
 
     return nonce;
@@ -946,7 +1044,6 @@ static const char *gen_nonce(ap_pool_t *p, ap_time_t now, const char *opaque,
  * Opaque and hash-table management
  */
 
-#ifdef HAVE_SHMEM_MM
 /*
  * Generate a new client entry, add it to the list, and return the
  * entry. Returns NULL if failed.
@@ -954,15 +1051,15 @@ static const char *gen_nonce(ap_pool_t *p, ap_time_t now, const char *opaque,
 static client_entry *gen_client(const request_rec *r)
 {
     unsigned long op;
-    client_entry new = { 0, NULL, 0, "", "" }, *entry;
+    client_entry new_entry = { 0, NULL, 0, "", "" }, *entry;
 
-    if (!opaque_mm)  return 0;
+    if (!opaque_cntr)  return NULL;
 
-    mm_lock(opaque_mm, MM_LOCK_RW);
+    apr_lock_aquire(opaque_lock /*, MM_LOCK_RW */);
     op = (*opaque_cntr)++;
-    mm_unlock(opaque_mm);
+    apr_lock_release(opaque_lock);
 
-    if (!(entry = add_client(op, &new, r->server))) {
+    if (!(entry = add_client(op, &new_entry, r->server))) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r,
                      "Digest: failed to allocate client entry - ignoring "
                      "client");
@@ -971,63 +1068,76 @@ static client_entry *gen_client(const request_rec *r)
 
     return entry;
 }
-#else  /* HAVE_SHMEM_MM */
-static client_entry *gen_client(const request_rec *r) { return NULL; }
-#endif /* HAVE_SHMEM_MM */
-
 
 
 /*
  * MD5-sess code.
  *
  * If you want to use algorithm=MD5-sess you must write get_userpw_hash()
- * yourself (see below). The dummy provided here just returns the hash
- * from the auth-file, i.e. it is only useful for testing client
- * implementations of MD5-sess .
+ * yourself (see below). The dummy provided here just uses the hash from
+ * the auth-file, i.e. it is only useful for testing client implementations
+ * of MD5-sess .
  */
 
 /*
  * get_userpw_hash() will be called each time a new session needs to be
  * generated and is expected to return the equivalent of
  *
+ * h_urp = ap_md5(r->pool,
+ *         apr_pstrcat(r->pool, username, ":", ap_auth_name(r), ":", passwd))
  * ap_md5(r->pool,
- *        ap_pstrcat(r->pool, username, ":", ap_auth_name(r), ":", passwd))
+ *         (unsigned char *) apr_pstrcat(r->pool, h_urp, ":", resp->nonce, ":",
+ *                                      resp->cnonce, NULL));
+ *
+ * or put differently, it must return
+ *
+ *   MD5(MD5(username ":" realm ":" password) ":" nonce ":" cnonce)
+ *
+ * If something goes wrong, the failure must be logged and NULL returned.
  *
- * You must implement this yourself, and will probably consist of code
- * contacting the password server and retrieving the hash from it.
+ * You must implement this yourself, which will probably consist of code
+ * contacting the password server with the necessary information (typically
+ * the username, realm, nonce, and cnonce) and receiving the hash from it.
  *
  * TBD: This function should probably be in a seperate source file so that
- * people need not modify mod_auth_digest.c each time they install a new version
- * of apache.
+ * people need not modify mod_auth_digest.c each time they install a new
+ * version of apache.
  */
 static const char *get_userpw_hash(const request_rec *r,
                                   const digest_header_rec *resp,
                                   const digest_config_rec *conf)
 {
-    /* for now, just get it from pwfile */
-    return conf->ha1;
+    return ap_md5(r->pool,
+            (unsigned char *) apr_pstrcat(r->pool, conf->ha1, ":", resp->nonce,
+                                         ":", resp->cnonce, NULL));
 }
 
 
-static const char *get_session(const request_rec *r,
-                              digest_header_rec *resp,
-                              const digest_config_rec *conf)
+/* Retrieve current session H(A1). If there is none and "generate" is
+ * true then a new session for MD5-sess is generated and stored in the
+ * client struct; if generate is false, or a new session could not be
+ * generated then NULL is returned (in case of failure to generate the
+ * failure reason will have been logged already).
+ */
+static const char *get_session_HA1(const request_rec *r,
+                                  digest_header_rec *resp,
+                                  const digest_config_rec *conf,
+                                  int generate)
 {
-    const char *ha1 = NULL, *urp;
-
-    /* get ha1 from client list */
-    if (resp->opaque && resp->client)
-       ha1 = resp->client->ha1;
-
-    /* generate new session if necessary */
-    if (ha1 == NULL || ha1[0] == '\0') {
-       urp = get_userpw_hash(r, resp, conf);
-       ha1 = ap_md5(r->pool,
-                    (unsigned char *) ap_pstrcat(r->pool, urp, ":", resp->nonce,
-                                                 ":", resp->cnonce, NULL));
-       if (!resp->client)
-           resp->client = gen_client(r);
-       if (resp->client)
+    const char *ha1 = NULL;
+
+    /* return the current sessions if there is one */
+    if (resp->opaque && resp->client && resp->client->ha1[0])
+       return resp->client->ha1;
+    else if (!generate)
+       return NULL;
+
+    /* generate a new session */
+    if (!resp->client)
+       resp->client = gen_client(r);
+    if (resp->client) {
+       ha1 = get_userpw_hash(r, resp, conf);
+       if (ha1)
            memcpy(resp->client->ha1, ha1, sizeof(resp->client->ha1));
     }
 
@@ -1046,7 +1156,7 @@ static void clear_session(const digest_header_rec *resp)
  * Authorization challenge generation code (for WWW-Authenticate)
  */
 
-static const char *guess_domain(ap_pool_t *p, const char *uri,
+static const char *guess_domain(apr_pool_t *p, const char *uri,
                                const char *filename, const char *dir)
 {
     size_t u_len = strlen(uri), f_len = strlen(filename), d_len = strlen(dir);
@@ -1102,7 +1212,7 @@ static const char *guess_domain(ap_pool_t *p, const char *uri,
      * take the uri with the same reach.
      */
     if ((unsigned long) (f-filename) < d_len) {
-       char *tmp = ap_pstrdup(p, uri);
+       char *tmp = apr_pstrdup(p, uri);
        tmp[(u-uri)+(d_len-(f-filename))] = '\0';
        return tmp;
     }
@@ -1111,10 +1221,10 @@ static const char *guess_domain(ap_pool_t *p, const char *uri,
 }
 
 
-static const char *ltox(ap_pool_t *p, unsigned long num)
+static const char *ltox(apr_pool_t *p, unsigned long num)
 {
     if (num != 0)
-       return ap_psprintf(p, "%lx", num);
+       return apr_psprintf(p, "%lx", num);
     else
        return "";
 }
@@ -1133,17 +1243,12 @@ static void note_digest_auth_failure(request_rec *r,
     } else if (!strcasecmp(conf->qop_list[0], "none")) {
        qop = "";
     } else {
-       qop = ap_pstrcat(r->pool, ", qop=\"", conf->qop_list[0], NULL);
+       qop = apr_pstrcat(r->pool, ", qop=\"", conf->qop_list[0], NULL);
        for (cnt=1; conf->qop_list[cnt] != NULL; cnt++)
-           qop = ap_pstrcat(r->pool, qop, ",", conf->qop_list[cnt], NULL);
-       qop = ap_pstrcat(r->pool, qop, "\"", NULL);
+           qop = apr_pstrcat(r->pool, qop, ",", conf->qop_list[cnt], NULL);
+       qop = apr_pstrcat(r->pool, qop, "\"", NULL);
     }
 
-    /* MD5-sess stuff */
-
-    if (!stale && !strcasecmp(conf->algorithm, "MD5-sess"))
-       clear_session(resp);
-
     /* Setup opaque */
 
     if (resp->opaque == NULL) {
@@ -1173,7 +1278,7 @@ static void note_digest_auth_failure(request_rec *r,
     }
 
     if (opaque[0])
-       opaque_param = ap_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
+       opaque_param = apr_pstrcat(r->pool, ", opaque=\"", opaque, "\"", NULL);
     else
        opaque_param = NULL;
 
@@ -1183,6 +1288,14 @@ static void note_digest_auth_failure(request_rec *r,
     if (resp->client && conf->nonce_lifetime == 0)
        memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
 
+    /* Setup MD5-sess stuff. Note that we just clear out the session
+     * info here, since we can't generate a new session until the request
+     * from the client comes in with the cnonce.
+     */
+
+    if (!strcasecmp(conf->algorithm, "MD5-sess"))
+       clear_session(resp);
+
     /* setup domain attribute. We want to send this attribute wherever
      * possible so that the client won't send the Authorization header
      * unneccessarily (it's usually > 200 bytes!).
@@ -1194,17 +1307,17 @@ static void note_digest_auth_failure(request_rec *r,
        domain = conf->uri_list;
     else {
        /* They didn't specify any domain, so let's guess at it */
-       domain = guess_domain(r->pool, resp->request_uri->path, r->filename,
+       domain = guess_domain(r->pool, resp->psd_request_uri->path, r->filename,
                              conf->dir_name);
        if (domain[0] == '/' && domain[1] == '\0')
            domain = NULL;      /* "/" is the default, so no need to send it */
        else
-           domain = ap_pstrcat(r->pool, ", domain=\"", domain, "\"", NULL);
+           domain = apr_pstrcat(r->pool, ", domain=\"", domain, "\"", NULL);
     }
 
-    ap_table_mergen(r->err_headers_out,
+    apr_table_mergen(r->err_headers_out,
                    r->proxyreq ? "Proxy-Authenticate" : "WWW-Authenticate",
-                   ap_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%s\", "
+                   apr_psprintf(r->pool, "Digest realm=\"%s\", nonce=\"%s\", "
                                         "algorithm=%s%s%s%s%s",
                                ap_auth_name(r), nonce, conf->algorithm,
                                opaque_param ? opaque_param : "",
@@ -1225,10 +1338,10 @@ static const char *get_hash(request_rec *r, const char *user,
     char l[MAX_STRING_LEN];
     const char *rpw;
     char *w, *x;
-    ap_status_t sts;
+    apr_status_t sts;
 
     if ((sts = ap_pcfg_openfile(&f, r->pool, auth_pwfile)) != APR_SUCCESS) {
-       ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
+       ap_log_rerror(APLOG_MARK, APLOG_ERR, sts, r,
                      "Digest: Could not open password file: %s", auth_pwfile);
        return NULL;
     }
@@ -1241,7 +1354,7 @@ static const char *get_hash(request_rec *r, const char *user,
 
        if (x && w && !strcmp(user, w) && !strcmp(realm, x)) {
            ap_cfg_closefile(f);
-           return ap_pstrdup(r->pool, rpw);
+           return apr_pstrdup(r->pool, rpw);
        }
     }
     ap_cfg_closefile(f);
@@ -1251,28 +1364,29 @@ static const char *get_hash(request_rec *r, const char *user,
 static int check_nc(const request_rec *r, const digest_header_rec *resp,
                    const digest_config_rec *conf)
 {
-    if (conf->check_nc && client_mm) {
-       unsigned long nc;
+    unsigned long nc;
+    const char *snc = resp->nonce_count;
+    char *endptr;
 
-       const char *snc = resp->nonce_count;
-       char *endptr;
+    if (!conf->check_nc || !client_shm)
+       return OK;
 
-       nc = strtol(snc, &endptr, 16);
-       if (endptr < (snc+strlen(snc)) && !ap_isspace(*endptr)) {
-           ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
-                         "Digest: invalid nc %s received - not a number", snc);
-           return !OK;
-       }
+    nc = strtol(snc, &endptr, 16);
+    if (endptr < (snc+strlen(snc)) && !apr_isspace(*endptr)) {
+       ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
+                     "Digest: invalid nc %s received - not a number", snc);
+       return !OK;
+    }
 
-       if (!resp->client)
-           return !OK;
+    if (!resp->client)
+       return !OK;
 
-       if (nc != resp->client->nonce_count) {
-           ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_DEBUG, 0, r,
-                         "nonce-count check failed: %lu != %lu", nc,
-                         resp->client->nonce_count);
-           return !OK;
-       }
+    if (nc != resp->client->nonce_count) {
+       ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
+                     "Digest: Warning, possible replay attack: nonce-count "
+                     "check failed: %lu != %lu", nc,
+                     resp->client->nonce_count);
+       return !OK;
     }
 
     return OK;
@@ -1282,6 +1396,7 @@ static int check_nonce(request_rec *r, digest_header_rec *resp,
                       const digest_config_rec *conf)
 {
     double dt;
+    int len;
     time_rec nonce_time;
     char tmp, hash[NONCE_HASH_LEN+1];
 
@@ -1290,12 +1405,12 @@ static int check_nonce(request_rec *r, digest_header_rec *resp,
                      "Digest: invalid nonce %s received - length is not %d",
                      resp->nonce, NONCE_LEN);
        note_digest_auth_failure(r, conf, resp, 1);
-       return AUTH_REQUIRED;
+       return HTTP_UNAUTHORIZED;
     }
 
     tmp = resp->nonce[NONCE_TIME_LEN];
     resp->nonce[NONCE_TIME_LEN] = '\0';
-    ap_base64decode_binary(nonce_time.arr, resp->nonce);
+    len = apr_base64_decode_binary(nonce_time.arr, resp->nonce);
     gen_nonce_hash(hash, resp->nonce, resp->opaque, r->server, conf);
     resp->nonce[NONCE_TIME_LEN] = tmp;
     resp->nonce_time = nonce_time.time;
@@ -1305,27 +1420,26 @@ static int check_nonce(request_rec *r, digest_header_rec *resp,
                      "Digest: invalid nonce %s received - hash is not %s",
                      resp->nonce, hash);
        note_digest_auth_failure(r, conf, resp, 1);
-       return AUTH_REQUIRED;
+       return HTTP_UNAUTHORIZED;
     }
 
     dt = r->request_time - nonce_time.time;
-    /* dt = difftime(r->request_time, nonce_time.time); */
     if (conf->nonce_lifetime > 0 && dt < 0) {
        ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
                      "Digest: invalid nonce %s received - user attempted "
                      "time travel", resp->nonce);
        note_digest_auth_failure(r, conf, resp, 1);
-       return AUTH_REQUIRED;
+       return HTTP_UNAUTHORIZED;
     }
 
     if (conf->nonce_lifetime > 0) {
        if (dt > conf->nonce_lifetime) {
            ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_INFO, 0,r,
-                         "Digest: user %s: nonce expired (%.2lf seconds old - max lifetime %.2lf) - sending new nonce", 
-                         r->user, ((double)dt)/1000
-                         ((double)(conf->nonce_lifetime))/1000);
+                         "Digest: user %s: nonce expired (%.2f seconds old - max lifetime %.2f) - sending new nonce", 
+                         r->user, ((double)dt)/APR_USEC_PER_SEC
+                         ((double)(conf->nonce_lifetime))/APR_USEC_PER_SEC);
            note_digest_auth_failure(r, conf, resp, 1);
-           return AUTH_REQUIRED;
+           return HTTP_UNAUTHORIZED;
        }
     }
     else if (conf->nonce_lifetime == 0 && resp->client) {
@@ -1334,7 +1448,7 @@ static int check_nonce(request_rec *r, digest_header_rec *resp,
                          "Digest: user %s: one-time-nonce mismatch - sending "
                          "new nonce", r->user);
            note_digest_auth_failure(r, conf, resp, 1);
-           return AUTH_REQUIRED;
+           return HTTP_UNAUTHORIZED;
        }
     }
     /* else (lifetime < 0) => never expires */
@@ -1344,40 +1458,43 @@ static int check_nonce(request_rec *r, digest_header_rec *resp,
 
 /* The actual MD5 code... whee */
 
+/* RFC-2069 */
 static const char *old_digest(const request_rec *r,
                              const digest_header_rec *resp, const char *ha1)
 {
     const char *ha2;
 
-    /* rfc-2069 */
-    ha2 = ap_md5(r->pool, (unsigned char *)ap_pstrcat(r->pool, r->method, ":",
+    ha2 = ap_md5(r->pool, (unsigned char *)apr_pstrcat(r->pool, r->method, ":",
                                                      resp->uri, NULL));
     return ap_md5(r->pool,
-                 (unsigned char *)ap_pstrcat(r->pool, ha1, ":", resp->nonce,
+                 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
                                              ":", ha2, NULL));
 }
 
+/* RFC-2617 */
 static const char *new_digest(const request_rec *r,
                              digest_header_rec *resp,
                              const digest_config_rec *conf)
 {
     const char *ha1, *ha2, *a2;
 
-    /* draft-ietf-http-authentication-03 */
-    if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess"))
-       ha1 = get_session(r, resp, conf);
+    if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
+       ha1 = get_session_HA1(r, resp, conf, 1);
+       if (!ha1)
+           return NULL;
+    }
     else
        ha1 = conf->ha1;
 
     if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int"))
-       a2 = ap_pstrcat(r->pool, r->method, ":", resp->uri, ":",
+       a2 = apr_pstrcat(r->pool, r->method, ":", resp->uri, ":",
                        ap_md5(r->pool, (const unsigned char*) ""), NULL); /* TBD */
     else
-       a2 = ap_pstrcat(r->pool, r->method, ":", resp->uri, NULL);
+       a2 = apr_pstrcat(r->pool, r->method, ":", resp->uri, NULL);
     ha2 = ap_md5(r->pool, (const unsigned char *)a2);
 
     return ap_md5(r->pool,
-                 (unsigned char *)ap_pstrcat(r->pool, ha1, ":", resp->nonce,
+                 (unsigned char *)apr_pstrcat(r->pool, ha1, ":", resp->nonce,
                                              ":", resp->nonce_count, ":",
                                              resp->cnonce, ":",
                                              resp->message_qop, ":", ha2,
@@ -1385,10 +1502,44 @@ static const char *new_digest(const request_rec *r,
 }
 
 
+static void copy_uri_components(uri_components *dst, uri_components *src,
+                               request_rec *r) {
+    if (src->scheme && src->scheme[0] != '\0')
+       dst->scheme = src->scheme;
+    else
+       dst->scheme = (char *) "http";
+
+    if (src->hostname && src->hostname[0] != '\0') {
+       dst->hostname = apr_pstrdup(r->pool, src->hostname);
+       ap_unescape_url(dst->hostname);
+    }
+    else
+       dst->hostname = (char *) ap_get_server_name(r);
+
+    if (src->port_str && src->port_str[0] != '\0')
+       dst->port = src->port;
+    else
+       dst->port = ap_get_server_port(r);
+
+    if (src->path && src->path[0] != '\0') {
+       dst->path = apr_pstrdup(r->pool, src->path);
+       ap_unescape_url(dst->path);
+    }
+    else
+       dst->path = src->path;
+
+    if (src->query && src->query[0] != '\0') {
+       dst->query = apr_pstrdup(r->pool, src->query);
+       ap_unescape_url(dst->query);
+    }
+    else
+       dst->query = src->query;
+}
+
 /* These functions return 0 if client is OK, and proper error status
- * if not... either AUTH_REQUIRED, if we made a check, and it failed, or
- * SERVER_ERROR, if things are so totally confused that we couldn't
- * figure out how to tell if the client is authorized or not.
+ * if not... either HTTP_UNAUTHORIZED, if we made a check, and it failed, or
+ * HTTP_INTERNAL_SERVER_ERROR, if things are so totally confused that we
+ * couldn't figure out how to tell if the client is authorized or not.
  *
  * If they return DECLINED, and all other modules also decline, that's
  * treated by the server core as a configuration error, logged and
@@ -1415,7 +1566,7 @@ static int authenticate_digest_user(request_rec *r)
     if (!ap_auth_name(r)) {
        ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
                      "Digest: need AuthName: %s", r->uri);
-       return SERVER_ERROR;
+       return HTTP_INTERNAL_SERVER_ERROR;
     }
 
 
@@ -1425,14 +1576,15 @@ static int authenticate_digest_user(request_rec *r)
     while (mainreq->main != NULL)  mainreq = mainreq->main;
     while (mainreq->prev != NULL)  mainreq = mainreq->prev;
     resp = (digest_header_rec *) ap_get_module_config(mainreq->request_config,
-                                                     &auth_digest_module);
+                                                     &digest_auth_module);
     resp->needed_auth = 1;
 
 
     /* get our conf */
 
     conf = (digest_config_rec *) ap_get_module_config(r->per_dir_config,
-                                                     &auth_digest_module);
+                                                     &digest_auth_module);
+
 
     /* check for existence and syntax of Auth header */
 
@@ -1443,11 +1595,12 @@ static int authenticate_digest_user(request_rec *r)
                          "`%s': %s", resp->scheme, r->uri);
        else if (resp->auth_hdr_sts == INVALID)
            ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
-                         "Digest: missing user, realm, nonce, uri, or digest "
-                         "in authorization header: %s", r->uri);
+                         "Digest: missing user, realm, nonce, uri, digest, "
+                         "cnonce, or nonce_count in authorization header: %s",
+                         r->uri);
        /* else (resp->auth_hdr_sts == NO_HEADER) */
        note_digest_auth_failure(r, conf, resp, 0);
-       return AUTH_REQUIRED;
+       return HTTP_UNAUTHORIZED;
     }
 
     r->user         = (char *) resp->username;
@@ -1455,15 +1608,18 @@ static int authenticate_digest_user(request_rec *r)
 
     /* check the auth attributes */
 
-    if (strcmp(resp->uri, resp->request_uri->path)) {
-       uri_components *r_uri = resp->request_uri, d_uri;
-       int port;
+    if (strcmp(resp->uri, resp->raw_request_uri)) {
+       /* Hmm, the simple match didn't work (probably a proxy modified the
+        * request-uri), so lets do a more sophisticated match
+        */
+       uri_components r_uri, d_uri;
 
+       copy_uri_components(&r_uri, resp->psd_request_uri, r);
        if (ap_parse_uri_components(r->pool, resp->uri, &d_uri) != HTTP_OK) {
            ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
                          "Digest: invalid uri <%s> in Authorization header",
                          resp->uri);
-           return BAD_REQUEST;
+           return HTTP_BAD_REQUEST;
        }
 
        if (d_uri.hostname)
@@ -1472,25 +1628,41 @@ static int authenticate_digest_user(request_rec *r)
            ap_unescape_url(d_uri.path);
        if (d_uri.query)
            ap_unescape_url(d_uri.query);
-       if (r_uri->query)
-           ap_unescape_url(r_uri->query);
-       port = ap_get_server_port(r);
 
-       if ((d_uri.hostname && d_uri.hostname[0] != '\0'
-            && strcasecmp(d_uri.hostname, ap_get_server_name(r)))
-           || (d_uri.port_str && d_uri.port != port)
+       if (r->method_number == M_CONNECT) {
+           if (strcmp(resp->uri, r_uri.hostinfo)) {
+               ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
+                             "Digest: uri mismatch - <%s> does not match "
+                             "request-uri <%s>", resp->uri, r_uri.hostinfo);
+               return HTTP_BAD_REQUEST;
+           }
+       }
+       else if (
+           /* check hostname matches, if present */
+           (d_uri.hostname && d_uri.hostname[0] != '\0'
+             && strcasecmp(d_uri.hostname, r_uri.hostname))
+           /* check port matches, if present */
+           || (d_uri.port_str && d_uri.port != r_uri.port)
+           /* check that server-port is default port if no port present */
            || (d_uri.hostname && d_uri.hostname[0] != '\0'
-               && !d_uri.port_str && port != ap_default_port(r))
-           || !d_uri.path || strcmp(d_uri.path, r_uri->path)
-           || (d_uri.query != r_uri->query
-               && (!d_uri.query || !r_uri->query
-                   || strcmp(d_uri.query, r_uri->query)))
+               && !d_uri.port_str && r_uri.port != ap_default_port(r))
+           /* check that path matches */
+           || (d_uri.path != r_uri.path
+               /* either exact match */
+               && (!d_uri.path || !r_uri.path
+                   || strcmp(d_uri.path, r_uri.path))
+               /* or '*' matches empty path in scheme://host */
+               && !(d_uri.path && !r_uri.path && resp->psd_request_uri->hostname
+                   && d_uri.path[0] == '*' && d_uri.path[1] == '\0'))
+           /* check that query matches */
+           || (d_uri.query != r_uri.query
+               && (!d_uri.query || !r_uri.query
+                   || strcmp(d_uri.query, r_uri.query)))
            ) {
            ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
                          "Digest: uri mismatch - <%s> does not match "
-                         "request-uri <%s>", resp->uri,
-                         ap_unparse_uri_components(r->pool, r_uri, 0));
-           return BAD_REQUEST;
+                         "request-uri <%s>", resp->uri, resp->raw_request_uri);
+           return HTTP_BAD_REQUEST;
        }
     }
 
@@ -1499,7 +1671,7 @@ static int authenticate_digest_user(request_rec *r)
                      "Digest: received invalid opaque - got `%s'",
                      resp->opaque);
        note_digest_auth_failure(r, conf, resp, 0);
-       return AUTH_REQUIRED;
+       return HTTP_UNAUTHORIZED;
     }
 
     if (strcmp(resp->realm, conf->realm)) {
@@ -1507,7 +1679,7 @@ static int authenticate_digest_user(request_rec *r)
                      "Digest: realm mismatch - got `%s' but expected `%s'",
                      resp->realm, conf->realm);
        note_digest_auth_failure(r, conf, resp, 0);
-       return AUTH_REQUIRED;
+       return HTTP_UNAUTHORIZED;
     }
 
     if (resp->algorithm != NULL
@@ -1517,7 +1689,7 @@ static int authenticate_digest_user(request_rec *r)
                      "Digest: unknown algorithm `%s' received: %s",
                      resp->algorithm, r->uri);
        note_digest_auth_failure(r, conf, resp, 0);
-       return AUTH_REQUIRED;
+       return HTTP_UNAUTHORIZED;
     }
 
     if (!conf->pwfile)
@@ -1528,7 +1700,7 @@ static int authenticate_digest_user(request_rec *r)
                      "Digest: user `%s' in realm `%s' not found: %s",
                      r->user, conf->realm, r->uri);
        note_digest_auth_failure(r, conf, resp, 0);
-       return AUTH_REQUIRED;
+       return HTTP_UNAUTHORIZED;
     }
 
     
@@ -1539,10 +1711,11 @@ static int authenticate_digest_user(request_rec *r)
                          "Digest: user %s: password mismatch: %s", r->user,
                          r->uri);
            note_digest_auth_failure(r, conf, resp, 0);
-           return AUTH_REQUIRED;
+           return HTTP_UNAUTHORIZED;
        }
     }
     else {
+       const char *exp_digest;
        int match = 0, idx;
        for (idx=0; conf->qop_list[idx] != NULL; idx++) {
            if (!strcasecmp(conf->qop_list[idx], resp->message_qop)) {
@@ -1558,21 +1731,26 @@ static int authenticate_digest_user(request_rec *r)
                          "Digest: invalid qop `%s' received: %s",
                          resp->message_qop, r->uri);
            note_digest_auth_failure(r, conf, resp, 0);
-           return AUTH_REQUIRED;
+           return HTTP_UNAUTHORIZED;
        }
 
-       if (strcmp(resp->digest, new_digest(r, resp, conf))) {
+       exp_digest = new_digest(r, resp, conf);
+       if (!exp_digest) {
+           /* we failed to allocate a client struct */
+           return HTTP_INTERNAL_SERVER_ERROR;
+       }
+       if (strcmp(resp->digest, exp_digest)) {
            ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
                          "Digest: user %s: password mismatch: %s", r->user,
                          r->uri);
            note_digest_auth_failure(r, conf, resp, 0);
-           return AUTH_REQUIRED;
+           return HTTP_UNAUTHORIZED;
        }
     }
 
     if (check_nc(r, resp, conf) != OK) {
        note_digest_auth_failure(r, conf, resp, 0);
-       return AUTH_REQUIRED;
+       return HTTP_UNAUTHORIZED;
     }
 
     /* Note: this check is done last so that a "stale=true" can be
@@ -1588,44 +1766,44 @@ static int authenticate_digest_user(request_rec *r)
  * Checking ID
  */
 
-static ap_table_t *groups_for_user(request_rec *r, const char *user,
+static apr_table_t *groups_for_user(request_rec *r, const char *user,
                              const char *grpfile)
 {
     configfile_t *f;
-    ap_table_t *grps = ap_make_table(r->pool, 15);
-    ap_pool_t *sp;
+    apr_table_t *grps = apr_table_make(r->pool, 15);
+    apr_pool_t *sp;
     char l[MAX_STRING_LEN];
     const char *group_name, *ll, *w;
-    ap_status_t sts;
+    apr_status_t sts;
 
     if ((sts = ap_pcfg_openfile(&f, r->pool, grpfile)) != APR_SUCCESS) {
-       ap_log_rerror(APLOG_MARK, APLOG_ERR, errno, r,
+       ap_log_rerror(APLOG_MARK, APLOG_ERR, sts, r,
                      "Digest: Could not open group file: %s", grpfile);
        return NULL;
     }
 
-    if (ap_create_pool(&sp, r->pool) != APR_SUCCESS)
+    if (apr_pool_create(&sp, r->pool) != APR_SUCCESS)
                return NULL;
 
     while (!(ap_cfg_getline(l, MAX_STRING_LEN, f))) {
        if ((l[0] == '#') || (!l[0]))
            continue;
        ll = l;
-       ap_clear_pool(sp);
+       apr_clear_pool(sp);
 
        group_name = ap_getword(sp, &ll, ':');
 
        while (ll[0]) {
            w = ap_getword_conf(sp, &ll);
            if (!strcmp(w, user)) {
-               ap_table_setn(grps, ap_pstrdup(r->pool, group_name), "in");
+               apr_table_setn(grps, apr_pstrdup(r->pool, group_name), "in");
                break;
            }
        }
     }
 
     ap_cfg_closefile(f);
-    ap_destroy_pool(sp);
+    apr_pool_destroy(sp);
     return grps;
 }
 
@@ -1634,14 +1812,14 @@ static int digest_check_auth(request_rec *r)
 {
     const digest_config_rec *conf =
                (digest_config_rec *) ap_get_module_config(r->per_dir_config,
-                                                          &auth_digest_module);
+                                                          &digest_auth_module);
     const char *user = r->user;
     int m = r->method_number;
     int method_restricted = 0;
     register int x;
     const char *t, *w;
-    ap_table_t *grpstatus;
-    const ap_array_header_t *reqs_arr;
+    apr_table_t *grpstatus;
+    const apr_array_header_t *reqs_arr;
     require_line *reqs;
 
     if (!(t = ap_auth_type(r)) || strcasecmp(t, "Digest"))
@@ -1683,7 +1861,7 @@ static int digest_check_auth(request_rec *r)
 
            while (t[0]) {
                w = ap_getword_conf(r->pool, &t);
-               if (ap_table_get(grpstatus, w))
+               if (apr_table_get(grpstatus, w))
                    return OK;
            }
        }
@@ -1704,9 +1882,9 @@ static int digest_check_auth(request_rec *r)
 
     note_digest_auth_failure(r, conf,
        (digest_header_rec *) ap_get_module_config(r->request_config,
-                                                  &auth_digest_module),
+                                                  &digest_auth_module),
        0);
-    return AUTH_REQUIRED;
+    return HTTP_UNAUTHORIZED;
 }
 
 
@@ -1715,9 +1893,9 @@ static int digest_check_auth(request_rec *r)
  */
 
 #ifdef SEND_DIGEST
-static const char *hdr(const ap_table_t *tbl, const char *name)
+static const char *hdr(const apr_table_t *tbl, const char *name)
 {
-    const char *val = ap_table_get(tbl, name);
+    const char *val = apr_table_get(tbl, name);
     if (val)
        return val;
     else
@@ -1729,10 +1907,10 @@ static int add_auth_info(request_rec *r)
 {
     const digest_config_rec *conf =
                (digest_config_rec *) ap_get_module_config(r->per_dir_config,
-                                                          &auth_digest_module);
+                                                          &digest_auth_module);
     digest_header_rec *resp =
                (digest_header_rec *) ap_get_module_config(r->request_config,
-                                                          &auth_digest_module);
+                                                          &digest_auth_module);
     const char *ai = NULL, *digest = NULL, *nextnonce = "";
 
     if (resp == NULL || !resp->needed_auth || conf == NULL)
@@ -1753,25 +1931,26 @@ static int add_auth_info(request_rec *r)
         * Content-length is never set yet when we get here, and we can't
         * calc the entity hash) it's best to just leave this #def'd out.
         */
+       char date[APR_RFC822_DATE_LEN];
+       apr_rfc822_date(date, r->request_time);
        char *entity_info =
            ap_md5(r->pool,
-                  (unsigned char *) ap_pstrcat(r->pool,
-                      ap_unparse_uri_components(r->pool,
-                                                resp->request_uri, 0), ":",
+                  (unsigned char *) apr_pstrcat(r->pool, resp->raw_request_uri,
+                      ":",
                       r->content_type ? r->content_type : ap_default_type(r), ":",
                       hdr(r->headers_out, "Content-Length"), ":",
                       r->content_encoding ? r->content_encoding : "", ":",
                       hdr(r->headers_out, "Last-Modified"), ":",
-                      r->no_cache && !ap_table_get(r->headers_out, "Expires") ?
-                           ap_gm_timestr_822(r->pool, r->request_time) :
+                      r->no_cache && !apr_table_get(r->headers_out, "Expires") ?
+                           date :
                            hdr(r->headers_out, "Expires"),
                       NULL));
        digest =
            ap_md5(r->pool,
-                  (unsigned char *)ap_pstrcat(r->pool, conf->ha1, ":",
+                  (unsigned char *)apr_pstrcat(r->pool, conf->ha1, ":",
                                               resp->nonce, ":",
                                               r->method, ":",
-                                              ap_gm_timestr_822(r->pool, r->request_time), ":",
+                                              date, ":",
                                               entity_info, ":",
                                               ap_md5(r->pool, (unsigned char *) ""), /* H(entity) - TBD */
                                               NULL));
@@ -1783,18 +1962,19 @@ static int add_auth_info(request_rec *r)
      */
     if (conf->nonce_lifetime > 0) {
        /* send nextnonce if current nonce will expire in less than 30 secs */
-       if (difftime(r->request_time, resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
-           nextnonce = ap_pstrcat(r->pool, ", nextnonce=\"",
+       if ((r->request_time - resp->nonce_time) > (conf->nonce_lifetime-NEXTNONCE_DELTA)) {
+           nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"",
                                   gen_nonce(r->pool, r->request_time,
                                             resp->opaque, r->server, conf),
                                   "\"", NULL);
-           resp->client->nonce_count = 0;
+           if (resp->client)
+               resp->client->nonce_count = 0;
        }
     }
     else if (conf->nonce_lifetime == 0 && resp->client) {
         const char *nonce = gen_nonce(r->pool, 0, resp->opaque, r->server,
                                      conf);
-       nextnonce = ap_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
+       nextnonce = apr_pstrcat(r->pool, ", nextnonce=\"", nonce, "\"", NULL);
        memcpy(resp->client->last_nonce, nonce, NONCE_LEN+1);
     }
     /* else nonce never expires, hence no nextnonce */
@@ -1806,7 +1986,7 @@ static int add_auth_info(request_rec *r)
        && resp->message_qop == NULL) {
        /* use only RFC-2069 format */
        if (digest)
-           ai = ap_pstrcat(r->pool, "digest=\"", digest, "\"", nextnonce,NULL);
+           ai = apr_pstrcat(r->pool, "digest=\"", digest, "\"", nextnonce,NULL);
        else
            ai = nextnonce;
     }
@@ -1815,20 +1995,27 @@ static int add_auth_info(request_rec *r)
 
        /* calculate rspauth attribute
         */
-       if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess"))
-           ha1 = get_session(r, resp, conf);
+       if (resp->algorithm && !strcasecmp(resp->algorithm, "MD5-sess")) {
+           ha1 = get_session_HA1(r, resp, conf, 0);
+           if (!ha1) {
+               ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, 0, r,
+                             "Digest: internal error: couldn't find session "
+                             "info for user %s", resp->username);
+               return !OK;
+           }
+       }
        else
            ha1 = conf->ha1;
 
        if (resp->message_qop && !strcasecmp(resp->message_qop, "auth-int"))
-           a2 = ap_pstrcat(r->pool, ":", resp->uri, ":",
+           a2 = apr_pstrcat(r->pool, ":", resp->uri, ":",
                            ap_md5(r->pool, (const unsigned char *) ""), NULL); /* TBD */
        else
-           a2 = ap_pstrcat(r->pool, ":", resp->uri, NULL);
+           a2 = apr_pstrcat(r->pool, ":", resp->uri, NULL);
        ha2 = ap_md5(r->pool, (const unsigned char *)a2);
 
        resp_dig = ap_md5(r->pool,
-                        (unsigned char *)ap_pstrcat(r->pool, ha1, ":",
+                        (unsigned char *)apr_pstrcat(r->pool, ha1, ":",
                                                     resp->nonce, ":",
                                                     resp->nonce_count, ":",
                                                     resp->cnonce, ":",
@@ -1838,7 +2025,7 @@ static int add_auth_info(request_rec *r)
 
        /* assemble Authentication-Info header
         */
-       ai = ap_pstrcat(r->pool,
+       ai = apr_pstrcat(r->pool,
                        "rspauth=\"", resp_dig, "\"",
                        nextnonce,
                        resp->cnonce ? ", cnonce=\"" : "",
@@ -1856,27 +2043,28 @@ static int add_auth_info(request_rec *r)
     }
 
     if (ai && ai[0])
-       ap_table_mergen(r->headers_out,
-                       r->proxyreq ? "Proxy-Authentication-Info" :
-                                     "Authentication-Info",
+       apr_table_mergen(r->headers_out,
+                       r->proxyreq ? "Proxy-Authentication-Info"
+                                   : "Authentication-Info",
                        ai);
     return OK;
 }
 
 
-static void register_hooks(void)
+static void register_hooks(apr_pool_t *p)
 {
     static const char * const cfgPost[]={ "http_core.c", NULL };
     static const char * const parsePre[]={ "mod_proxy.c", NULL };
 
-    ap_hook_post_config(initialize_module, NULL, cfgPost, 0);
-    ap_hook_post_read_request(parse_hdr_and_update_nc, parsePre, NULL, 0);
-    ap_hook_check_user_id(authenticate_digest_user, NULL, NULL, AP_HOOK_MIDDLE);
-    ap_hook_auth_checker(digest_check_auth, NULL, NULL, AP_HOOK_MIDDLE);
-    ap_hook_fixups(add_auth_info, NULL, NULL, AP_HOOK_MIDDLE);
+    ap_hook_post_config(initialize_module, NULL, cfgPost, APR_HOOK_MIDDLE);
+    ap_hook_child_init(initialize_child, NULL, NULL, APR_HOOK_MIDDLE);
+    ap_hook_post_read_request(parse_hdr_and_update_nc, parsePre, NULL, APR_HOOK_MIDDLE);
+    ap_hook_check_user_id(authenticate_digest_user, NULL, NULL, APR_HOOK_MIDDLE);
+    ap_hook_auth_checker(digest_check_auth, NULL, NULL, APR_HOOK_MIDDLE);
+    ap_hook_fixups(add_auth_info, NULL, NULL, APR_HOOK_MIDDLE);
 }
 
-module MODULE_VAR_EXPORT auth_digest_module =
+module AP_MODULE_DECLARE_DATA digest_auth_module =
 {
     STANDARD20_MODULE_STUFF,
     create_digest_dir_config,  /* dir config creater */
@@ -1884,7 +2072,6 @@ module MODULE_VAR_EXPORT auth_digest_module =
     NULL,                      /* server config */
     NULL,                      /* merge server config */
     digest_cmds,               /* command table */
-    NULL,                      /* handlers */
     register_hooks             /* register hooks */
 };