/* 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
 */

#ifndef MOD_DNS_H
#define MOD_DNS_H

#include "httpd.h"
#define CORE_PRIVATE
#include "util_filter.h"
#include "apr.h"
#include "apr_tables.h"
#include "apr_hooks.h"
#include "apr_pools.h"
#include "apu.h"
#include "apr_buckets.h"
#include "ap_config.h"

#include "http_protocol.h"
#include "http_config.h"
#include "http_connection.h"
#include "http_core.h"
#include "http_request.h"
#include "http_vhost.h"
#include "scoreboard.h"
#include "http_log.h"
#include "apr_network_io.h"
#include "apr_strings.h"
#include "apr_uri.h"

#define APR_WANT_BYTEF
#define APR_WANT_MEMFUNC
#include "apr_want.h"

#ifdef  __cplusplus
 extern "C" {
#endif

#define DEFAULT_DEFAULT_TTL 2592000 /* 30 days */
#define DNS_MAGIC_TYPE "apache/mod_dns_query"

/* Create a set of DNS_DECLARE(type), DNS_DECLARE_NONSTD(type) and
 * DNS_DECLARE_DATA with appropriate export and import tags for the platform
 */
#if !defined(WIN32)
#define DNS_DECLARE(type)            type
#define DNS_DECLARE_NONSTD(type)     type
#define DNS_DECLARE_DATA
#elif defined(DNS_DECLARE_STATIC)
#define DNS_DECLARE(type)            type __stdcall
#define DNS_DECLARE_NONSTD(type)     type
#define DNS_DECLARE_DATA
#elif defined(DNS_DECLARE_EXPORT)
#define DNS_DECLARE(type)            __declspec(dllexport) type __stdcall
#define DNS_DECLARE_NONSTD(type)     __declspec(dllexport) type
#define DNS_DECLARE_DATA             __declspec(dllexport)
#else
#define DNS_DECLARE(type)            __declspec(dllimport) type __stdcall
#define DNS_DECLARE_NONSTD(type)     __declspec(dllimport) type
#define DNS_DECLARE_DATA             __declspec(dllimport)
#endif

/** mod_dns server config */

module AP_MODULE_DECLARE_DATA dns_module;

typedef struct {
    int enabled;
    int enabled_set;
    apr_int32_t default_ttl;
    int default_ttl_set;
    apr_array_header_t *mx;
} dns_module_config_t;

/* generic payload type for RRs */
typedef struct dns_rdata_t {
    void *rdata;            /* Contains the rdata type */
    apr_status_t (*serialize)(void *rdata, char *data, int *dlen);
                            /* Serializing function which takes a pre-allocated
                             * character array large enough to fit and serializes
                             * the rdata structure into it.  dlen will return
                             * the actual length of data on return.*/
    apr_status_t (*pserialize)(void *rdata, apr_pool_t *pool, char **data,
                               int *dlen);
                            /* Similar to serialize, but will allocate memory
                             * from pool as needed.  dlen will be data length
                             * on return.*/
    apr_status_t (*unserialize)(apr_pool_t *pool, const char *data,
                                void **rdata);
                            /* Unserialize data into an rdata struct allocated
                             * from pool */
} dns_rdata_t;

/** DNS "TYPE" values */
typedef enum {
    DNS_TYPE_A        =   1, /* a host address */
    DNS_TYPE_NS,             /* an authoritative name server */
    DNS_TYPE_MD,             /* a mail destination (Obsolete - use MX) */
    DNS_TYPE_MF,             /* a mail forwarder (Obsolete - use MX) */
    DNS_TYPE_CNAME,          /* the canonical name for an alias */
    DNS_TYPE_SOA,            /* marks the start of a zone of authority */
    DNS_TYPE_MB,             /* a mailbox domain name (EXPERIMENTAL) */
    DNS_TYPE_MG,             /* a mail group member (EXPERIMENTAL) */
    DNS_TYPE_MR,             /* a mail rename domain name (EXPERIMENTAL) */
    DNS_TYPE_NULL,           /* a null RR (EXPERIMENTAL) */
    DNS_TYPE_WKS,            /* a well known service description */
    DNS_TYPE_PTR,            /* a domain name pointer */
    DNS_TYPE_HINFO,          /* host information */
    DNS_TYPE_MINFO,          /* mailbox or mail list information */
    DNS_TYPE_MX,             /* mail exchange */
    DNS_TYPE_TXT,            /* text strings */
    DNS_QTYPE_AXFR    = 252, /* A request for a transfer of an entire zone */
    DNS_QTYPE_MAILB,         /* A request for mailbox-related records */
    DNS_QTYPE_MAILA,         /* A request for mail agent RRs (Obsolete - see MX) */
    DNS_QTYPE_ALL            /* A request for all records */
} dns_type_t;

/** DNS "CLASS" values */
typedef enum {
    DNS_CLASS_IN      =   1, /* The internet */
    DNS_CLASS_CS,            /* The CSNET class (Obsolete) */
    DNS_CLASS_CH,            /* The CHAOS class */
    DNS_CLASS_HS,            /* Hesiod [Dyer 87] */
    DNS_QCLASS_ALL    = 255  /* Any class */
} dns_class_t;

/** Generic flag (1-bit). */
typedef enum {
    DNS_FLAG_OFF    = 0,
    DNS_FLAG_ON     = 1
} dns_flag_t;

/** DNS Opcode */
typedef enum {
    DNS_OPCODE_QUERY    = 0,
    DNS_OPCODE_IQUERY   = 1,
    DNS_OPCODE_STATUS   = 2,
    DNS_OPCODE_RESERVED = 15
} dns_opcode_t;

/** DNS Response code */
typedef enum {
    DNS_SUCCESS         =  0,
    DNS_EFORMAT         =  1,
    DNS_ESERVER         =  2,
    DNS_ENAME           =  3,
    DNS_ENOIMPL         =  4,
    DNS_EREFUSED        =  5,
    DNS_ERESERVED       = 15,
} dns_rcode_t;

/* Query data type
 * The question section is used to carry the "question" in most queries,
 * i.e., the parameters that define what is being asked.  The section
 * contains QDCOUNT (usually 1) entries, each of the following format:
 *
 *                                     1  1  1  1  1  1
 *       0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                                               |
 *     /                     QNAME                     /
 *     /                                               /
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                     QTYPE                     |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                     QCLASS                    |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 */
typedef struct {
    char *qname;            /* a domain name represented as a sequence of
                             * labels, where each label consists of a length
                             * octet followed by that number of octets.
                             * The domain name terminates with the zero length
                             * octet for the null label of the root.  Note that
                             * this field may be an odd number of octets; no
                             * padding is used.*/
    apr_uint16_t qtype;     /* a two octet code which specifies the type of the
                             * query.  The values for this field include all
                             * codes valid for a TYPE field, together with some
                             * more general codes which can match more than one
                             * type of RR.*/
    apr_uint16_t qclass;    /* a two octet code that specifies the class of the
                             * query.  For example, the QCLASS field is IN for
                             * the Internet.*/
} dns_query_t;

/* RR data type
 * All RRs have the same top level format shown below:
 *
 *                                     1  1  1  1  1  1
 *       0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                                               |
 *     /                                               /
 *     /                      NAME                     /
 *     |                                               |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                      TYPE                     |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                     CLASS                     |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                      TTL                      |
 *     |                                               |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                   RDLENGTH                    |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
 *     /                     RDATA                     /
 *     /                                               /
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
*/

typedef struct {
    char *name;             /* an owner name, i.e., the name of the node to
                             * which this resource record pertains.*/
    apr_uint16_t type;      /* two octets containing one of the RR TYPE codes.*/
    apr_uint16_t classtype; /* two octets containing one of the RR CLASS codes.*/
    apr_int32_t ttl;        /* a 32 bit signed integer that specifies the time
                             * that the resource record may be cached before
                             * the source interval of the information should
                             * again be consulted.  Zero values are interpreted
                             * to mean that the RR can only be used for the
                             * transaction in progress, and should not be
                             * cached.  For example, SOA records are always
                             * distributed with a zero TTL to prohibit caching.
                             * Zero values can also be used for extremely
                             * volatile data.*/
    apr_uint16_t rdlength;  /* an unsigned 16 bit integer that specifies the
                             * length in octets of the RDATA field.*/
    dns_rdata_t *rdata;     /* a variable length string of octets that describes
                             * the resource.  The format of this information
                             * varies according to the TYPE and CLASS of the
                             * resource record.*/
} dns_rr_t;

/* rdata payloads */

typedef struct {
    char *cname;            /* A <domain-name> which specifies the canonical
                             * or primary name for the owner.  The owner name
                             * is an alias.*/
} dns_rdata_cname_t;

typedef struct {
    apr_uint16_t preference;/* A 16 bit integer which specifies the preference
                             * given to this RR among others at the same owner
                             * Lower values are preferred.*/
    char *exchange;         /* A <domain-name> which specifies a host willing
                             * to act as a mail exchange for the owner name.*/
} dns_rdata_mx_t;

typedef struct {
    char *nsdname;          /* A <domain-name> which specifies a host which
                             * should be authoritative for the specified class
                             * and domain.*/
} dns_rdata_ns_t;


typedef struct {
    char *mname;            /* The <domain-name> of the name server that was the
                             * original or primary source of data for this zone.*/
    char *rname;            /* A <domain-name> which specifies the mailbox of
                             * the person responsible for this zone.*/
    apr_uint32_t serial;    /* The unsigned 32 bit version number of the
                             * original copy of the zone.  Zone transfers
                             * preserve this value. This value wraps and should
                             * be compared using sequence space arithmetic.*/
    apr_int32_t refresh;    /* A 32 bit time interval before the zone should be
                             * refreshed.*/
    apr_int32_t retry;      /* A 32 bit time interval that should elapse before
                             * a failed refresh should be retried.*/
    apr_int32_t expires;    /* A 32 bit time value that specifies the upper
                             * limit on the time interval that can elapse
                             * before the zone is no longer authoritative.*/
    apr_uint32_t minimum;   /* The unsigned 32 bit minimum TTL field that should
                               be exported with any RR from this zone.*/
} dns_rdata_soa_t;

typedef struct {
    char *txtdata;          /* One or more <character-string>s.*/
} dns_rdata_txt_t;

typedef struct {
    apr_uint32_t address;  /* A 32 bit Internet address */
} dns_rdata_a_t;

/* Message header data type
 * The header contains the following fields:
 *
 *                                     1  1  1  1  1  1
 *       0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                      ID                       |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                    QDCOUNT                    |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                    ANCOUNT                    |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                    NSCOUNT                    |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 *     |                    ARCOUNT                    |
 *     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
 */

/** We'll use apr_byte_t for any field < 8 bytes */
typedef struct {
    apr_uint16_t id;       /* A 16 bit identifier assigned by the program that
                            * generates any kind of query.  This identifier is
                            * copied the corresponding reply and can be used by
                            * the requester to match up replies to outstanding
                            * queries.*/
    dns_flag_t qr;         /* A one bit field that specifies whether this
                            * message is a query (OFF), or a response (ON).*/
    dns_opcode_t opcode;   /* A four bit field that specifies kind of query in
                            * this  message.  This value is set by the
                            * originator of a query and copied into the response
                            * The values are:
                            * DNS_OPCODE_QUERY       a standard query
                            * DNS_OPCODE_IQUERY      an inverse query
                            * DNS_OPCODE_STATUS      a server status request
                            * DNS_OPCODE_RESERVED    reserved for future use*/
    dns_flag_t aa;         /* Authoritative Answer - this bit is valid in
                            * responses and specifies that the responding
                            * name server is an authority for the domain name
                            * in question section.
                            * Note that the contents of the answer section may
                            * have multiple owner names because of aliases.
                            * The AA bit corresponds to the name which matches
                            * the query name, or the first owner name in the
                            * answer section.*/
    dns_flag_t tc;         /* TrunCation - specifies that this message was
                            * truncated due to length greater than that
                            * permitted on the transmission channel.*/
    dns_flag_t rd;         /* Recursion Desired - this bit may be set in a
                            * query and is copied into the response.  If RD is
                            * set, it directs the name server to pursue the
                            * query recursively.  Recursive query support is
                            * optional according to RFC 1035.*/
    int        ra;         /* Recursion Available - this be is set or cleared
                            * in a response, and denotes whether recursive
                            * query support is available in the name server.*/
    dns_flag_t z;          /* Reserved for future use.  Must be zero in all
                            * queries and responses.*/
    dns_rcode_t rcode;     /* Response code - this 4 bit field is set as part
                            * of responses.  The values have the following
                            * interpretation:
                            * DNS_SUCCESS      No error condition
                            * DNS_EFORMAT      Format error - The name server
                            *                  was unable to interpret the query
                            * DNS_ESERVER      The name server was unable to
                            *                  process this query due to a
                            *                  problem with the name server.
                            * DNS_ENAME        Meaningful only for responses
                            *                  from an authoritative name server
                            *                  this code signifies that the
                            *                  domain name referenced in the
                            *                  query does not exist.
                            * DNS_ENOIMPL      The name server does not support
                            *                  the requested kind of query.
                            * DNS_EREFUSED     The name server refuses to
                            *                  perform the specified operation
                            *                  for policy reasons.  For example
                            *                  a name server may not wish to
                            *                  provide the information to the
                            *                  particular requester, or a name
                            *                  server may not wish to perform
                            *                  a particular operation (e.g.,
                            *                  zone transfer) for particular
                            *                  data.
                            * DNS_ERESERVED    Reserved for future use.*/
    apr_uint16_t qdcount;  /* an unsigned 16 bit integer specifying the number
                            * of entries in the question section.*/
    apr_uint16_t ancount;  /* an unsigned 16 bit integer specifying the number
                            * of resource records in the answer section.*/
    apr_uint16_t nscount;  /* an unsigned 16 bit integer specifying the number
                            * of name server resource records in the authority
                            * records section.*/
    apr_uint16_t arcount;  /* an unsigned 16 bit integer specifying the number
                            * of resource records in the additional records
                            * section.*/
} dns_header_t;

/* DNS message
 *
 *     +---------------------+
 *     |        Header       |
 *     +---------------------+
 *     |       Question      | the question for the name server
 *     +---------------------+
 *     |        Answer       | RRs answering the question
 *     +---------------------+
 *     |      Authority      | RRs pointing toward an authority
 *     +---------------------+
 *     |      Additional     | RRs holding additional information
 *     +---------------------+
 */
typedef struct {
    apr_pool_t         *pool;       /* Local pool */
    conn_rec           *conn;       /* The underlying connection */
    apr_uint16_t       length;      /* Length - UDP sets this to 0, and sets
                                     * TC bit in headers if > 512 bytes */
    apr_uint16_t       bytesread;   /* Bytes of message read so far */
    int answered;                   /* Counter of answered queries so far */
    ap_filter_t        *filters_in; /* Per-message input filters */
    ap_filter_t        *filters_out;/* Per-message output filters */
    dns_header_t       *header;
    apr_array_header_t *query;
    apr_array_header_t *answer;
    apr_array_header_t *authority;
    apr_array_header_t *additional;
} dns_message_t;

/** errors.c */
DNS_DECLARE(char *) dns_get_name_type(dns_type_t type);
DNS_DECLARE(char *) dns_get_name_class(dns_class_t type);

/** protocol.c */
DNS_DECLARE(apr_status_t) dns_query_serialize(dns_query_t *q, char *data,
                                              int *dlen);
DNS_DECLARE(apr_status_t) dns_query_pserialize(dns_query_t *q,
                                               apr_pool_t *pool,
                                               char **data, int *dlen);
DNS_DECLARE(apr_status_t) dns_write_response(dns_message_t *dns,
                                             char **response,
                                             apr_size_t *len);
DNS_DECLARE(apr_status_t) dns_read_request(dns_message_t *dns,
                                           request_rec **r_in,
                                           dns_query_t **q_in);
DNS_DECLARE(dns_message_t *) dns_read_message_header(conn_rec *c);

DNS_DECLARE(apr_status_t) dns_add_rr_answer(request_rec *r, dns_rr_t *rr);
DNS_DECLARE(apr_status_t) dns_add_rr_authority(request_rec *r, dns_rr_t *rr);
DNS_DECLARE(apr_status_t) dns_add_rr_additional(request_rec *r, dns_rr_t *rr);

/** buckets.c */
extern const apr_bucket_type_t DNS_DECLARE_DATA dns_rr_answer_bucket_type;
extern const apr_bucket_type_t DNS_DECLARE_DATA dns_rr_authority_bucket_type;
extern const apr_bucket_type_t DNS_DECLARE_DATA dns_rr_additional_bucket_type;

#define BUCKET_IS_DNS_ANSWER(e) ((e)->type == &dns_rr_answer_bucket_type)
#define BUCKET_IS_DNS_AUTHORITY(e) ((e)->type == &dns_rr_authority_bucket_type)
#define BUCKET_IS_DNS_ADDITIONAL(e) ((e)->type == &dns_rr_additional_bucket_type)
#define BUCKET_IS_DNS_RR(e) (BUCKET_IS_DNS_ANSWER(e) || \
                             BUCKET_IS_DNS_AUTHORITY(e) || \
                             BUCKET_IS_DNS_ADDITIONAL(e))

