You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@httpd.apache.org by jo...@apache.org on 2017/01/31 09:52:09 UTC

svn commit: r1781045 [49/50] - in /httpd/httpd/branches/2.4.x-openssl-1.1.0-compat: ./ build/ docs/man/ docs/manual/ docs/manual/developer/ docs/manual/faq/ docs/manual/howto/ docs/manual/misc/ docs/manual/mod/ docs/manual/platform/ docs/manual/program...

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/session/mod_session_crypto.c
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/session/mod_session_crypto.c?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/session/mod_session_crypto.c (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/session/mod_session_crypto.c Tue Jan 31 09:52:02 2017
@@ -18,6 +18,7 @@
 #include "apu_version.h"
 #include "apr_base64.h"                /* for apr_base64_decode et al */
 #include "apr_lib.h"
+#include "apr_md5.h"
 #include "apr_strings.h"
 #include "http_log.h"
 #include "http_core.h"
@@ -57,6 +58,146 @@ typedef struct {
     int library_set;
 } session_crypto_conf;
 
+/* Wrappers around apr_siphash24() and apr_crypto_equals(),
+ * available in APU-1.6/APR-2.0 only.
+ */
+#if APU_MAJOR_VERSION > 1 || (APU_MAJOR_VERSION == 1 && APU_MINOR_VERSION >= 6)
+
+#include "apr_siphash.h"
+
+#define AP_SIPHASH_DSIZE    APR_SIPHASH_DSIZE
+#define AP_SIPHASH_KSIZE    APR_SIPHASH_KSIZE
+#define ap_siphash24_auth   apr_siphash24_auth
+
+#define ap_crypto_equals    apr_crypto_equals
+
+#else
+
+#define AP_SIPHASH_DSIZE    8
+#define AP_SIPHASH_KSIZE    16
+
+#define ROTL64(x, n) (((x) << (n)) | ((x) >> (64 - (n))))
+
+#define U8TO64_LE(p) \
+    (((apr_uint64_t)((p)[0])      ) | \
+     ((apr_uint64_t)((p)[1]) <<  8) | \
+     ((apr_uint64_t)((p)[2]) << 16) | \
+     ((apr_uint64_t)((p)[3]) << 24) | \
+     ((apr_uint64_t)((p)[4]) << 32) | \
+     ((apr_uint64_t)((p)[5]) << 40) | \
+     ((apr_uint64_t)((p)[6]) << 48) | \
+     ((apr_uint64_t)((p)[7]) << 56))
+
+#define U64TO8_LE(p, v) \
+do { \
+    (p)[0] = (unsigned char)((v)      ); \
+    (p)[1] = (unsigned char)((v) >>  8); \
+    (p)[2] = (unsigned char)((v) >> 16); \
+    (p)[3] = (unsigned char)((v) >> 24); \
+    (p)[4] = (unsigned char)((v) >> 32); \
+    (p)[5] = (unsigned char)((v) >> 40); \
+    (p)[6] = (unsigned char)((v) >> 48); \
+    (p)[7] = (unsigned char)((v) >> 56); \
+} while (0)
+
+#define SIPROUND() \
+do { \
+    v0 += v1; v1=ROTL64(v1,13); v1 ^= v0; v0=ROTL64(v0,32); \
+    v2 += v3; v3=ROTL64(v3,16); v3 ^= v2; \
+    v0 += v3; v3=ROTL64(v3,21); v3 ^= v0; \
+    v2 += v1; v1=ROTL64(v1,17); v1 ^= v2; v2=ROTL64(v2,32); \
+} while(0)
+
+static apr_uint64_t ap_siphash24(const void *src, apr_size_t len,
+                                 const unsigned char key[AP_SIPHASH_KSIZE])
+{
+    const unsigned char *ptr, *end;
+    apr_uint64_t v0, v1, v2, v3, m;
+    apr_uint64_t k0, k1;
+    unsigned int rem;
+
+    k0 = U8TO64_LE(key + 0);
+    k1 = U8TO64_LE(key + 8);
+    v3 = k1 ^ (apr_uint64_t)0x7465646279746573ULL;
+    v2 = k0 ^ (apr_uint64_t)0x6c7967656e657261ULL;
+    v1 = k1 ^ (apr_uint64_t)0x646f72616e646f6dULL;
+    v0 = k0 ^ (apr_uint64_t)0x736f6d6570736575ULL;
+
+    rem = (unsigned int)(len & 0x7);
+    for (ptr = src, end = ptr + len - rem; ptr < end; ptr += 8) {
+        m = U8TO64_LE(ptr);
+        v3 ^= m;
+        SIPROUND();
+        SIPROUND();
+        v0 ^= m;
+    }
+    m = (apr_uint64_t)(len & 0xff) << 56;
+    switch (rem) {
+        case 7: m |= (apr_uint64_t)ptr[6] << 48;
+        case 6: m |= (apr_uint64_t)ptr[5] << 40;
+        case 5: m |= (apr_uint64_t)ptr[4] << 32;
+        case 4: m |= (apr_uint64_t)ptr[3] << 24;
+        case 3: m |= (apr_uint64_t)ptr[2] << 16;
+        case 2: m |= (apr_uint64_t)ptr[1] << 8;
+        case 1: m |= (apr_uint64_t)ptr[0];
+        case 0: break;
+    }
+    v3 ^= m;
+    SIPROUND();
+    SIPROUND();
+    v0 ^= m;
+
+    v2 ^= 0xff;
+    SIPROUND();
+    SIPROUND();
+    SIPROUND();
+    SIPROUND();
+
+    return v0 ^ v1 ^ v2 ^ v3;
+}
+
+static void ap_siphash24_auth(unsigned char out[AP_SIPHASH_DSIZE],
+                              const void *src, apr_size_t len,
+                              const unsigned char key[AP_SIPHASH_KSIZE])
+{
+    apr_uint64_t h;
+    h = ap_siphash24(src, len, key);
+    U64TO8_LE(out, h);
+}
+
+static int ap_crypto_equals(const void *buf1, const void *buf2,
+                            apr_size_t size)
+{
+    const unsigned char *p1 = buf1;
+    const unsigned char *p2 = buf2;
+    unsigned char diff = 0;
+    apr_size_t i;
+
+    for (i = 0; i < size; ++i) {
+        diff |= p1[i] ^ p2[i];
+    }
+
+    return 1 & ((diff - 1) >> 8);
+}
+
+#endif
+
+static void compute_auth(const void *src, apr_size_t len,
+                         const char *passphrase, apr_size_t passlen,
+                         unsigned char auth[AP_SIPHASH_DSIZE])
+{
+    unsigned char key[APR_MD5_DIGESTSIZE];
+
+    /* XXX: if we had a way to get the raw bytes from an apr_crypto_key_t
+     *      we could use them directly (not available in APR-1.5.x).
+     * MD5 is 128bit too, so use it to get a suitable siphash key
+     * from the passphrase.
+     */
+    apr_md5(key, passphrase, passlen);
+
+    ap_siphash24_auth(auth, src, len, key);
+}
+
 /**
  * Initialise the encryption as per the current config.
  *
@@ -128,21 +269,14 @@ static apr_status_t encrypt_string(reque
     apr_crypto_block_t *block = NULL;
     unsigned char *encrypt = NULL;
     unsigned char *combined = NULL;
-    apr_size_t encryptlen, tlen;
+    apr_size_t encryptlen, tlen, combinedlen;
     char *base64;
     apr_size_t blockSize = 0;
     const unsigned char *iv = NULL;
     apr_uuid_t salt;
     apr_crypto_block_key_type_e *cipher;
     const char *passphrase;
-
-    /* by default, return an empty string */
-    *out = "";
-
-    /* don't attempt to encrypt an empty string, trying to do so causes a segfault */
-    if (!in || !*in) {
-        return APR_SUCCESS;
-    }
+    apr_size_t passlen;
 
     /* use a uuid as a salt value, and prepend it to our result */
     apr_uuid_get(&salt);
@@ -152,9 +286,9 @@ static apr_status_t encrypt_string(reque
     }
 
     /* encrypt using the first passphrase in the list */
-    passphrase = APR_ARRAY_IDX(dconf->passphrases, 0, char *);
-    res = apr_crypto_passphrase(&key, &ivSize, passphrase,
-            strlen(passphrase),
+    passphrase = APR_ARRAY_IDX(dconf->passphrases, 0, const char *);
+    passlen = strlen(passphrase);
+    res = apr_crypto_passphrase(&key, &ivSize, passphrase, passlen,
             (unsigned char *) (&salt), sizeof(apr_uuid_t),
             *cipher, APR_MODE_CBC, 1, 4096, f, r->pool);
     if (APR_STATUS_IS_ENOKEY(res)) {
@@ -183,8 +317,9 @@ static apr_status_t encrypt_string(reque
     }
 
     /* encrypt the given string */
-    res = apr_crypto_block_encrypt(&encrypt, &encryptlen, (unsigned char *)in,
-            strlen(in), block);
+    res = apr_crypto_block_encrypt(&encrypt, &encryptlen,
+                                   (const unsigned char *)in, strlen(in),
+                                   block);
     if (APR_SUCCESS != res) {
         ap_log_rerror(APLOG_MARK, APLOG_ERR, res, r, APLOGNO(01830)
                 "apr_crypto_block_encrypt failed");
@@ -198,18 +333,20 @@ static apr_status_t encrypt_string(reque
     }
     encryptlen += tlen;
 
-    /* prepend the salt and the iv to the result */
-    combined = apr_palloc(r->pool, ivSize + encryptlen + sizeof(apr_uuid_t));
-    memcpy(combined, &salt, sizeof(apr_uuid_t));
-    memcpy(combined + sizeof(apr_uuid_t), iv, ivSize);
-    memcpy(combined + sizeof(apr_uuid_t) + ivSize, encrypt, encryptlen);
-
-    /* base64 encode the result */
-    base64 = apr_palloc(r->pool, apr_base64_encode_len(ivSize + encryptlen +
-                    sizeof(apr_uuid_t) + 1)
-            * sizeof(char));
-    apr_base64_encode(base64, (const char *) combined,
-            ivSize + encryptlen + sizeof(apr_uuid_t));
+    /* prepend the salt and the iv to the result (keep room for the MAC) */
+    combinedlen = AP_SIPHASH_DSIZE + sizeof(apr_uuid_t) + ivSize + encryptlen;
+    combined = apr_palloc(r->pool, combinedlen);
+    memcpy(combined + AP_SIPHASH_DSIZE, &salt, sizeof(apr_uuid_t));
+    memcpy(combined + AP_SIPHASH_DSIZE + sizeof(apr_uuid_t), iv, ivSize);
+    memcpy(combined + AP_SIPHASH_DSIZE + sizeof(apr_uuid_t) + ivSize,
+           encrypt, encryptlen);
+    /* authenticate the whole salt+IV+ciphertext with a leading MAC */
+    compute_auth(combined + AP_SIPHASH_DSIZE, combinedlen - AP_SIPHASH_DSIZE,
+                 passphrase, passlen, combined);
+
+    /* base64 encode the result (APR handles the trailing '\0') */
+    base64 = apr_palloc(r->pool, apr_base64_encode_len(combinedlen));
+    apr_base64_encode(base64, (const char *) combined, combinedlen);
     *out = base64;
 
     return res;
@@ -234,6 +371,7 @@ static apr_status_t decrypt_string(reque
     char *decoded;
     apr_size_t blockSize = 0;
     apr_crypto_block_key_type_e *cipher;
+    unsigned char auth[AP_SIPHASH_DSIZE];
     int i = 0;
 
     /* strip base64 from the string */
@@ -241,6 +379,13 @@ static apr_status_t decrypt_string(reque
     decodedlen = apr_base64_decode(decoded, in);
     decoded[decodedlen] = '\0';
 
+    /* sanity check - decoded too short? */
+    if (decodedlen < (AP_SIPHASH_DSIZE + sizeof(apr_uuid_t))) {
+        ap_log_rerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, r, APLOGNO()
+                "too short to decrypt, aborting");
+        return APR_ECRYPT;
+    }
+
     res = crypt_init(r, f, &cipher, dconf);
     if (res != APR_SUCCESS) {
         return res;
@@ -249,14 +394,25 @@ static apr_status_t decrypt_string(reque
     /* try each passphrase in turn */
     for (; i < dconf->passphrases->nelts; i++) {
         const char *passphrase = APR_ARRAY_IDX(dconf->passphrases, i, char *);
-        apr_size_t len = decodedlen;
-        char *slider = decoded;
+        apr_size_t passlen = strlen(passphrase);
+        apr_size_t len = decodedlen - AP_SIPHASH_DSIZE;
+        unsigned char *slider = (unsigned char *)decoded + AP_SIPHASH_DSIZE;
+
+        /* Verify authentication of the whole salt+IV+ciphertext by computing
+         * the MAC and comparing it (timing safe) with the one in the payload.
+         */
+        compute_auth(slider, len, passphrase, passlen, auth);
+        if (!ap_crypto_equals(auth, decoded, AP_SIPHASH_DSIZE)) {
+            ap_log_rerror(APLOG_MARK, APLOG_DEBUG, res, r, APLOGNO()
+                    "auth does not match, skipping");
+            continue;
+        }
 
         /* encrypt using the first passphrase in the list */
-        res = apr_crypto_passphrase(&key, &ivSize, passphrase,
-                strlen(passphrase),
-                (unsigned char *)decoded, sizeof(apr_uuid_t),
-                *cipher, APR_MODE_CBC, 1, 4096, f, r->pool);
+        res = apr_crypto_passphrase(&key, &ivSize, passphrase, passlen,
+                                    slider, sizeof(apr_uuid_t),
+                                    *cipher, APR_MODE_CBC, 1, 4096,
+                                    f, r->pool);
         if (APR_STATUS_IS_ENOKEY(res)) {
             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, res, r, APLOGNO(01832)
                     "the passphrase '%s' was empty", passphrase);
@@ -279,7 +435,7 @@ static apr_status_t decrypt_string(reque
         }
 
         /* sanity check - decoded too short? */
-        if (decodedlen < (sizeof(apr_uuid_t) + ivSize)) {
+        if (len < (sizeof(apr_uuid_t) + ivSize)) {
             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, r, APLOGNO(01836)
                     "too short to decrypt, skipping");
             res = APR_ECRYPT;
@@ -290,8 +446,8 @@ static apr_status_t decrypt_string(reque
         slider += sizeof(apr_uuid_t);
         len -= sizeof(apr_uuid_t);
 
-        res = apr_crypto_block_decrypt_init(&block, &blockSize, (unsigned char *)slider, key,
-                r->pool);
+        res = apr_crypto_block_decrypt_init(&block, &blockSize, slider, key,
+                                            r->pool);
         if (APR_SUCCESS != res) {
             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, res, r, APLOGNO(01837)
                     "apr_crypto_block_decrypt_init failed");
@@ -304,7 +460,7 @@ static apr_status_t decrypt_string(reque
 
         /* decrypt the given string */
         res = apr_crypto_block_decrypt(&decrypted, &decryptedlen,
-                (unsigned char *)slider, len, block);
+                                       slider, len, block);
         if (res) {
             ap_log_rerror(APLOG_MARK, APLOG_DEBUG, res, r, APLOGNO(01838)
                     "apr_crypto_block_decrypt failed");

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_engine_kernel.c
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_engine_kernel.c?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_engine_kernel.c (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_engine_kernel.c Tue Jan 31 09:52:02 2017
@@ -886,7 +886,14 @@ int ssl_hook_Access(request_rec *r)
 
             cert = SSL_get_peer_certificate(ssl);
 
-            if (!cert_stack && cert) {
+            if (!cert_stack || (sk_X509_num(cert_stack) == 0)) {
+                if (!cert) {
+                    ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02222)
+                                  "Cannot find peer certificate chain");
+
+                    return HTTP_FORBIDDEN;
+                }
+
                 /* client cert is in the session cache, but there is
                  * no chain, since ssl3_get_client_certificate()
                  * sk_X509_shift-ed the peer cert out of the chain.
@@ -896,13 +903,6 @@ int ssl_hook_Access(request_rec *r)
                 sk_X509_push(cert_stack, cert);
             }
 
-            if (!cert_stack || (sk_X509_num(cert_stack) == 0)) {
-                ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(02222)
-                              "Cannot find peer certificate chain");
-
-                return HTTP_FORBIDDEN;
-            }
-
             if (!(cert_store ||
                   (cert_store = SSL_CTX_get_cert_store(ctx))))
             {

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_private.h
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_private.h?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_private.h (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_private.h Tue Jan 31 09:52:02 2017
@@ -57,7 +57,7 @@
 /* The #ifdef macros are only defined AFTER including the above
  * therefore we cannot include these system files at the top  :-(
  */
-#ifdef APR_HAVE_STDLIB_H
+#if APR_HAVE_STDLIB_H
 #include <stdlib.h>
 #endif
 #if APR_HAVE_SYS_TIME_H

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_util_stapling.c
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_util_stapling.c?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_util_stapling.c (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/modules/ssl/ssl_util_stapling.c Tue Jan 31 09:52:02 2017
@@ -690,7 +690,7 @@ static int get_and_check_cached_response
                                          OCSP_RESPONSE **rsp, BOOL *pok,
                                          certinfo *cinf, apr_pool_t *p)
 {
-    BOOL ok;
+    BOOL ok = FALSE;
     int rv;
 
     AP_DEBUG_ASSERT(*rsp == NULL);

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/os/win32/BaseAddr.ref
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/os/win32/BaseAddr.ref?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/os/win32/BaseAddr.ref (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/os/win32/BaseAddr.ref Tue Jan 31 09:52:02 2017
@@ -128,3 +128,4 @@ mod_optional_hook_import.so 0x70BE0000
 mod_authnz_fcgi.so          0x70BF0000    0x00020000
 mod_http2.so                0x70C10000    0x00030000
 mod_proxy_http2.so          0x70C40000    0x00020000
+mod_proxy_hcheck.so         0x70C60000    0x00020000

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/core.c
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/core.c?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/core.c (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/core.c Tue Jan 31 09:52:02 2017
@@ -519,6 +519,15 @@ static void *merge_core_server_configs(a
     if (virt->trace_enable != AP_TRACE_UNSET)
         conf->trace_enable = virt->trace_enable;
 
+    if (virt->http09_enable != AP_HTTP09_UNSET)
+        conf->http09_enable = virt->http09_enable;
+
+    if (virt->http_conformance != AP_HTTP_CONFORMANCE_UNSET)
+        conf->http_conformance = virt->http_conformance;
+
+    if (virt->http_methods != AP_HTTP_METHODS_UNSET)
+        conf->http_methods = virt->http_methods;
+
     /* no action for virt->accf_map, not allowed per-vhost */
 
     if (virt->protocol)
@@ -2340,7 +2349,7 @@ static const char *dirsection(cmd_parms
             return "Regex could not be compiled";
         }
     }
-    else if (!strcmp(cmd->path, "/") == 0)
+    else if (strcmp(cmd->path, "/") != 0)
     {
         char *newpath;
 
@@ -3895,6 +3904,57 @@ static const char *set_protocols_honor_o
     return NULL;
 }
 
+static const char *set_http_protocol_options(cmd_parms *cmd, void *dummy,
+                                             const char *arg)
+{
+    core_server_config *conf =
+        ap_get_core_module_config(cmd->server->module_config);
+
+    if (strcasecmp(arg, "allow0.9") == 0)
+        conf->http09_enable |= AP_HTTP09_ENABLE;
+    else if (strcasecmp(arg, "require1.0") == 0)
+        conf->http09_enable |= AP_HTTP09_DISABLE;
+    else if (strcasecmp(arg, "strict") == 0)
+        conf->http_conformance |= AP_HTTP_CONFORMANCE_STRICT;
+    else if (strcasecmp(arg, "unsafe") == 0)
+        conf->http_conformance |= AP_HTTP_CONFORMANCE_UNSAFE;
+    else if (strcasecmp(arg, "registeredmethods") == 0)
+        conf->http_methods |= AP_HTTP_METHODS_REGISTERED;
+    else if (strcasecmp(arg, "lenientmethods") == 0)
+        conf->http_methods |= AP_HTTP_METHODS_LENIENT;
+    else
+        return "HttpProtocolOptions accepts "
+               "'Unsafe' or 'Strict' (default), "
+               "'RegisteredMethods' or 'LenientMethods' (default), and "
+               "'Require1.0' or 'Allow0.9' (default)";
+
+    if ((conf->http09_enable & AP_HTTP09_ENABLE)
+            && (conf->http09_enable & AP_HTTP09_DISABLE))
+        return "HttpProtocolOptions 'Allow0.9' and 'Require1.0'"
+               " are mutually exclusive";
+
+    if ((conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT)
+            && (conf->http_conformance & AP_HTTP_CONFORMANCE_UNSAFE))
+        return "HttpProtocolOptions 'Strict' and 'Unsafe'"
+               " are mutually exclusive";
+
+    if ((conf->http_methods & AP_HTTP_METHODS_REGISTERED)
+            && (conf->http_methods & AP_HTTP_METHODS_LENIENT))
+        return "HttpProtocolOptions 'RegisteredMethods' and 'LenientMethods'"
+               " are mutually exclusive";
+
+    return NULL;
+}
+
+static const char *set_http_method(cmd_parms *cmd, void *conf, const char *arg)
+{
+    const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+    if (err != NULL)
+        return err;
+    ap_method_register(cmd->pool, arg);
+    return NULL;
+}
+
 static apr_hash_t *errorlog_hash;
 
 static int log_constant_item(const ap_errorlog_info *info, const char *arg,
@@ -4419,6 +4479,12 @@ AP_INIT_ITERATE("Protocols", set_protoco
 AP_INIT_TAKE1("ProtocolsHonorOrder", set_protocols_honor_order, NULL, RSRC_CONF,
               "'off' (default) or 'on' to respect given order of protocols, "
               "by default the client specified order determines selection"),
+AP_INIT_ITERATE("HttpProtocolOptions", set_http_protocol_options, NULL, RSRC_CONF,
+                "'Allow0.9' or 'Require1.0' (default); "
+                "'RegisteredMethods' or 'LenientMethods' (default); "
+                "'Unsafe' or 'Strict' (default). Sets HTTP acceptance rules"),
+AP_INIT_ITERATE("RegisterHttpMethod", set_http_method, NULL, RSRC_CONF,
+                "Registers non-standard HTTP methods"),
 { NULL }
 };
 

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/gen_test_char.c
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/gen_test_char.c?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/gen_test_char.c (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/gen_test_char.c Tue Jan 31 09:52:02 2017
@@ -16,11 +16,11 @@
 
 #ifdef CROSS_COMPILE
 
+#include <ctype.h>
 #define apr_isalnum(c) (isalnum(((unsigned char)(c))))
 #define apr_isalpha(c) (isalpha(((unsigned char)(c))))
 #define apr_iscntrl(c) (iscntrl(((unsigned char)(c))))
 #define apr_isprint(c) (isprint(((unsigned char)(c))))
-#include <ctype.h>
 #define APR_HAVE_STDIO_H 1
 #define APR_HAVE_STRING_H 1
 
@@ -52,11 +52,13 @@
 #define T_ESCAPE_LOGITEM      (0x10)
 #define T_ESCAPE_FORENSIC     (0x20)
 #define T_ESCAPE_URLENCODED   (0x40)
+#define T_HTTP_CTRLS          (0x80)
+#define T_VCHAR_OBSTEXT      (0x100)
 
 int main(int argc, char *argv[])
 {
     unsigned c;
-    unsigned char flags;
+    unsigned short flags;
 
     printf("/* this file is automatically generated by gen_test_char, "
            "do not edit */\n"
@@ -67,19 +69,23 @@ int main(int argc, char *argv[])
            "#define T_ESCAPE_LOGITEM       (%u)\n"
            "#define T_ESCAPE_FORENSIC      (%u)\n"
            "#define T_ESCAPE_URLENCODED    (%u)\n"
+           "#define T_HTTP_CTRLS           (%u)\n"
+           "#define T_VCHAR_OBSTEXT        (%u)\n"
            "\n"
-           "static const unsigned char test_char_table[256] = {",
+           "static const unsigned short test_char_table[256] = {",
            T_ESCAPE_SHELL_CMD,
            T_ESCAPE_PATH_SEGMENT,
            T_OS_ESCAPE_PATH,
            T_HTTP_TOKEN_STOP,
            T_ESCAPE_LOGITEM,
            T_ESCAPE_FORENSIC,
-           T_ESCAPE_URLENCODED);
+           T_ESCAPE_URLENCODED,
+           T_HTTP_CTRLS,
+           T_VCHAR_OBSTEXT);
 
     for (c = 0; c < 256; ++c) {
         flags = 0;
-        if (c % 20 == 0)
+        if (c % 8 == 0)
             printf("\n    ");
 
         /* escape_shell_cmd */
@@ -107,7 +113,7 @@ int main(int argc, char *argv[])
             flags |= T_ESCAPE_PATH_SEGMENT;
         }
 
-        if (!apr_isalnum(c) && !strchr("$-_.+!*'(),:@&=/~", c)) {
+        if (!apr_isalnum(c) && !strchr("$-_.+!*'(),:;@&=/~", c)) {
             flags |= T_OS_ESCAPE_PATH;
         }
 
@@ -115,11 +121,32 @@ int main(int argc, char *argv[])
             flags |= T_ESCAPE_URLENCODED;
         }
 
-        /* these are the "tspecials" (RFC2068) or "separators" (RFC2616) */
-        if (c && (apr_iscntrl(c) || strchr(" \t()<>@,;:\\\"/[]?={}", c))) {
+        /* Stop for any non-'token' character, including ctrls, obs-text,
+         * and "tspecials" (RFC2068) a.k.a. "separators" (RFC2616), which
+         * is easer to express as characters remaining in the ASCII token set
+         */
+        if (!c || !(apr_isalnum(c) || strchr("!#$%&'*+-.^_`|~", c))) {
             flags |= T_HTTP_TOKEN_STOP;
         }
 
+        /* Catch CTRLs other than VCHAR, HT and SP, and obs-text (RFC7230 3.2)
+         * This includes only the C0 plane, not C1 (which is obs-text itself.)
+         * XXX: We should verify that all ASCII C0 ctrls/DEL corresponding to
+         * the current EBCDIC translation are captured, and ASCII C1 ctrls
+         * corresponding are all permitted (as they fall under obs-text rule)
+         */
+        if (!c || (apr_iscntrl(c) && c != '\t')) {
+            flags |= T_HTTP_CTRLS;
+        }
+
+        /* From RFC3986, the specific sets of gen-delims, sub-delims (2.2),
+         * and unreserved (2.3) that are possible somewhere within a URI.
+         * Spec requires all others to be %XX encoded, including obs-text.
+         */
+        if (c && !apr_iscntrl(c) && c != ' ') {
+            flags |= T_VCHAR_OBSTEXT;
+        }
+
         /* For logging, escape all control characters,
          * double quotes (because they delimit the request in the log file)
          * backslashes (because we use backslash for escaping)
@@ -137,7 +164,7 @@ int main(int argc, char *argv[])
             flags |= T_ESCAPE_FORENSIC;
         }
 
-        printf("%u%c", flags, (c < 255) ? ',' : ' ');
+        printf("0x%03x%c", flags, (c < 255) ? ',' : ' ');
     }
 
     printf("\n};\n");

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/event.c
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/event.c?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/event.c (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/event.c Tue Jan 31 09:52:02 2017
@@ -160,15 +160,18 @@
 #endif
 #define WORKER_FACTOR_SCALE   16  /* scale factor to allow fractional values */
 static unsigned int worker_factor = DEFAULT_WORKER_FACTOR * WORKER_FACTOR_SCALE;
+    /* AsyncRequestWorkerFactor * 16 */
 
-static int threads_per_child = 0;   /* Worker threads per child */
-static int ap_daemons_to_start = 0;
-static int min_spare_threads = 0;
-static int max_spare_threads = 0;
-static int ap_daemons_limit = 0;
-static int max_workers = 0;
-static int server_limit = 0;
-static int thread_limit = 0;
+static int threads_per_child = 0;           /* ThreadsPerChild */
+static int ap_daemons_to_start = 0;         /* StartServers */
+static int min_spare_threads = 0;           /* MinSpareThreads */
+static int max_spare_threads = 0;           /* MaxSpareThreads */
+static int active_daemons_limit = 0;        /* MaxRequestWorkers / ThreadsPerChild */
+static int active_daemons = 0;              /* workers that still active, i.e. are
+                                               not shutting down gracefully */
+static int max_workers = 0;                 /* MaxRequestWorkers */
+static int server_limit = 0;                /* ServerLimit */
+static int thread_limit = 0;                /* ThreadLimit */
 static int had_healthy_child = 0;
 static int dying = 0;
 static int workers_may_exit = 0;
@@ -181,6 +184,8 @@ static apr_uint32_t connection_count = 0
 static apr_uint32_t lingering_count = 0;    /* Number of connections in lingering close */
 static apr_uint32_t suspended_count = 0;    /* Number of suspended connections */
 static apr_uint32_t clogged_count = 0;      /* Number of threads processing ssl conns */
+static apr_uint32_t threads_shutdown = 0;   /* Number of threads that have shutdown
+                                               early during graceful termination */
 static int resource_shortage = 0;
 static fd_queue_t *worker_queue;
 static fd_queue_info_t *worker_queue_info;
@@ -288,9 +293,8 @@ static apr_pollset_t *event_pollset;
 /* The structure used to pass unique initialization info to each thread */
 typedef struct
 {
-    int pid;
-    int tid;
-    int sd;
+    int pslot;  /* process slot */
+    int tslot;  /* worker slot of the thread */
 } proc_info;
 
 /* Structure used to pass information to the thread responsible for
@@ -335,6 +339,14 @@ typedef struct event_retained_data {
      * scoreboard.
      */
     int max_daemons_limit;
+
+    /*
+     * All running workers, active and shutting down, including those that
+     * may be left from before a graceful restart.
+     * Not kept up-to-date when shutdown is pending.
+     */
+    int total_daemons;
+
     /*
      * idle_spawn_rate is the number of children that will be spawned on the
      * next maintenance cycle if there aren't enough idle servers.  It is
@@ -548,7 +560,7 @@ static int event_query(int query_code, i
         *result = ap_max_requests_per_child;
         break;
     case AP_MPMQ_MAX_DAEMONS:
-        *result = ap_daemons_limit;
+        *result = active_daemons_limit;
         break;
     case AP_MPMQ_MPM_STATE:
         *result = mpm_state;
@@ -585,27 +597,6 @@ static void event_note_child_started(int
                         retained->my_generation, slot, MPM_CHILD_STARTED);
 }
 
-static void event_note_child_lost_slot(int slot, pid_t newpid)
-{
-    ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(00458)
-                 "pid %" APR_PID_T_FMT " taking over scoreboard slot from "
-                 "%" APR_PID_T_FMT "%s",
-                 newpid,
-                 ap_scoreboard_image->parent[slot].pid,
-                 ap_scoreboard_image->parent[slot].quiescing ?
-                 " (quiescing)" : "");
-    ap_run_child_status(ap_server_conf,
-                        ap_scoreboard_image->parent[slot].pid,
-                        ap_scoreboard_image->parent[slot].generation,
-                        slot, MPM_CHILD_LOST_SLOT);
-    /* 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_register_extra_mpm_process(ap_scoreboard_image->parent[slot].pid,
-                                  ap_scoreboard_image->parent[slot].generation);
-}
-
 static const char *event_get_name(void)
 {
     return "event";
@@ -911,6 +902,8 @@ static int start_lingering_close_nonbloc
         || apr_socket_shutdown(csd, APR_SHUTDOWN_WRITE) != APR_SUCCESS) {
         apr_socket_close(csd);
         ap_push_pool(worker_queue_info, cs->p);
+        if (dying)
+            ap_queue_interrupt_one(worker_queue);
         return 0;
     }
     return start_lingering_close_common(cs, 0);
@@ -934,6 +927,8 @@ static int stop_lingering_close(event_co
         AP_DEBUG_ASSERT(0);
     }
     ap_push_pool(worker_queue_info, cs->p);
+    if (dying)
+        ap_queue_interrupt_one(worker_queue);
     return 0;
 }
 
@@ -1219,6 +1214,9 @@ static void close_listeners(int process_
         }
         /* wake up the main thread */
         kill(ap_my_pid, SIGTERM);
+
+        ap_free_idle_pools(worker_queue_info);
+        ap_queue_interrupt_all(worker_queue);
     }
 }
 
@@ -1439,6 +1437,8 @@ static void process_lingering_close(even
     TO_QUEUE_ELEM_INIT(cs);
 
     ap_push_pool(worker_queue_info, cs->p);
+    if (dying)
+        ap_queue_interrupt_one(worker_queue);
 }
 
 /* call 'func' for all elements of 'q' with timeout less than 'timeout_time'.
@@ -1518,7 +1518,7 @@ static void * APR_THREAD_FUNC listener_t
     timer_event_t *te;
     apr_status_t rc;
     proc_info *ti = dummy;
-    int process_slot = ti->pid;
+    int process_slot = ti->pslot;
     apr_pool_t *tpool = apr_thread_pool_get(thd);
     void *csd = NULL;
     apr_pool_t *ptrans;         /* Pool for per-transaction stuff */
@@ -1584,6 +1584,12 @@ static void * APR_THREAD_FUNC listener_t
                              *keepalive_q->total,
                              apr_atomic_read32(&lingering_count),
                              apr_atomic_read32(&suspended_count));
+                if (dying) {
+                    ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, ap_server_conf,
+                                 "%u/%u workers shutdown",
+                                 apr_atomic_read32(&threads_shutdown),
+                                 threads_per_child);
+                }
                 apr_thread_mutex_unlock(timeout_mutex);
             }
         }
@@ -1818,11 +1824,12 @@ static void * APR_THREAD_FUNC listener_t
             /* If all workers are busy, we kill older keep-alive connections so that they
              * may connect to another process.
              */
-            if (workers_were_busy && *keepalive_q->total) {
-                ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
-                             "All workers are busy, will close %d keep-alive "
-                             "connections",
-                             *keepalive_q->total);
+            if ((workers_were_busy || dying) && *keepalive_q->total) {
+                if (!dying)
+                    ap_log_error(APLOG_MARK, APLOG_TRACE1, 0, ap_server_conf,
+                                 "All workers are busy, will close %d keep-alive "
+                                 "connections",
+                                 *keepalive_q->total);
                 process_timeout_queue(keepalive_q, 0,
                                       start_lingering_close_nonblocking);
             }
@@ -1869,6 +1876,34 @@ static void * APR_THREAD_FUNC listener_t
     return NULL;
 }
 
+/*
+ * During graceful shutdown, if there are more running worker threads than
+ * open connections, exit one worker thread.
+ *
+ * return 1 if thread should exit, 0 if it should continue running.
+ */
+static int worker_thread_should_exit_early(void)
+{
+    for (;;) {
+        apr_uint32_t conns = apr_atomic_read32(&connection_count);
+        apr_uint32_t dead = apr_atomic_read32(&threads_shutdown);
+        apr_uint32_t newdead;
+
+        AP_DEBUG_ASSERT(dead <= threads_per_child);
+        if (conns >= threads_per_child - dead)
+            return 0;
+
+        newdead = dead + 1;
+        if (apr_atomic_cas32(&threads_shutdown, newdead, dead) == dead) {
+            /*
+             * No other thread has exited in the mean time, safe to exit
+             * this one.
+             */
+            return 1;
+        }
+    }
+}
+
 /* XXX For ungraceful termination/restart, we definitely don't want to
  *     wait for active connections to finish but we may want to wait
  *     for idle workers to get out of the queue code and release mutexes,
@@ -1879,8 +1914,8 @@ static void * APR_THREAD_FUNC listener_t
 static void *APR_THREAD_FUNC worker_thread(apr_thread_t * thd, void *dummy)
 {
     proc_info *ti = dummy;
-    int process_slot = ti->pid;
-    int thread_slot = ti->tid;
+    int process_slot = ti->pslot;
+    int thread_slot = ti->tslot;
     apr_socket_t *csd = NULL;
     event_conn_state_t *cs;
     apr_pool_t *ptrans;         /* Pool for per-transaction stuff */
@@ -1916,6 +1951,9 @@ static void *APR_THREAD_FUNC worker_thre
         if (workers_may_exit) {
             break;
         }
+        if (dying && worker_thread_should_exit_early()) {
+            break;
+        }
 
         te = NULL;
         rv = ap_queue_pop_something(worker_queue, &csd, &cs, &ptrans, &te);
@@ -1993,9 +2031,8 @@ static void create_listener_thread(threa
     apr_status_t rv;
 
     my_info = (proc_info *) ap_malloc(sizeof(proc_info));
-    my_info->pid = my_child_num;
-    my_info->tid = -1;          /* listener thread doesn't have a thread slot */
-    my_info->sd = 0;
+    my_info->pslot = my_child_num;
+    my_info->tslot = -1;      /* listener thread doesn't have a thread slot */
     rv = apr_thread_create(&ts->listener, thread_attr, listener_thread,
                            my_info, pchild);
     if (rv != APR_SUCCESS) {
@@ -2103,14 +2140,13 @@ static void *APR_THREAD_FUNC start_threa
             int status =
                 ap_scoreboard_image->servers[my_child_num][i].status;
 
-            if (status != SERVER_GRACEFUL && status != SERVER_DEAD) {
+            if (status != SERVER_DEAD) {
                 continue;
             }
 
             my_info = (proc_info *) ap_malloc(sizeof(proc_info));
-            my_info->pid = my_child_num;
-            my_info->tid = i;
-            my_info->sd = 0;
+            my_info->pslot = my_child_num;
+            my_info->tslot = i;
 
             /* We are creating threads right now */
             ap_update_child_status_from_indexes(my_child_num, i,
@@ -2411,6 +2447,15 @@ static int make_child(server_rec * s, in
         retained->max_daemons_limit = slot + 1;
     }
 
+    if (ap_scoreboard_image->parent[slot].pid != 0) {
+        /* XXX replace with assert or remove ? */
+        ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(03455)
+                 "BUG: Scoreboard slot %d should be empty but is "
+                 "in use by pid %" APR_PID_T_FMT,
+                 slot, ap_scoreboard_image->parent[slot].pid);
+        return -1;
+    }
+
     if (one_process) {
         my_bucket = &all_buckets[0];
 
@@ -2464,17 +2509,12 @@ static int make_child(server_rec * s, in
         return -1;
     }
 
-    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.
-         */
-        event_note_child_lost_slot(slot, pid);
-    }
     ap_scoreboard_image->parent[slot].quiescing = 0;
     ap_scoreboard_image->parent[slot].not_accepting = 0;
     ap_scoreboard_image->parent[slot].bucket = bucket;
     event_note_child_started(slot, pid);
+    active_daemons++;
+    retained->total_daemons++;
     return 0;
 }
 
@@ -2483,7 +2523,7 @@ static void startup_children(int number_
 {
     int i;
 
-    for (i = 0; number_to_start && i < ap_daemons_limit; ++i) {
+    for (i = 0; number_to_start && i < server_limit; ++i) {
         if (ap_scoreboard_image->parent[i].pid != 0) {
             continue;
         }
@@ -2497,34 +2537,22 @@ static void startup_children(int number_
 static void perform_idle_server_maintenance(int child_bucket, int num_buckets)
 {
     int i, j;
-    int idle_thread_count;
+    int idle_thread_count = 0;
     worker_score *ws;
     process_score *ps;
-    int free_length;
-    int totally_free_length = 0;
+    int free_length = 0;
     int free_slots[MAX_SPAWN_RATE];
-    int last_non_dead;
-    int total_non_dead;
+    int last_non_dead = -1;
     int active_thread_count = 0;
 
-    /* initialize the free_list */
-    free_length = 0;
-
-    idle_thread_count = 0;
-    last_non_dead = -1;
-    total_non_dead = 0;
-
-    for (i = 0; i < ap_daemons_limit; ++i) {
+    for (i = 0; i < server_limit; ++i) {
         /* Initialization to satisfy the compiler. It doesn't know
          * that threads_per_child is always > 0 */
         int status = SERVER_DEAD;
-        int any_dying_threads = 0;
-        int any_dead_threads = 0;
-        int all_dead_threads = 1;
         int child_threads_active = 0;
 
         if (i >= retained->max_daemons_limit &&
-            totally_free_length == retained->idle_spawn_rate[child_bucket]) {
+            free_length == retained->idle_spawn_rate[child_bucket]) {
             /* short cut if all active processes have been examined and
              * enough empty scoreboard slots have been found
              */
@@ -2532,25 +2560,17 @@ static void perform_idle_server_maintena
             break;
         }
         ps = &ap_scoreboard_image->parent[i];
-        for (j = 0; j < threads_per_child; j++) {
-            ws = &ap_scoreboard_image->servers[i][j];
-            status = ws->status;
-
-            /* XXX any_dying_threads is probably no longer needed    GLA */
-            any_dying_threads = any_dying_threads ||
-                (status == SERVER_GRACEFUL);
-            any_dead_threads = any_dead_threads || (status == SERVER_DEAD);
-            all_dead_threads = all_dead_threads &&
-                (status == SERVER_DEAD || status == SERVER_GRACEFUL);
-
-            /* We consider a starting server as idle because we started it
-             * at least a cycle ago, and if it still hasn't finished starting
-             * then we're just going to swamp things worse by forking more.
-             * 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 (ps->pid != 0) { /* XXX just set all_dead_threads in outer
-                                   for loop if no pid?  not much else matters */
+        if (ps->pid != 0) {
+            for (j = 0; j < threads_per_child; j++) {
+                ws = &ap_scoreboard_image->servers[i][j];
+                status = ws->status;
+
+                /* We consider a starting server as idle because we started it
+                 * at least a cycle ago, and if it still hasn't finished starting
+                 * then we're just going to swamp things worse by forking more.
+                 * 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 && !ps->quiescing && !ps->not_accepting
                     && ps->generation == retained->my_generation
                     && ps->bucket == child_bucket)
@@ -2561,39 +2581,13 @@ static void perform_idle_server_maintena
                     ++child_threads_active;
                 }
             }
+            last_non_dead = i;
         }
         active_thread_count += child_threads_active;
-        if (any_dead_threads
-            && totally_free_length < retained->idle_spawn_rate[child_bucket]
-            && free_length < MAX_SPAWN_RATE / num_buckets
-            && (!ps->pid      /* no process in the slot */
-                  || ps->quiescing)) {  /* or at least one is going away */
-            if (all_dead_threads) {
-                /* great! we prefer these, because the new process can
-                 * start more threads sooner.  So prioritize this slot
-                 * by putting it ahead of any slots with active threads.
-                 *
-                 * first, make room by moving a slot that's potentially still
-                 * in use to the end of the array
-                 */
-                free_slots[free_length] = free_slots[totally_free_length];
-                free_slots[totally_free_length++] = i;
-            }
-            else {
-                /* slot is still in use - back of the bus
-                 */
-                free_slots[free_length] = i;
-            }
-            ++free_length;
-        }
-        else if (child_threads_active == threads_per_child) {
+        if (!ps->pid && free_length < retained->idle_spawn_rate[child_bucket])
+            free_slots[free_length++] = i;
+        else if (child_threads_active == threads_per_child)
             had_healthy_child = 1;
-        }
-        /* XXX if (!ps->quiescing)     is probably more reliable  GLA */
-        if (!any_dying_threads) {
-            last_non_dead = i;
-            ++total_non_dead;
-        }
     }
 
     if (retained->sick_child_detected) {
@@ -2621,32 +2615,56 @@ static void perform_idle_server_maintena
 
     retained->max_daemons_limit = last_non_dead + 1;
 
-    if (idle_thread_count > max_spare_threads / num_buckets) {
-        /* Kill off one child */
-        ap_mpm_podx_signal(all_buckets[child_bucket].pod,
-                           AP_MPM_PODX_GRACEFUL);
-        retained->idle_spawn_rate[child_bucket] = 1;
+    if (idle_thread_count > max_spare_threads / num_buckets)
+    {
+        /*
+         * Child processes that we ask to shut down won't die immediately
+         * but may stay around for a long time when they finish their
+         * requests. If the server load changes many times, many such
+         * gracefully finishing processes may accumulate, filling up the
+         * scoreboard. To avoid running out of scoreboard entries, we
+         * don't shut down more processes when the total number of processes
+         * is high.
+         *
+         * XXX It would be nice if we could
+         * XXX - kill processes without keepalive connections first
+         * XXX - tell children to stop accepting new connections, and
+         * XXX   depending on server load, later be able to resurrect them
+         *       or kill them
+         */
+        if (retained->total_daemons <= active_daemons_limit &&
+            retained->total_daemons < server_limit) {
+            /* Kill off one child */
+            ap_mpm_podx_signal(all_buckets[child_bucket].pod,
+                               AP_MPM_PODX_GRACEFUL);
+            retained->idle_spawn_rate[child_bucket] = 1;
+            active_daemons--;
+        } else {
+            ap_log_error(APLOG_MARK, APLOG_TRACE5, 0, ap_server_conf,
+                         "Not shutting down child: total daemons %d / "
+                         "active limit %d / ServerLimit %d",
+                         retained->total_daemons, active_daemons_limit,
+                         server_limit);
+        }
     }
     else if (idle_thread_count < min_spare_threads / num_buckets) {
-        /* terminate the free list */
-        if (free_length == 0) { /* scoreboard is full, can't fork */
-
-            if (active_thread_count >= ap_daemons_limit * threads_per_child) {
-                if (!retained->maxclients_reported) {
-                    /* only report this condition once */
-                    ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00484)
-                                 "server reached MaxRequestWorkers setting, "
-                                 "consider raising the MaxRequestWorkers "
-                                 "setting");
-                    retained->maxclients_reported = 1;
-                }
-            }
-            else {
-                ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00485)
-                             "scoreboard is full, not at MaxRequestWorkers");
+        if (active_thread_count >= max_workers) {
+            if (!retained->maxclients_reported) {
+                /* only report this condition once */
+                ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(00484)
+                             "server reached MaxRequestWorkers setting, "
+                             "consider raising the MaxRequestWorkers "
+                             "setting");
+                retained->maxclients_reported = 1;
             }
             retained->idle_spawn_rate[child_bucket] = 1;
         }
+        else if (free_length == 0) { /* scoreboard is full, can't fork */
+            ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(03490)
+                         "scoreboard is full, not at MaxRequestWorkers."
+                         "Increase ServerLimit.");
+            retained->idle_spawn_rate[child_bucket] = 1;
+        }
         else {
             if (free_length > retained->idle_spawn_rate[child_bucket]) {
                 free_length = retained->idle_spawn_rate[child_bucket];
@@ -2657,10 +2675,17 @@ static void perform_idle_server_maintena
                              "to increase StartServers, ThreadsPerChild "
                              "or Min/MaxSpareThreads), "
                              "spawning %d children, there are around %d idle "
-                             "threads, and %d total children", free_length,
-                             idle_thread_count, total_non_dead);
+                             "threads, %d active children, and %d children "
+                             "that are shutting down", free_length,
+                             idle_thread_count, active_daemons,
+                             retained->total_daemons);
             }
             for (i = 0; i < free_length; ++i) {
+                ap_log_error(APLOG_MARK, APLOG_TRACE5, 0, ap_server_conf,
+                             "Spawning new child: slot %d active / "
+                             "total daemons: %d/%d",
+                             free_slots[i], active_daemons,
+                             retained->total_daemons);
                 make_child(ap_server_conf, free_slots[i], child_bucket);
             }
             /* the next time around we want to spawn twice as many if this
@@ -2682,7 +2707,6 @@ static void perform_idle_server_maintena
 
 static void server_main_loop(int remaining_children_to_start, int num_buckets)
 {
-    ap_generation_t old_gen;
     int child_slot;
     apr_exit_why_e exitwhy;
     int status, processed_status;
@@ -2706,6 +2730,10 @@ static void server_main_loop(int remaini
                        == retained->my_generation) {
                     shutdown_pending = 1;
                     child_fatal = 1;
+                    /*
+                     * total_daemons counting will be off now, but as we
+                     * are shutting down, that is not an issue anymore.
+                     */
                     return;
                 }
                 else {
@@ -2732,13 +2760,16 @@ static void server_main_loop(int remaini
 
                 event_note_child_killed(child_slot, 0, 0);
                 ps = &ap_scoreboard_image->parent[child_slot];
+                if (!ps->quiescing)
+                    active_daemons--;
                 ps->quiescing = 0;
+                /* NOTE: We don't dec in the (child_slot < 0) case! */
+                retained->total_daemons--;
                 if (processed_status == APEXIT_CHILDSICK) {
                     /* resource shortage, minimize the fork rate */
                     retained->idle_spawn_rate[ps->bucket] = 1;
                 }
-                else if (remaining_children_to_start
-                         && child_slot < ap_daemons_limit) {
+                else if (remaining_children_to_start) {
                     /* we're still doing a 1-for-1 replacement of dead
                      * children with new children
                      */
@@ -2746,24 +2777,12 @@ static void server_main_loop(int remaini
                     --remaining_children_to_start;
                 }
             }
-            else if (ap_unregister_extra_mpm_process(pid.pid, &old_gen) == 1) {
-
-                event_note_child_killed(-1, /* already out of the scoreboard */
-                                        pid.pid, old_gen);
-                if (processed_status == APEXIT_CHILDSICK
-                    && old_gen == retained->my_generation) {
-                    /* resource shortage, minimize the fork rate */
-                    for (i = 0; i < num_buckets; i++) {
-                        retained->idle_spawn_rate[i] = 1;
-                    }
-                }
 #if APR_HAS_OTHER_CHILD
-            }
             else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH,
                                                 status) == 0) {
                 /* handled */
-#endif
             }
+#endif
             else if (retained->is_graceful) {
                 /* Great, we've probably just lost a slot in the
                  * scoreboard.  Somehow we don't know about this child.
@@ -2825,8 +2844,8 @@ static int event_run(apr_pool_t * _pconf
     /* Don't thrash since num_buckets depends on the
      * system and the number of online CPU cores...
      */
-    if (ap_daemons_limit < num_buckets)
-        ap_daemons_limit = num_buckets;
+    if (active_daemons_limit < num_buckets)
+        active_daemons_limit = num_buckets;
     if (ap_daemons_to_start < num_buckets)
         ap_daemons_to_start = num_buckets;
     /* We want to create as much children at a time as the number of buckets,
@@ -2850,8 +2869,8 @@ static int event_run(apr_pool_t * _pconf
      * supposed to start up without the 1 second penalty between each fork.
      */
     remaining_children_to_start = ap_daemons_to_start;
-    if (remaining_children_to_start > ap_daemons_limit) {
-        remaining_children_to_start = ap_daemons_limit;
+    if (remaining_children_to_start > active_daemons_limit) {
+        remaining_children_to_start = active_daemons_limit;
     }
     if (!retained->is_graceful) {
         startup_children(remaining_children_to_start);
@@ -2881,7 +2900,7 @@ static int event_run(apr_pool_t * _pconf
          * Kill child processes, tell them to call child_exit, etc...
          */
         for (i = 0; i < num_buckets; i++) {
-            ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
+            ap_mpm_podx_killpg(all_buckets[i].pod, active_daemons_limit,
                                AP_MPM_PODX_RESTART);
         }
         ap_reclaim_child_processes(1, /* Start with SIGTERM */
@@ -2905,7 +2924,7 @@ static int event_run(apr_pool_t * _pconf
         /* Close our listeners, and then ask our children to do same */
         ap_close_listeners();
         for (i = 0; i < num_buckets; i++) {
-            ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
+            ap_mpm_podx_killpg(all_buckets[i].pod, active_daemons_limit,
                                AP_MPM_PODX_GRACEFUL);
         }
         ap_relieve_child_processes(event_note_child_killed);
@@ -2933,7 +2952,7 @@ static int event_run(apr_pool_t * _pconf
             ap_relieve_child_processes(event_note_child_killed);
 
             active_children = 0;
-            for (index = 0; index < ap_daemons_limit; ++index) {
+            for (index = 0; index < retained->max_daemons_limit; ++index) {
                 if (ap_mpm_safe_kill(MPM_CHILD_PID(index), 0) == APR_SUCCESS) {
                     active_children = 1;
                     /* Having just one child is enough to stay around */
@@ -2948,7 +2967,7 @@ static int event_run(apr_pool_t * _pconf
          * really dead.
          */
         for (i = 0; i < num_buckets; i++) {
-            ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
+            ap_mpm_podx_killpg(all_buckets[i].pod, active_daemons_limit,
                                AP_MPM_PODX_RESTART);
         }
         ap_reclaim_child_processes(1, event_note_child_killed);
@@ -2977,7 +2996,7 @@ static int event_run(apr_pool_t * _pconf
                      " received.  Doing graceful restart");
         /* wake up the children...time to die.  But we'll have more soon */
         for (i = 0; i < num_buckets; i++) {
-            ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
+            ap_mpm_podx_killpg(all_buckets[i].pod, active_daemons_limit,
                                AP_MPM_PODX_GRACEFUL);
         }
 
@@ -2992,7 +3011,7 @@ static int event_run(apr_pool_t * _pconf
          * pthreads are stealing signals from us left and right.
          */
         for (i = 0; i < num_buckets; i++) {
-            ap_mpm_podx_killpg(all_buckets[i].pod, ap_daemons_limit,
+            ap_mpm_podx_killpg(all_buckets[i].pod, active_daemons_limit,
                                AP_MPM_PODX_RESTART);
         }
 
@@ -3002,6 +3021,8 @@ static int event_run(apr_pool_t * _pconf
                      "SIGHUP received.  Attempting to restart");
     }
 
+    active_daemons = 0;
+
     return OK;
 }
 
@@ -3215,9 +3236,9 @@ static int event_pre_config(apr_pool_t *
     max_spare_threads = DEFAULT_MAX_FREE_DAEMON * DEFAULT_THREADS_PER_CHILD;
     server_limit = DEFAULT_SERVER_LIMIT;
     thread_limit = DEFAULT_THREAD_LIMIT;
-    ap_daemons_limit = server_limit;
+    active_daemons_limit = server_limit;
     threads_per_child = DEFAULT_THREADS_PER_CHILD;
-    max_workers = ap_daemons_limit * threads_per_child;
+    max_workers = active_daemons_limit * threads_per_child;
     had_healthy_child = 0;
     ap_extended_status = 0;
 
@@ -3426,10 +3447,10 @@ static int event_check_config(apr_pool_t
         max_workers = threads_per_child;
     }
 
-    ap_daemons_limit = max_workers / threads_per_child;
+    active_daemons_limit = max_workers / threads_per_child;
 
     if (max_workers % threads_per_child) {
-        int tmp_max_workers = ap_daemons_limit * threads_per_child;
+        int tmp_max_workers = active_daemons_limit * threads_per_child;
 
         if (startup) {
             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00513)
@@ -3437,7 +3458,7 @@ static int event_check_config(apr_pool_t
                          "multiple of ThreadsPerChild of %d, decreasing to nearest "
                          "multiple %d, for a maximum of %d servers.",
                          max_workers, threads_per_child, tmp_max_workers,
-                         ap_daemons_limit);
+                         active_daemons_limit);
         } else {
             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00514)
                          "MaxRequestWorkers of %d is not an integer multiple "
@@ -3448,25 +3469,25 @@ static int event_check_config(apr_pool_t
         max_workers = tmp_max_workers;
     }
 
-    if (ap_daemons_limit > server_limit) {
+    if (active_daemons_limit > server_limit) {
         if (startup) {
             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00515)
                          "WARNING: MaxRequestWorkers of %d would require %d servers "
                          "and would exceed ServerLimit of %d, decreasing to %d. "
                          "To increase, please see the ServerLimit directive.",
-                         max_workers, ap_daemons_limit, server_limit,
+                         max_workers, active_daemons_limit, server_limit,
                          server_limit * threads_per_child);
         } else {
             ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(00516)
                          "MaxRequestWorkers of %d would require %d servers and "
                          "exceed ServerLimit of %d, decreasing to %d",
-                         max_workers, ap_daemons_limit, server_limit,
+                         max_workers, active_daemons_limit, server_limit,
                          server_limit * threads_per_child);
         }
-        ap_daemons_limit = server_limit;
+        active_daemons_limit = server_limit;
     }
 
-    /* ap_daemons_to_start > ap_daemons_limit checked in ap_mpm_run() */
+    /* ap_daemons_to_start > active_daemons_limit checked in ap_mpm_run() */
     if (ap_daemons_to_start < 1) {
         if (startup) {
             ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(00517)

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/fdqueue.c
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/fdqueue.c?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/fdqueue.c (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/fdqueue.c Tue Jan 31 09:52:02 2017
@@ -280,6 +280,19 @@ void ap_pop_pool(apr_pool_t ** recycled_
     }
 }
 
+void ap_free_idle_pools(fd_queue_info_t *queue_info)
+{
+    apr_pool_t *p;
+
+    queue_info->max_recycled_pools = 0;
+    do {
+        ap_pop_pool(&p, queue_info);
+        if (p != NULL)
+            apr_pool_destroy(p);
+    } while (p != NULL);
+}
+
+
 apr_status_t ap_queue_info_term(fd_queue_info_t * queue_info)
 {
     apr_status_t rv;
@@ -477,17 +490,30 @@ apr_status_t ap_queue_pop_something(fd_q
     return rv;
 }
 
-apr_status_t ap_queue_interrupt_all(fd_queue_t * queue)
+static apr_status_t queue_interrupt(fd_queue_t * queue, int all)
 {
     apr_status_t rv;
 
     if ((rv = apr_thread_mutex_lock(queue->one_big_mutex)) != APR_SUCCESS) {
         return rv;
     }
-    apr_thread_cond_broadcast(queue->not_empty);
+    if (all)
+        apr_thread_cond_broadcast(queue->not_empty);
+    else
+        apr_thread_cond_signal(queue->not_empty);
     return apr_thread_mutex_unlock(queue->one_big_mutex);
 }
 
+apr_status_t ap_queue_interrupt_all(fd_queue_t * queue)
+{
+    return queue_interrupt(queue, 1);
+}
+
+apr_status_t ap_queue_interrupt_one(fd_queue_t * queue)
+{
+    return queue_interrupt(queue, 0);
+}
+
 apr_status_t ap_queue_term(fd_queue_t * queue)
 {
     apr_status_t rv;

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/fdqueue.h
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/fdqueue.h?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/fdqueue.h (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm/event/fdqueue.h Tue Jan 31 09:52:02 2017
@@ -52,6 +52,7 @@ apr_status_t ap_queue_info_wait_for_idle
                                           int *had_to_block);
 apr_status_t ap_queue_info_term(fd_queue_info_t * queue_info);
 apr_uint32_t ap_queue_info_get_idlers(fd_queue_info_t * queue_info);
+void ap_free_idle_pools(fd_queue_info_t *queue_info);
 
 struct fd_queue_elem_t
 {
@@ -98,6 +99,7 @@ apr_status_t ap_queue_pop_something(fd_q
                                     event_conn_state_t ** ecs, apr_pool_t ** p,
                                     timer_event_t ** te);
 apr_status_t ap_queue_interrupt_all(fd_queue_t * queue);
+apr_status_t ap_queue_interrupt_one(fd_queue_t * queue);
 apr_status_t ap_queue_term(fd_queue_t * queue);
 
 #endif /* FDQUEUE_H */

Modified: httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm_unix.c
URL: http://svn.apache.org/viewvc/httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm_unix.c?rev=1781045&r1=1781044&r2=1781045&view=diff
==============================================================================
--- httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm_unix.c (original)
+++ httpd/httpd/branches/2.4.x-openssl-1.1.0-compat/server/mpm_unix.c Tue Jan 31 09:52:02 2017
@@ -63,7 +63,13 @@
 #undef APLOG_MODULE_INDEX
 #define APLOG_MODULE_INDEX AP_CORE_MODULE_INDEX
 
-typedef enum {DO_NOTHING, SEND_SIGTERM, SEND_SIGKILL, GIVEUP} action_t;
+typedef enum {
+    DO_NOTHING,
+    SEND_SIGTERM,
+    SEND_SIGTERM_NOLOG,
+    SEND_SIGKILL,
+    GIVEUP
+} action_t;
 
 typedef struct extra_process_t {
     struct extra_process_t *next;
@@ -142,6 +148,8 @@ static int reclaim_one_pid(pid_t pid, ac
                      " still did not exit, "
                      "sending a SIGTERM",
                      pid);
+        /* FALLTHROUGH */
+    case SEND_SIGTERM_NOLOG:
         kill(pid, SIGTERM);
         break;
 
@@ -193,6 +201,7 @@ AP_DECLARE(void) ap_reclaim_child_proces
                           * children but take no action against
                           * stragglers
                           */
+        {SEND_SIGTERM_NOLOG, 0}, /* skipped if terminate == 0 */
         {SEND_SIGTERM, apr_time_from_sec(3)},
         {SEND_SIGTERM, apr_time_from_sec(5)},
         {SEND_SIGTERM, apr_time_from_sec(7)},
@@ -202,19 +211,21 @@ AP_DECLARE(void) ap_reclaim_child_proces
     int cur_action;      /* index of action we decided to take this
                           * iteration
                           */
-    int next_action = 1; /* index of first real action */
+    int next_action = terminate ? 1 : 2; /* index of first real action */
 
     ap_mpm_query(AP_MPMQ_MAX_DAEMON_USED, &max_daemons);
 
     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);
+        if (action_table[next_action].action_time > 0) {
+            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 */