/* Copyright 1999-2007 The Apache Software Foundation or its licensors, as
 * applicable.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Original Copyright (c) Netmask.IT!® 2006-2007
 *
 * DNS Protocol module for Apache 2.x
 */


/* TODO LIST:
 ** filters for compression (RFC 1035)
 ** output truncation filter (limit UDP to 512 + set TC bit)
 ** forward queries (*via tcp / * via udp with retransmission policy)
 ** support AXFR queries for slaves to update from us
 ** How should we update the scoreboard?  we use many logical reads/writes
 ** query cache via mod_cache with special key_generator
 ** Error support dns_die()
 ** IPV6 Support?
 ** Wildcard virtualhosts will return 0.0.0.0 as the IP.  What do we do with this?
 */

#include "mod_dns.h"

static server_rec *base_server;

APR_HOOK_STRUCT(
    APR_HOOK_LINK(post_read_request)
    APR_HOOK_LINK(create_request)
    APR_HOOK_LINK(handler)
)

APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL(dns, DNS, int, post_read_request,
                                    (dns_message_t *dns),
                                    (dns),
                                    OK, DECLINED)

APR_IMPLEMENT_EXTERNAL_HOOK_RUN_ALL(dns, DNS, int, create_request,
                                    (request_rec *r, dns_message_t *dns),
                                    (r, dns),
                                    OK, DECLINED)

APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(dns, DNS, int, handler,
                                    (request_rec *r),
                                    (r), DECLINED)

/** Be nice and export so other modules can remove it if they really want */
DNS_DECLARE_DATA ap_filter_rec_t* dns_buffered_write_response_filter_handle;
DNS_DECLARE_DATA ap_filter_rec_t* dns_buffered_write_proto_filter_handle;
DNS_DECLARE_DATA ap_filter_rec_t* dns_output_protocol_filter_handle;
DNS_DECLARE_DATA ap_filter_rec_t* dns_tcp_length_filter_handle;

/** This isn't exported by core, so we need to redo ourselves... */
DNS_DECLARE(int) dns_invoke_filter_init(ap_filter_t *filters)
{
    while (filters) {
        if (filters->frec->filter_init_func) {
            int result = filters->frec->filter_init_func(filters);
            if (result != OK) {
                return result;
            }
        }
        filters = filters->next;
    }
    return OK;
}

DNS_DECLARE(request_rec *) dns_create_request(dns_message_t *dns) {
    request_rec *r;
    apr_pool_t *p;

    apr_pool_create(&p, dns->pool);
    apr_pool_tag(p, "request");
    r = apr_pcalloc(p, sizeof(*r));
    r->pool            = p;
    r->connection      = dns->conn;
    r->server          = dns->conn->base_server;

    r->user            = NULL;
    r->ap_auth_type    = NULL;
    r->next            = NULL;
    r->prev            = NULL;
    r->main            = NULL;

    r->allowed_methods = ap_make_method_list(p, 2);

    r->headers_in      = apr_table_make(r->pool, 1);
    r->subprocess_env  = apr_table_make(r->pool, 1);
    r->headers_out     = apr_table_make(r->pool, 1);
    r->err_headers_out = apr_table_make(r->pool, 1);
    r->notes           = apr_table_make(r->pool, 5);

    r->request_config  = ap_create_request_config(r->pool);
    /* Must be set before we run create request hook */

    r->proto_output_filters = dns->filters_out;
    r->output_filters  = r->proto_output_filters;
    r->proto_input_filters = dns->filters_in;
    r->input_filters   = r->proto_input_filters;
    r->per_dir_config  = r->server->lookup_defaults;

    r->sent_bodyct     = 0;                      /* bytect isn't for body */

    r->read_body       = REQUEST_NO_BODY;
    r->handler         = NULL;

    r->status          = HTTP_OK;  /* Until we get a request */
    r->status_line     = NULL;
    r->the_request     = NULL;

    /* Begin by presuming any module can make its own path_info assumptions,
     * until some module interjects and changes the value.
     */
    r->used_path_info = AP_REQ_DEFAULT_PATH_INFO;

    ap_set_module_config(r->request_config, &dns_module, dns);
    /** Cheat here and add our buffered write filter before anyone
     *  else gets in the way */
    ap_add_output_filter_handle(dns_buffered_write_response_filter_handle, NULL,
                                r, dns->conn);

    /** Let other modules do what they need now */
    ap_run_create_request(r);
    dns_run_create_request(r, dns);
    return r;
}