DNS_DECLARE(apr_bucket *) dns_bucket_rr_answer_create (
                           const char *buf, apr_size_t length,
                           apr_pool_t *pool, apr_bucket_alloc_t *list);
DNS_DECLARE(apr_bucket *) dns_bucket_rr_answer_make (
                           apr_bucket *b, const char *buf,
                           apr_size_t length, apr_pool_t *pool);
DNS_DECLARE(apr_bucket *) dns_bucket_rr_authority_create (
                           const char *buf, apr_size_t length,
                           apr_pool_t *pool, apr_bucket_alloc_t *list);
DNS_DECLARE(apr_bucket *) dns_bucket_rr_authority_make (
                           apr_bucket *b, const char *buf,
                           apr_size_t length, apr_pool_t *pool);
DNS_DECLARE(apr_bucket *) dns_bucket_rr_additional_create (
                           const char *buf, apr_size_t length,
                           apr_pool_t *pool, apr_bucket_alloc_t *list);
DNS_DECLARE(apr_bucket *) dns_bucket_rr_additional_make (
                           apr_bucket *b, const char *buf,
                           apr_size_t length, apr_pool_t *pool);

/** rr.c */
DNS_DECLARE(void) dns_register_rr(dns_rdata_t *rdata, apr_uint16_t type);
DNS_DECLARE(dns_rr_t *) dns_create_rr(request_rec *r, const char *name,
                                            dns_type_t rrtype,
                                            dns_class_t rrclass,
                                            apr_int32_t ttl);