/** Our buffered output filter */
typedef struct {
    apr_bucket_brigade *bb;
    int seen_eos;
} dns_buffered_write_filter_ctx;

static apr_status_t dns_buffered_write_filter(ap_filter_t *f,
                                              apr_bucket_brigade *bb)
{
    dns_buffered_write_filter_ctx *ctx = f->ctx;
    apr_bucket *b;
    apr_off_t len = 0;
    apr_status_t rv;

    if (ctx == NULL) {
        f->ctx = ctx = apr_palloc(f->r->pool, sizeof(*ctx));
        ctx->bb = apr_brigade_create(f->r->pool,
                                     f->r->connection->bucket_alloc);
        ctx->seen_eos = 0;
    }

    if (ctx->seen_eos)
        return APR_SUCCESS;

    rv = APR_SUCCESS;

    /** Buffer until we get a EOS or FLUSH */
    for (b = APR_BRIGADE_FIRST(bb);
         b != APR_BRIGADE_SENTINEL(bb) && !APR_BRIGADE_EMPTY(bb);
         b = APR_BUCKET_NEXT(b))
    {
        APR_BUCKET_REMOVE(b);
        APR_BRIGADE_INSERT_TAIL(ctx->bb, b);
        apr_brigade_length(ctx->bb, 1, &len);
        if ((APR_BUCKET_IS_EOS(b) || APR_BUCKET_IS_FLUSH(b)) ||
            (len > APR_BUCKET_BUFF_SIZE))
        {
            rv = ap_pass_brigade(f->next, ctx->bb);
            apr_brigade_cleanup(ctx->bb);
            if (APR_BUCKET_IS_EOS(b))
                ctx->seen_eos = 1;
        }
    }

    /** Give an empty brigade back */
    apr_brigade_cleanup(bb);

    /** if we got the EOS before the brigade ended, replace the unsent data */
    if (ctx->seen_eos) {
        APR_BRIGADE_CONCAT(bb, ctx->bb);
        apr_brigade_destroy(ctx->bb);
    }

    return rv;
}

/** Our protocol output filter */
static apr_status_t dns_output_protocol_filter(ap_filter_t *f,
                                               apr_bucket_brigade *bb)
{

    dns_message_t *dns;
    apr_bucket *b;
    apr_size_t len = 0;
    apr_status_t rv;
    dns_rr_t *rr, *tmp_rr;
    const char *data;
    char *response;
    apr_bucket_brigade *bb_out;

    /*if (AP_BUCKET_IS_ERROR(e)) {
            ap_bucket_error *eb = e->data;

            ap_die(eb->status, r);
            return AP_FILTER_ERROR;
        }*/
    /** Get our DNS message */
    dns = (dns_message_t *)ap_get_module_config(f->r->request_config,
                                                &dns_module);

    if (!(dns)) {
        ap_remove_output_filter(f);
        return ap_pass_brigade(f->next, bb);
    }

    rv = APR_SUCCESS;

    /** We can't flush and EOS means end of answer; we send content onward
     *  when we've got all of our answers */
    for (b = APR_BRIGADE_FIRST(bb);
         b != APR_BRIGADE_SENTINEL(bb) && !APR_BRIGADE_EMPTY(bb);
         b = APR_BUCKET_NEXT(b))
    {
        if (BUCKET_IS_DNS_RR(b)) {
            /** Got an RR */
            if (BUCKET_IS_DNS_ANSWER(b)) {
                rr = apr_array_push(dns->answer);
                dns->header->ancount++;
            }
            else if (BUCKET_IS_DNS_AUTHORITY(b)) {
                rr = apr_array_push(dns->authority);
                dns->header->nscount++;
            }
            else if (BUCKET_IS_DNS_ADDITIONAL(b)) {
                rr = apr_array_push(dns->additional);
                dns->header->arcount++;
            }
            else
                rr = NULL;

            rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
            /** This is a waste of memory, but unserialize (correctly)
             *  allocates a new rr, and apr_array_push will lose it's
             *  pointer...  Since we can't play with the array's
             *  pointers (why not?) we copy the block of memory */
            dns_rr_unserialize(f->r->pool, data, &tmp_rr);
            memcpy(rr, tmp_rr, sizeof(*rr));
            apr_bucket_delete(b);
            /** Handle errors */

            continue;
        }

        if (APR_BUCKET_IS_EOS(b)) {
            /** End of query - ignore everything after this */
            apr_brigade_cleanup(bb);
            dns->answered++;
            break;
        }

        if (APR_BUCKET_IS_FLUSH(b)) {
            /** We can't flush before we've assembled the response - sorry */
            apr_bucket_delete(b);
            continue;
        }

        /** Handle error buckets */

        /** We don't know what to do with anything else... */
        apr_bucket_delete(b);
    }

    if (dns->answered == dns->header->qdcount) {
        /** We've assembled a response - send it out */
        bb_out = apr_brigade_create(dns->pool, dns->conn->bucket_alloc);
        rv = dns_write_response(dns, &response, &len);
        b = apr_bucket_heap_create(response, len, free,
                                   bb_out->bucket_alloc);
        APR_BRIGADE_INSERT_TAIL(bb_out, b);
        /** Add flush (UDP needs this push) */
        b = apr_bucket_flush_create(bb_out->bucket_alloc);
        APR_BRIGADE_INSERT_TAIL(bb_out, b);
        /** Add EOS */
        b = apr_bucket_eos_create(bb_out->bucket_alloc);
        APR_BRIGADE_INSERT_TAIL(bb_out, b);
        /** Send it on its merry way */
        rv = ap_pass_brigade(f->next, bb_out);
        /** Core-output will destroy this brigade for us */
    }
    return rv;
}