DNS_DECLARE(apr_status_t) dns_rr_serialize(dns_rr_t *rr, char *data, int *dlen);
DNS_DECLARE(apr_status_t) dns_rr_unserialize(apr_pool_t *pool,
                                             const char *data,
                                             dns_rr_t **rr);
DNS_DECLARE(apr_status_t) dns_rr_pserialize(dns_rr_t *rr, apr_pool_t *pool,
                                            char **data, int *dlen);

/** mod_dns.c */
DNS_DECLARE(int) dns_invoke_filter_init(ap_filter_t *filters);
DNS_DECLARE(request_rec *) dns_create_request(dns_message_t *dns);

/**
 * Hook an optional hook.  Unlike static hooks, this uses a macro
 * instead of a function.
 */
#define DNS_OPTIONAL_HOOK(name,fn,pre,succ,order) \
        APR_OPTIONAL_HOOK(dns,name,fn,pre,succ,order)

/**
 * This hook is used to allow modules to implement custom processing once a
 * DNS message header has been successfully read, but before the queries are
 * read from the socket (and dispatched as request_rec's).  Useful for
 * injecting input filters on the queries (without needing to ignore the
 * message header)
 */
APR_DECLARE_EXTERNAL_HOOK(dns, DNS, int, post_read_request,
                          (dns_message_t *dns))
APR_DECLARE_EXTERNAL_HOOK(dns, DNS, int, create_request,
                          (request_rec *r, dns_message_t *dns))
APR_DECLARE_EXTERNAL_HOOK(dns, DNS, int, handler,
                          (request_rec *r))

#ifdef __cplusplus
 }
#endif

/** ensure we pull in rrs, if needed */
#ifndef RR_H
#include "rr.h"
#endif

#endif