/** TCP set-length filter - we cheat now by assuming one brigade holds
 *  everything; it almost certainly does, but that's besides the point */
static apr_status_t dns_tcp_length_filter(ap_filter_t *f,
                                          apr_bucket_brigade *bb)
{
    apr_bucket *b;
    apr_uint16_t len = 0;
    apr_status_t rv;
    int sd_type;

    /** If we have a TCP connection, we'll need to write length */
    apr_socket_type_get(ap_get_module_config(f->r->connection->conn_config,
                                             &core_module),
                        &sd_type);
    if (sd_type == SOCK_STREAM) {
        apr_brigade_length(bb, 1, (apr_off_t *)&len);
        len = htons(len);

        b = apr_bucket_transient_create((const char *)&len, 2, bb->bucket_alloc);
        APR_BRIGADE_INSERT_HEAD(bb, b);
    }

    rv = ap_pass_brigade(f->next, bb);

    /** We've done our work (and don't want to risk screwing more up) */
    ap_remove_output_filter(f);

    return rv;
}

static void finalize_response(request_rec *r) {
    apr_bucket_brigade *bb;
    apr_bucket *b;

    bb = apr_brigade_create(r->pool, r->connection->bucket_alloc);
    b = apr_bucket_eos_create(bb->bucket_alloc);
    APR_BRIGADE_INSERT_TAIL(bb, b);
    ap_pass_brigade(r->output_filters, bb);
    apr_brigade_destroy(bb);
}

static int process_dns_connection(conn_rec *c)
{
    dns_module_config_t *conf;
    dns_message_t *dns;
    dns_query_t *q;
    request_rec *r;
    server_rec *s = c->base_server;
    apr_status_t rv;
    int access_status;
    int i;

    conf = (dns_module_config_t *)ap_get_module_config(s->module_config,
                                                       &dns_module);
    if (!conf) {
        /* We're not configured.  Something's very wrong. Abort. */
        return DECLINED;
    }

    if (!conf->enabled) {
        /* We're configured, but disabled */
        return DECLINED;
    }
    ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0,c, "I got a connection!");

    dns = dns_read_message_header(c);

    if (!(dns)) {
        ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, c, "[mod_dns] Unable to read "
                      "DNS message header.  Aborting.");
        return OK;
    }

    dns_run_post_read_request(dns);
    for (i=0;i<dns->header->qdcount;i++) {
        q = NULL;
        r = NULL;
        rv = dns_read_request(dns, &r, &q);
        if (rv != APR_SUCCESS) {
            /* Set header->rcode to error and abort */
            /* dns_die should read remaining bytes from socket,
             * set error in dns_header_t, write response, and return
             */
        } else {
            /** Allow mod_cache to act as our resolver cache */
            access_status = ap_run_quick_handler(r, 0);
                if (access_status == DECLINED) {
                    access_status = ap_process_request_internal(r);
                    if (access_status != OK) {
                        /** Handle me */
                    }
                    /** Invoke handler (return response) */
                    access_status = dns_invoke_filter_init(r->output_filters);
                    if (access_status != OK)
                        /** Log, but continue */
                        ap_log_rerror(APLOG_MARK, APLOG_WARNING, access_status,
                                      r, "[mod_dns] Error initializing "
                                      "output filters for %s",
                                      r->the_request);

                    /** Run handler - only DNS registered handlers
                      * to avoid default-handler */
                    access_status = dns_run_handler(r);
                    finalize_response(r);

                    if (access_status == DECLINED) {
                        ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r,
                            "[mod_dns] handler not found for method \"%s\"",
                            r->handler, r->method);
                        /** die */
                    }
                }
            if (access_status == DONE) {
                /* e.g., something not in storage like TRACE */
                access_status = OK;
            }

            if (access_status != OK) {
                /** Return error (dns_die)*/
            } else {
                /** Cleanup */
            }

            /* FIXME:
             * Suppose that the logging causes a DNS lookup to occur, which may
             * have a high latency.  If we hold off on this packet, then it'll
             * appear like the link is stalled when really it's the application
             * that's stalled.
             * Since we can't send packets until all queries in the message
             * are answered, we should add the request_rec to a list and
             * batch-log them later
             */
            ap_run_log_transaction(r);
        }
    }
    /** Flush response */
    /** Log + cleanup */
    return OK;
}

/* -------------------------------------------------------------- */
/* Default handlers */

static server_rec *matches_aliases(server_rec *s, const char *host)
{
    int i;
    apr_array_header_t *names;

    while (s) {
        /* match ServerName */
        if (!strcasecmp(host, s->server_hostname)) {
            return s;
        }

        /* search all the aliases from ServerAlias directive */
        names = s->names;
        if (names) {
            char **name = (char **) names->elts;
            for (i = 0; i < names->nelts; ++i) {
                if(!name[i]) continue;
                if (!strcasecmp(host, name[i]))
                    return s;
            }
        }
        names = s->wild_names;
        if (names) {
            char **name = (char **) names->elts;
            for (i = 0; i < names->nelts; ++i) {
                if(!name[i]) continue;
                if (!ap_strcasecmp_match(host, name[i]))
                    return s;
            }
        }
        s = s->next;
    }
    return NULL;
}

static int dns_default_handler(request_rec *r) {
    dns_rr_t* rr;
    dns_rdata_a_t *a;
    server_rec *s;
    char *name;

    if (strcasecmp(r->handler, DNS_MAGIC_TYPE))
        return DECLINED;
    if (strcasecmp(r->method, "A"))
        return DECLINED;
    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
                  "Running A/CNAME lookup for host %s", r->hostname);

    if ((s = matches_aliases(base_server, r->hostname)) == NULL)
        return DECLINED;

    name = (char *)r->hostname;
    if (strcasecmp(s->server_hostname, r->hostname)) {
        dns_rdata_cname_t *cname;
        /** Add CNAME */
        cname = apr_palloc(r->pool, sizeof(*cname));
        cname->cname = apr_pstrdup(r->pool, s->server_hostname);
        rr = dns_create_rr(r, r->hostname, DNS_TYPE_CNAME, DNS_CLASS_IN, 0);
        rr->rdata->rdata = cname;
        dns_add_rr_answer(r, rr);
        name = s->server_hostname;
    }
    /** Add A */
    a = apr_pcalloc(r->pool, sizeof(*a));
    a->address = inet_addr(inet_ntoa(*((struct in_addr *)s->addrs->host_addr->ipaddr_ptr)));
    /** We get network address in network order; since serialize expects it in
     *  host order, switch here.*/
    a->address = ntohl(a->address);
    rr = dns_create_rr(r, name, DNS_TYPE_A, DNS_CLASS_IN, 0);
    rr->rdata->rdata = a;
    dns_add_rr_answer(r, rr);
    return OK;
}

static int dns_mx_handler(request_rec *r) {
    dns_module_config_t *conf;
    dns_rr_t* rr;
    dns_rdata_mx_t *mx;
    apr_array_header_t *mxs;
    server_rec *s;
    char *name;

    if (strcasecmp(r->handler, DNS_MAGIC_TYPE))
        return DECLINED;
    if (strcasecmp(r->method, "MX"))
        return DECLINED;

    ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r,
              "Running MX lookup for host %s", r->hostname);

    if ((s = matches_aliases(base_server, r->hostname)) == NULL)
        return DECLINED;

    name = (char *)r->hostname;
    if (strcasecmp(s->server_hostname, r->hostname))
        return DECLINED; /* Require exact match here */

    conf =
      (dns_module_config_t *)ap_get_module_config(s->module_config,
                                                  &dns_module);

    if (!(conf->mx))
        return DECLINED;

    mxs = apr_array_copy(r->pool, conf->mx);

    while (!(apr_is_empty_array(mxs))) {
        mx = apr_array_pop(mxs);
        rr = dns_create_rr(r, r->hostname, DNS_TYPE_MX, DNS_CLASS_IN, 0);
        rr->rdata->rdata = mx;
        dns_add_rr_answer(r, rr);
    }
    return OK;
}

static int ap_create_request_handler(request_rec *r) {
    dns_message_t *dns;

    dns = (dns_message_t *)ap_get_module_config(r->request_config,
                                                &dns_module);

    if (!(dns))
        return DECLINED;

    ap_add_output_filter_handle(dns_output_protocol_filter_handle, NULL,
                                r, dns->conn);
/*    ap_add_output_filter_handle(dns_buffered_write_proto_filter_handle, NULL,
                                r, dns->conn);*/
    ap_add_output_filter_handle(dns_tcp_length_filter_handle, NULL,
                                r, dns->conn);

    /** Don't care what this is, as long as it's not OK,  We do it to prevent
     *  default HTTP protocol handlers from registering */
    return DECLINED * 2;
}

static int dns_post_read_request(dns_message_t *dns) {
    ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, dns->conn,
                  "I got %d queries in the message", dns->header->qdcount);
    return OK;
}

static int dns_post_config(apr_pool_t *p, apr_pool_t *plog,
                           apr_pool_t *ptemp, server_rec *s)
{
    base_server = s;
    dns_register_rr((dns_rdata_t *)&dns_rdata_a, DNS_TYPE_A);
    dns_register_rr((dns_rdata_t *)&dns_rdata_cname, DNS_TYPE_CNAME);
    dns_register_rr((dns_rdata_t *)&dns_rdata_mx, DNS_TYPE_MX);
    return OK;
}



/* -------------------------------------------------------------- */
/* Setup configurable data */

static void *create_dns_config(apr_pool_t *p, server_rec *s)
{
    dns_module_config_t *ps = apr_pcalloc(p, sizeof(*ps));
    ps->enabled = 0;
    ps->enabled_set = 0;
    ps->default_ttl = DEFAULT_DEFAULT_TTL;
    ps->default_ttl_set = 0;
    ps->mx = NULL;
    return ps;
}

static void *merge_dns_config(apr_pool_t *p, void *basev, void *overridesv)
{
    dns_module_config_t *ps = apr_pcalloc(p, sizeof(*ps));
    dns_module_config_t *base = (dns_module_config_t *) basev;
    dns_module_config_t *overrides = (dns_module_config_t *) overridesv;

    ps->enabled =
        (overrides->enabled_set == 0)
        ? base->enabled
        : overrides->enabled;
    ps->default_ttl =
        (overrides->default_ttl_set == 0)
        ? base->default_ttl
        : overrides->default_ttl;

    if (base->mx || overrides->mx) {
        if (base->mx)
            ps->mx = base->mx;
        if (overrides->mx)
            if (ps->mx) {
                apr_array_cat(ps->mx, overrides->mx);
            } else {
                ps->mx = overrides->mx;
            }
    }


    return ps;
}

static const char *set_dns_enabled(cmd_parms *parms, void *dummy, int flag)
{
    dns_module_config_t *conf;

    const char *err = ap_check_cmd_context(parms,
                                           NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
    if (err) {
        return err;
    }

    conf =
      (dns_module_config_t *)ap_get_module_config(parms->server->module_config,
                                                  &dns_module);
    conf->enabled = flag;
    conf->enabled_set = 1;
    return NULL;
}

static const char *set_dns_default_ttl(cmd_parms *parms, void *dummy,
                                       const char *arg)
{
    dns_module_config_t *conf;

    const char *err = ap_check_cmd_context(parms, GLOBAL_ONLY);
    if (err) {
        return err;
    }

    conf =
      (dns_module_config_t *)ap_get_module_config(parms->server->module_config,
                                                  &dns_module);
    conf->default_ttl = (apr_size_t) atol(arg);
    conf->default_ttl_set = 1;
    return NULL;
}

static const char *set_dns_add_mx(cmd_parms *parms, void *dummy,
                                  const char *preference, const char *exchange)
{
    dns_module_config_t *conf;
    dns_rdata_mx_t *mx;

    const char *err = ap_check_cmd_context(parms, 
                                           NOT_IN_DIR_LOC_FILE|NOT_IN_LIMIT);
    if (err) {
        return err;
    }

    conf =
      (dns_module_config_t *)ap_get_module_config(parms->server->module_config,
                                                  &dns_module);

    if (!(conf->mx)) {
        conf->mx = apr_array_make(parms->pool, 2, sizeof(dns_rdata_mx_t));
        if (!(conf->mx))
            return "Could not allocate list of MXs for virtualhost";
    }

    mx = apr_array_push(conf->mx);
    if (!(mx))
        return "Could not allocate MX";
    mx->preference = (apr_uint16_t)apr_atoi64(preference);
    mx->exchange = apr_pstrdup(parms->pool, exchange);

    return NULL;
}

static const command_rec dns_cmds[] =
{
    AP_INIT_FLAG("DNSEnabled", set_dns_enabled, NULL, RSRC_CONF,
                  "Enable the DNS server on this VirtualHost."),
    AP_INIT_TAKE1("DNSDefaultTTL", set_dns_default_ttl, NULL, RSRC_CONF,
                  "Sets the default TTL used for all DNS replies (defaults"
                  "to 30 days"),
    AP_INIT_TAKE2("DNSAddMX", set_dns_add_mx, NULL, RSRC_CONF,
                  "Adds an MX record to the current domain"),
    {NULL}
};

static void register_hooks(apr_pool_t *p)
{
    ap_hook_post_config(dns_post_config, NULL, NULL, APR_HOOK_MIDDLE);
    ap_hook_process_connection(process_dns_connection, NULL, NULL, APR_HOOK_FIRST);
    /** FIXME: We hook REALLY_LAST - 1 to prevent default HTTP protocol
     *  handlers to be installed for the request, but there ought to be a
     *  better way... */
    ap_hook_create_request(ap_create_request_handler, NULL, NULL,
                           APR_HOOK_REALLY_LAST - 1);
    dns_hook_post_read_request(dns_post_read_request, NULL, NULL, APR_HOOK_MIDDLE);
    /** Although we don't take care of everything, hook after last so 3rd party
     *  handlers are always before us */
    dns_hook_handler(dns_mx_handler, NULL, NULL, APR_HOOK_LAST + 4);
    dns_hook_handler(dns_default_handler, NULL, NULL, APR_HOOK_LAST + 5);
    /* Put buffered output filter as close as possible to front */
    dns_buffered_write_response_filter_handle =
        ap_register_output_filter_protocol("DNS_BUFFERED_WRITE",
                                           dns_buffered_write_filter, NULL,
                                           AP_FTYPE_RESOURCE, 0);
    dns_output_protocol_filter_handle =
        ap_register_output_filter_protocol("DNS_OUTPUT_PROTOCOL",
                                           dns_output_protocol_filter, NULL,
                                           AP_FTYPE_PROTOCOL,
                                           AP_FILTER_PROTO_CHANGE +
                                           AP_FILTER_PROTO_CHANGE_LENGTH +
                                           AP_FILTER_PROTO_NO_BYTERANGE);
    dns_buffered_write_proto_filter_handle =
        ap_register_output_filter_protocol("DNS_BUFFERED_WRITE",
                                           dns_buffered_write_filter, NULL,
                                           AP_FTYPE_PROTOCOL, 0);
    dns_tcp_length_filter_handle =
        ap_register_output_filter_protocol("DNS_TCP_LENGTH",
                                           dns_tcp_length_filter, NULL,
                                           AP_FTYPE_PROTOCOL,
                                           AP_FILTER_PROTO_CHANGE +
                                           AP_FILTER_PROTO_CHANGE_LENGTH +
                                           AP_FILTER_PROTO_NO_BYTERANGE);
}

/* Dispatch list for API hooks */
module AP_MODULE_DECLARE_DATA dns_module = {
    STANDARD20_MODULE_STUFF,
    NULL,                  /* create per-dir    config structures */
    NULL,                  /* merge  per-dir    config structures */
    create_dns_config,     /* create per-server config structures */
    merge_dns_config,      /* merge  per-server config structures */
    dns_cmds,              /* table of config file commands       */
    register_hooks         /* register hooks                      */
};
