Ignore:
Timestamp:
Feb 25, 2011, 9:26:54 PM (13 years ago)
Author:
Bruno Cornec
Message:
  • Update mindi-busybox to 1.18.3 to avoid problems with the tar command which is now failing on recent versions with busybox 1.7.3
File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/2.2.9/mindi-busybox/networking/dnsd.c

    r1765 r2725  
    77 * Copyright (C) 2003 Paul Sheer
    88 *
    9  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
     9 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
    1010 *
    1111 * Odd Arild Olsen started out with the sheerdns [1] of Paul Sheer and rewrote
     
    1818 */
    1919
     20#include "libbb.h"
    2021#include <syslog.h>
    21 #include "libbb.h"
    2222
    2323//#define DEBUG 1
     
    2525
    2626enum {
    27     MAX_HOST_LEN = 16,      // longest host name allowed is 15
    28     IP_STRING_LEN = 18,     // .xxx.xxx.xxx.xxx\0
    29 
    30 //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
    31     MAX_NAME_LEN = (IP_STRING_LEN + 13),
    32 
    33 /* Cannot get bigger packets than 512 per RFC1035
    34    In practice this can be set considerably smaller:
    35    Length of response packet is  header (12B) + 2*type(4B) + 2*class(4B) +
    36    ttl(4B) + rlen(2B) + r (MAX_NAME_LEN =21B) +
    37    2*querystring (2 MAX_NAME_LEN= 42B), all together 90 Byte
    38 */
    39     MAX_PACK_LEN = 512 + 1,
    40 
    41     DEFAULT_TTL = 30,       // increase this when not testing?
    42 
     27    /* can tweak this */
     28    DEFAULT_TTL = 120,
     29
     30    /* cannot get bigger packets than 512 per RFC1035. */
     31    MAX_PACK_LEN = 512,
     32    IP_STRING_LEN = sizeof(".xxx.xxx.xxx.xxx"),
     33    MAX_NAME_LEN = IP_STRING_LEN - 1 + sizeof(".in-addr.arpa"),
    4334    REQ_A = 1,
    44     REQ_PTR = 12
     35    REQ_PTR = 12,
    4536};
    4637
    47 struct dns_repl {       // resource record, add 0 or 1 to accepted dns_msg in resp
    48     uint16_t rlen;
    49     uint8_t *r;     // resource
    50     uint16_t flags;
    51 };
    52 
    53 struct dns_head {       // the message from client and first part of response mag
     38/* the message from client and first part of response msg */
     39struct dns_head {
    5440    uint16_t id;
    5541    uint16_t flags;
    56     uint16_t nquer;     // accepts 0
    57     uint16_t nansw;     // 1 in response
    58     uint16_t nauth;     // 0
    59     uint16_t nadd;      // 0
     42    uint16_t nquer;
     43    uint16_t nansw;
     44    uint16_t nauth;
     45    uint16_t nadd;
    6046};
    61 struct dns_prop {
    62     uint16_t type;
    63     uint16_t class;
     47/* Structure used to access type and class fields.
     48 * They are totally unaligned, but gcc 4.3.4 thinks that pointer of type uint16_t*
     49 * is 16-bit aligned and replaces 16-bit memcpy (in move_from_unaligned16 macro)
     50 * with aligned halfword access on arm920t!
     51 * Oh well. Slapping PACKED everywhere seems to help: */
     52struct type_and_class {
     53    uint16_t type PACKED;
     54    uint16_t class PACKED;
     55} PACKED;
     56/* element of known name, ip address and reversed ip address */
     57struct dns_entry {
     58    struct dns_entry *next;
     59    uint32_t ip;
     60    char rip[IP_STRING_LEN]; /* length decimal reversed IP */
     61    char name[1];
    6462};
    65 struct dns_entry {      // element of known name, ip address and reversed ip address
    66     struct dns_entry *next;
    67     char ip[IP_STRING_LEN];     // dotted decimal IP
    68     char rip[IP_STRING_LEN];    // length decimal reversed IP
    69     char name[MAX_HOST_LEN];
    70 };
    71 
    72 static struct dns_entry *dnsentry;
    73 static uint32_t ttl = DEFAULT_TTL;
    74 
    75 static const char *fileconf = "/etc/dnsd.conf";
    76 
    77 // Must match getopt32 call
    78 #define OPT_daemon  (option_mask32 & 0x10)
    79 #define OPT_verbose (option_mask32 & 0x20)
    80 
    81 
    82 /*
    83  * Convert host name from C-string to dns length/string.
    84  */
    85 static void convname(char *a, uint8_t *q)
    86 {
    87     int i = (q[0] == '.') ? 0 : 1;
    88     for (; i < MAX_HOST_LEN-1 && *q; i++, q++)
    89         a[i] = tolower(*q);
    90     a[0] = i - 1;
    91     a[i] = 0;
    92 }
     63
     64#define OPT_verbose (option_mask32 & 1)
     65#define OPT_silent  (option_mask32 & 2)
     66
    9367
    9468/*
    9569 * Insert length of substrings instead of dots
    9670 */
    97 static void undot(uint8_t * rip)
     71static void undot(char *rip)
    9872{
    99     int i = 0, s = 0;
     73    int i = 0;
     74    int s = 0;
     75
    10076    while (rip[i])
    10177        i++;
     
    10480            rip[i] = s;
    10581            s = 0;
    106         } else s++;
    107     }
    108 }
    109 
    110 /*
    111  * Read one line of hostname/IP from file
    112  * Returns 0 for each valid entry read, -1 at EOF
    113  * Assumes all host names are lower case only
    114  * Hostnames with more than one label are not handled correctly.
    115  * Presently the dot is copied into name without
    116  * converting to a length/string substring for that label.
    117  */
    118 static int getfileentry(FILE * fp, struct dns_entry *s)
    119 {
    120     unsigned int a,b,c,d;
    121     char *line, *r, *name;
    122 
    123  restart:
    124     line = r = xmalloc_fgets(fp);
    125     if (!r)
    126         return -1;
    127     while (*r == ' ' || *r == '\t') {
    128         r++;
    129         if (!*r || *r == '#' || *r == '\n') {
    130             free(line);
    131             goto restart; /* skipping empty/blank and commented lines  */
     82        } else {
     83            s++;
    13284        }
    13385    }
    134     name = r;
    135     while (*r != ' ' && *r != '\t')
    136         r++;
    137     *r++ = '\0';
    138     if (sscanf(r, ".%u.%u.%u.%u"+1, &a, &b, &c, &d) != 4) {
    139         free(line);
    140         goto restart; /* skipping wrong lines */
    141     }
    142 
    143     sprintf(s->ip, ".%u.%u.%u.%u"+1, a, b, c, d);
    144     sprintf(s->rip, ".%u.%u.%u.%u", d, c, b, a);
    145     undot((uint8_t*)s->rip);
    146     convname(s->name, (uint8_t*)name);
    147 
    148     if (OPT_verbose)
    149         fprintf(stderr, "\tname:%s, ip:%s\n", &(s->name[1]),s->ip);
    150 
    151     free(line);
    152     return 0;
    15386}
    15487
     
    15689 * Read hostname/IP records from file
    15790 */
    158 static void dnsentryinit(void)
     91static struct dns_entry *parse_conf_file(const char *fileconf)
    15992{
    160     FILE *fp;
    161     struct dns_entry *m, *prev;
    162 
    163     prev = dnsentry = NULL;
    164     fp = xfopen(fileconf, "r");
    165 
    166     while (1) {
    167         m = xzalloc(sizeof(*m));
     93    char *token[2];
     94    parser_t *parser;
     95    struct dns_entry *m, *conf_data;
     96    struct dns_entry **nextp;
     97
     98    conf_data = NULL;
     99    nextp = &conf_data;
     100
     101    parser = config_open(fileconf);
     102    while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
     103        struct in_addr ip;
     104        uint32_t v32;
     105
     106        if (inet_aton(token[1], &ip) == 0) {
     107            bb_error_msg("error at line %u, skipping", parser->lineno);
     108            continue;
     109        }
     110
     111        if (OPT_verbose)
     112            bb_error_msg("name:%s, ip:%s", token[0], token[1]);
     113
     114        /* sizeof(*m) includes 1 byte for m->name[0] */
     115        m = xzalloc(sizeof(*m) + strlen(token[0]) + 1);
    168116        /*m->next = NULL;*/
    169         if (getfileentry(fp, m))
    170             break;
    171 
    172         if (prev == NULL)
    173             dnsentry = m;
    174         else
    175             prev->next = m;
    176         prev = m;
    177     }
    178     fclose(fp);
     117        *nextp = m;
     118        nextp = &m->next;
     119
     120        m->name[0] = '.';
     121        strcpy(m->name + 1, token[0]);
     122        undot(m->name);
     123        m->ip = ip.s_addr; /* in network order */
     124        v32 = ntohl(m->ip);
     125        /* inverted order */
     126        sprintf(m->rip, ".%u.%u.%u.%u",
     127            (uint8_t)(v32),
     128            (uint8_t)(v32 >> 8),
     129            (uint8_t)(v32 >> 16),
     130            (v32 >> 24)
     131        );
     132        undot(m->rip);
     133    }
     134    config_close(parser);
     135    return conf_data;
    179136}
    180137
    181138/*
    182  * Look query up in dns records and return answer if found
    183  * qs is the query string, first byte the string length
    184  */
    185 static int table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
     139 * Look query up in dns records and return answer if found.
     140 */
     141static char *table_lookup(struct dns_entry *d,
     142        uint16_t type,
     143        char* query_string)
    186144{
    187     int i;
    188     struct dns_entry *d = dnsentry;
    189 
    190     do {
     145    while (d) {
     146        unsigned len = d->name[0];
     147        /* d->name[len] is the last (non NUL) char */
    191148#if DEBUG
    192         char *p,*q;
    193         q = (char *)&(qs[1]);
    194         p = &(d->name[1]);
    195         fprintf(stderr, "\n%s: %d/%d p:%s q:%s %d",
    196             __FUNCTION__, (int)strlen(p), (int)(d->name[0]),
    197             p, q, (int)strlen(q));
     149        char *p, *q;
     150        q = query_string + 1;
     151        p = d->name + 1;
     152        fprintf(stderr, "%d/%d p:%s q:%s %d\n",
     153            (int)strlen(p), len,
     154            p, q, (int)strlen(q)
     155        );
    198156#endif
    199         if (type == REQ_A) { /* search by host name */
    200             for (i = 1; i <= (int)(d->name[0]); i++)
    201                 if (tolower(qs[i]) != d->name[i])
    202                     break;
    203             if (i > (int)(d->name[0])) {
    204                 strcpy((char *)as, d->ip);
     157        if (type == htons(REQ_A)) {
     158            /* search by host name */
     159            if (len != 1 || d->name[1] != '*') {
     160/* we are lax, hope no name component is ever >64 so that length
     161 * (which will be represented as 'A','B'...) matches a lowercase letter.
     162 * Actually, I think false matches are hard to construct.
     163 * Example.
     164 * [31] len is represented as '1', [65] as 'A', [65+32] as 'a'.
     165 * [65]   <65 same chars>[31]<31 same chars>NUL
     166 * [65+32]<65 same chars>1   <31 same chars>NUL
     167 * This example seems to be the minimal case when false match occurs.
     168 */
     169                if (strcasecmp(d->name, query_string) != 0)
     170                    goto next;
     171            }
     172            return (char *)&d->ip;
    205173#if DEBUG
    206                 fprintf(stderr, " OK as:%s\n", as);
     174            fprintf(stderr, "Found IP:%x\n", (int)d->ip);
    207175#endif
    208                 return 0;
    209             }
    210         } else if (type == REQ_PTR) { /* search by IP-address */
    211             if (!strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
    212                 strcpy((char *)as, d->name);
    213                 return 0;
    214             }
     176            return 0;
    215177        }
     178        /* search by IP-address */
     179        if ((len != 1 || d->name[1] != '*')
     180        /* we assume (do not check) that query_string
     181         * ends in ".in-addr.arpa" */
     182         && strncmp(d->rip, query_string, strlen(d->rip)) == 0
     183        ) {
     184#if DEBUG
     185            fprintf(stderr, "Found name:%s\n", d->name);
     186#endif
     187            return d->name;
     188        }
     189 next:
    216190        d = d->next;
    217     } while (d);
    218     return -1;
     191    }
     192
     193    return NULL;
    219194}
    220 
    221195
    222196/*
    223197 * Decode message and generate answer
    224198 */
    225 static int process_packet(uint8_t * buf)
     199/* RFC 1035
     200...
     201Whenever an octet represents a numeric quantity, the left most bit
     202in the diagram is the high order or most significant bit.
     203That is, the bit labeled 0 is the most significant bit.
     204...
     205
     2064.1.1. Header section format
     207      0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
     208    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     209    |                      ID                       |
     210    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     211    |QR|   OPCODE  |AA|TC|RD|RA| 0  0  0|   RCODE   |
     212    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     213    |                    QDCOUNT                    |
     214    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     215    |                    ANCOUNT                    |
     216    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     217    |                    NSCOUNT                    |
     218    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     219    |                    ARCOUNT                    |
     220    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     221ID      16 bit random identifier assigned by querying peer.
     222        Used to match query/response.
     223QR      message is a query (0), or a response (1).
     224OPCODE  0   standard query (QUERY)
     225        1   inverse query (IQUERY)
     226        2   server status request (STATUS)
     227AA      Authoritative Answer - this bit is valid in responses.
     228        Responding name server is an authority for the domain name
     229        in question section. Answer section may have multiple owner names
     230        because of aliases.  The AA bit corresponds to the name which matches
     231        the query name, or the first owner name in the answer section.
     232TC      TrunCation - this message was truncated.
     233RD      Recursion Desired - this bit may be set in a query and
     234        is copied into the response.  If RD is set, it directs
     235        the name server to pursue the query recursively.
     236        Recursive query support is optional.
     237RA      Recursion Available - this be is set or cleared in a
     238        response, and denotes whether recursive query support is
     239        available in the name server.
     240RCODE   Response code.
     241        0   No error condition
     242        1   Format error
     243        2   Server failure - server was unable to process the query
     244            due to a problem with the name server.
     245        3   Name Error - meaningful only for responses from
     246            an authoritative name server. The referenced domain name
     247            does not exist.
     248        4   Not Implemented.
     249        5   Refused.
     250QDCOUNT number of entries in the question section.
     251ANCOUNT number of records in the answer section.
     252NSCOUNT number of records in the authority records section.
     253ARCOUNT number of records in the additional records section.
     254
     2554.1.2. Question section format
     256
     257The section contains QDCOUNT (usually 1) entries, each of this format:
     258      0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
     259    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     260    /                     QNAME                     /
     261    /                                               /
     262    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     263    |                     QTYPE                     |
     264    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     265    |                     QCLASS                    |
     266    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     267QNAME   a domain name represented as a sequence of labels, where
     268        each label consists of a length octet followed by that
     269        number of octets. The domain name terminates with the
     270        zero length octet for the null label of the root. Note
     271        that this field may be an odd number of octets; no
     272        padding is used.
     273QTYPE   a two octet type of the query.
     274          1 a host address [REQ_A const]
     275          2 an authoritative name server
     276          3 a mail destination (Obsolete - use MX)
     277          4 a mail forwarder (Obsolete - use MX)
     278          5 the canonical name for an alias
     279          6 marks the start of a zone of authority
     280          7 a mailbox domain name (EXPERIMENTAL)
     281          8 a mail group member (EXPERIMENTAL)
     282          9 a mail rename domain name (EXPERIMENTAL)
     283         10 a null RR (EXPERIMENTAL)
     284         11 a well known service description
     285         12 a domain name pointer [REQ_PTR const]
     286         13 host information
     287         14 mailbox or mail list information
     288         15 mail exchange
     289         16 text strings
     290       0x1c IPv6?
     291        252 a request for a transfer of an entire zone
     292        253 a request for mailbox-related records (MB, MG or MR)
     293        254 a request for mail agent RRs (Obsolete - see MX)
     294        255 a request for all records
     295QCLASS  a two octet code that specifies the class of the query.
     296          1 the Internet
     297        (others are historic only)
     298        255 any class
     299
     3004.1.3. Resource Record format
     301
     302The answer, authority, and additional sections all share the same format:
     303a variable number of resource records, where the number of records
     304is specified in the corresponding count field in the header.
     305Each resource record has this format:
     306      0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
     307    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     308    /                                               /
     309    /                      NAME                     /
     310    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     311    |                      TYPE                     |
     312    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     313    |                     CLASS                     |
     314    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     315    |                      TTL                      |
     316    |                                               |
     317    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     318    |                   RDLENGTH                    |
     319    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
     320    /                     RDATA                     /
     321    /                                               /
     322    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     323NAME    a domain name to which this resource record pertains.
     324TYPE    two octets containing one of the RR type codes.  This
     325        field specifies the meaning of the data in the RDATA field.
     326CLASS   two octets which specify the class of the data in the RDATA field.
     327TTL     a 32 bit unsigned integer that specifies the time interval
     328        (in seconds) that the record may be cached.
     329RDLENGTH a 16 bit integer, length in octets of the RDATA field.
     330RDATA   a variable length string of octets that describes the resource.
     331        The format of this information varies according to the TYPE
     332        and CLASS of the resource record.
     333        If the TYPE is A and the CLASS is IN, it's a 4 octet IP address.
     334
     3354.1.4. Message compression
     336
     337In order to reduce the size of messages, domain names coan be compressed.
     338An entire domain name or a list of labels at the end of a domain name
     339is replaced with a pointer to a prior occurance of the same name.
     340
     341The pointer takes the form of a two octet sequence:
     342    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     343    | 1  1|                OFFSET                   |
     344    +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
     345The first two bits are ones.  This allows a pointer to be distinguished
     346from a label, since the label must begin with two zero bits because
     347labels are restricted to 63 octets or less.  The OFFSET field specifies
     348an offset from the start of the message (i.e., the first octet
     349of the ID field in the domain header).
     350A zero offset specifies the first byte of the ID field, etc.
     351Domain name in a message can be represented as either:
     352   - a sequence of labels ending in a zero octet
     353   - a pointer
     354   - a sequence of labels ending with a pointer
     355 */
     356static int process_packet(struct dns_entry *conf_data,
     357        uint32_t conf_ttl,
     358        uint8_t *buf)
    226359{
    227360    struct dns_head *head;
    228     struct dns_prop *qprop;
    229     struct dns_repl outr;
    230     void *next, *from, *answb;
    231 
    232     uint8_t answstr[MAX_NAME_LEN + 1];
    233     int lookup_result, type, len, packet_len;
    234     uint16_t flags;
    235 
    236     answstr[0] = '\0';
     361    struct type_and_class *unaligned_type_class;
     362    const char *err_msg;
     363    char *query_string;
     364    char *answstr;
     365    uint8_t *answb;
     366    uint16_t outr_rlen;
     367    uint16_t outr_flags;
     368    uint16_t type;
     369    uint16_t class;
     370    int query_len;
    237371
    238372    head = (struct dns_head *)buf;
    239373    if (head->nquer == 0) {
    240         bb_error_msg("no queries");
    241         return -1;
    242     }
    243 
    244     if (head->flags & 0x8000) {
    245         bb_error_msg("ignoring response packet");
    246         return -1;
    247     }
    248 
    249     from = (void *)&head[1];    //  start of query string
    250     next = answb = from + strlen((char *)from) + 1 + sizeof(struct dns_prop);   // where to append answer block
    251 
    252     outr.rlen = 0;          // may change later
    253     outr.r = NULL;
    254     outr.flags = 0;
    255 
    256     qprop = (struct dns_prop *)(answb - 4);
    257     type = ntohs(qprop->type);
    258 
    259     // only let REQ_A and REQ_PTR pass
    260     if (!(type == REQ_A || type == REQ_PTR)) {
    261         goto empty_packet;  /* we can't handle the query type */
    262     }
    263 
    264     if (ntohs(qprop->class) != 1 /* class INET */ ) {
    265         outr.flags = 4; /* not supported */
     374        bb_error_msg("packet has 0 queries, ignored");
     375        return 0; /* don't reply */
     376    }
     377    if (head->flags & htons(0x8000)) { /* QR bit */
     378        bb_error_msg("response packet, ignored");
     379        return 0; /* don't reply */
     380    }
     381    /* QR = 1 "response", RCODE = 4 "Not Implemented" */
     382    outr_flags = htons(0x8000 | 4);
     383    err_msg = NULL;
     384
     385    /* start of query string */
     386    query_string = (void *)(head + 1);
     387    /* caller guarantees strlen is <= MAX_PACK_LEN */
     388    query_len = strlen(query_string) + 1;
     389    /* may be unaligned! */
     390    unaligned_type_class = (void *)(query_string + query_len);
     391    query_len += sizeof(*unaligned_type_class);
     392    /* where to append answer block */
     393    answb = (void *)(unaligned_type_class + 1);
     394
     395    /* OPCODE != 0 "standard query"? */
     396    if ((head->flags & htons(0x7800)) != 0) {
     397        err_msg = "opcode != 0";
    266398        goto empty_packet;
    267399    }
    268     /* we only support standard queries */
    269 
    270     if ((ntohs(head->flags) & 0x7800) != 0)
     400    move_from_unaligned16(class, &unaligned_type_class->class);
     401    if (class != htons(1)) { /* not class INET? */
     402        err_msg = "class != 1";
    271403        goto empty_packet;
    272 
    273     // We have a standard query
    274     bb_info_msg("%s", (char *)from);
    275     lookup_result = table_lookup(type, answstr, (uint8_t*)from);
    276     if (lookup_result != 0) {
    277         outr.flags = 3 | 0x0400;    //name do not exist and auth
     404    }
     405    move_from_unaligned16(type, &unaligned_type_class->type);
     406    if (type != htons(REQ_A) && type != htons(REQ_PTR)) {
     407        /* we can't handle this query type */
     408//TODO: happens all the time with REQ_AAAA (0x1c) requests - implement those?
     409        err_msg = "type is !REQ_A and !REQ_PTR";
    278410        goto empty_packet;
    279411    }
    280     if (type == REQ_A) {    // return an address
    281         struct in_addr a;
    282         if (!inet_aton((char*)answstr, &a)) {//dotted dec to long conv
    283             outr.flags = 1; /* Frmt err */
    284             goto empty_packet;
     412
     413    /* look up the name */
     414    answstr = table_lookup(conf_data, type, query_string);
     415#if DEBUG
     416    /* Shows lengths instead of dots, unusable for !DEBUG */
     417    bb_error_msg("'%s'->'%s'", query_string, answstr);
     418#endif
     419    outr_rlen = 4;
     420    if (answstr && type == htons(REQ_PTR)) {
     421        /* returning a host name */
     422        outr_rlen = strlen(answstr) + 1;
     423    }
     424    if (!answstr
     425     || (unsigned)(answb - buf) + query_len + 4 + 2 + outr_rlen > MAX_PACK_LEN
     426    ) {
     427        /* QR = 1 "response"
     428         * AA = 1 "Authoritative Answer"
     429         * RCODE = 3 "Name Error" */
     430        err_msg = "name is not found";
     431        outr_flags = htons(0x8000 | 0x0400 | 3);
     432        goto empty_packet;
     433    }
     434
     435    /* Append answer Resource Record */
     436    memcpy(answb, query_string, query_len); /* name, type, class */
     437    answb += query_len;
     438    move_to_unaligned32((uint32_t *)answb, htonl(conf_ttl));
     439    answb += 4;
     440    move_to_unaligned16((uint16_t *)answb, htons(outr_rlen));
     441    answb += 2;
     442    memcpy(answb, answstr, outr_rlen);
     443    answb += outr_rlen;
     444
     445    /* QR = 1 "response",
     446     * AA = 1 "Authoritative Answer",
     447     * TODO: need to set RA bit 0x80? One user says nslookup complains
     448     * "Got recursion not available from SERVER, trying next server"
     449     * "** server can't find HOSTNAME"
     450     * RCODE = 0 "success"
     451     */
     452    if (OPT_verbose)
     453        bb_error_msg("returning positive reply");
     454    outr_flags = htons(0x8000 | 0x0400 | 0);
     455    /* we have one answer */
     456    head->nansw = htons(1);
     457
     458 empty_packet:
     459    if ((outr_flags & htons(0xf)) != 0) { /* not a positive response */
     460        if (OPT_verbose) {
     461            bb_error_msg("%s, %s",
     462                err_msg,
     463                OPT_silent ? "dropping query" : "sending error reply"
     464            );
    285465        }
    286         memcpy(answstr, &a.s_addr, 4);  // save before a disappears
    287         outr.rlen = 4;          // uint32_t IP
    288     } else
    289         outr.rlen = strlen((char *)answstr) + 1;    // a host name
    290     outr.r = answstr;           // 32 bit ip or a host name
    291     outr.flags |= 0x0400;           /* authority-bit */
    292     // we have an answer
    293     head->nansw = htons(1);
    294 
    295     // copy query block to answer block
    296     len = answb - from;
    297     memcpy(answb, from, len);
    298     next += len;
    299 
    300     // and append answer rr
    301     *(uint32_t *) next = htonl(ttl);
    302     next += 4;
    303     *(uint16_t *) next = htons(outr.rlen);
    304     next += 2;
    305     memcpy(next, (void *)answstr, outr.rlen);
    306     next += outr.rlen;
    307 
    308  empty_packet:
    309 
    310     flags = ntohs(head->flags);
    311     // clear rcode and RA, set responsebit and our new flags
    312     flags |= (outr.flags & 0xff80) | 0x8000;
    313     head->flags = htons(flags);
    314     head->nauth = head->nadd = htons(0);
    315     head->nquer = htons(1);
    316 
    317     packet_len = (uint8_t *)next - buf;
    318     return packet_len;
     466        if (OPT_silent)
     467            return 0;
     468    }
     469    head->flags |= outr_flags;
     470    head->nauth = head->nadd = 0;
     471    head->nquer = htons(1); // why???
     472
     473    return answb - buf;
    319474}
    320475
    321 /*
    322  * Exit on signal
    323  */
    324 static void interrupt(int x)
    325 {
    326     /* unlink("/var/run/dnsd.lock"); */
    327     bb_error_msg("interrupt, exiting\n");
    328     exit(2);
    329 }
    330 
    331 int dnsd_main(int argc, char **argv);
    332 int dnsd_main(int argc, char **argv)
     476int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
     477int dnsd_main(int argc UNUSED_PARAM, char **argv)
    333478{
    334479    const char *listen_interface = "0.0.0.0";
     480    const char *fileconf = "/etc/dnsd.conf";
     481    struct dns_entry *conf_data;
     482    uint32_t conf_ttl = DEFAULT_TTL;
    335483    char *sttl, *sport;
    336     len_and_sockaddr *lsa;
    337     int udps;
     484    len_and_sockaddr *lsa, *from, *to;
     485    unsigned lsa_size;
     486    int udps, opts;
    338487    uint16_t port = 53;
    339     uint8_t buf[MAX_PACK_LEN];
    340 
    341     getopt32(argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
    342     //if (option_mask32 & 0x1) // -i
    343     //if (option_mask32 & 0x2) // -c
    344     if (option_mask32 & 0x4) // -t
    345         ttl = xatou_range(sttl, 1, 0xffffffff);
    346     if (option_mask32 & 0x8) // -p
     488    /* Ensure buf is 32bit aligned (we need 16bit, but 32bit can't hurt) */
     489    uint8_t buf[MAX_PACK_LEN + 1] ALIGN4;
     490
     491    opts = getopt32(argv, "vsi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport);
     492    //if (opts & (1 << 0)) // -v
     493    //if (opts & (1 << 1)) // -s
     494    //if (opts & (1 << 2)) // -i
     495    //if (opts & (1 << 3)) // -c
     496    if (opts & (1 << 4)) // -t
     497        conf_ttl = xatou_range(sttl, 1, 0xffffffff);
     498    if (opts & (1 << 5)) // -p
    347499        port = xatou_range(sport, 1, 0xffff);
    348 
    349     if (OPT_verbose) {
    350         bb_info_msg("listen_interface: %s", listen_interface);
    351         bb_info_msg("ttl: %d, port: %d", ttl, port);
    352         bb_info_msg("fileconf: %s", fileconf);
    353     }
    354 
    355     if (OPT_daemon) {
     500    if (opts & (1 << 6)) { // -d
    356501        bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
    357502        openlog(applet_name, LOG_PID, LOG_DAEMON);
     
    359504    }
    360505
    361     dnsentryinit();
    362 
    363     signal(SIGINT, interrupt);
    364     /* why? signal(SIGPIPE, SIG_IGN); */
    365     signal(SIGHUP, SIG_IGN);
    366 #ifdef SIGTSTP
    367     signal(SIGTSTP, SIG_IGN);
    368 #endif
    369 #ifdef SIGURG
    370     signal(SIGURG, SIG_IGN);
    371 #endif
     506    conf_data = parse_conf_file(fileconf);
    372507
    373508    lsa = xdotted2sockaddr(listen_interface, port);
    374     udps = xsocket(lsa->sa.sa_family, SOCK_DGRAM, 0);
    375     xbind(udps, &lsa->sa, lsa->len);
    376     /* xlisten(udps, 50); - ?!! DGRAM sockets are never listened on I think? */
    377     bb_info_msg("Accepting UDP packets on %s",
    378             xmalloc_sockaddr2dotted(&lsa->sa));
     509    udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
     510    xbind(udps, &lsa->u.sa, lsa->len);
     511    socket_want_pktinfo(udps); /* needed for recv_from_to to work */
     512    lsa_size = LSA_LEN_SIZE + lsa->len;
     513    from = xzalloc(lsa_size);
     514    to = xzalloc(lsa_size);
     515
     516    {
     517        char *p = xmalloc_sockaddr2dotted(&lsa->u.sa);
     518        bb_error_msg("accepting UDP packets on %s", p);
     519        free(p);
     520    }
    379521
    380522    while (1) {
    381523        int r;
    382         socklen_t fromlen = lsa->len;
    383 // FIXME: need to get *DEST* address (to which of our addresses
    384 // this query was directed), and reply from the same address.
    385 // Or else we can exhibit usual UDP ugliness:
    386 // [ip1.multihomed.ip2] <=  query to ip1  <= peer
    387 // [ip1.multihomed.ip2] => reply from ip2 => peer (confused)
    388         r = recvfrom(udps, buf, sizeof(buf), 0, &lsa->sa, &fromlen);
    389         if (OPT_verbose)
    390             bb_info_msg("Got UDP packet");
    391         if (r < 12 || r > 512) {
    392             bb_error_msg("invalid packet size");
     524        /* Try to get *DEST* address (to which of our addresses
     525         * this query was directed), and reply from the same address.
     526         * Or else we can exhibit usual UDP ugliness:
     527         * [ip1.multihomed.ip2] <=  query to ip1  <= peer
     528         * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
     529        memcpy(to, lsa, lsa_size);
     530        r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
     531        if (r < 12 || r > MAX_PACK_LEN) {
     532            bb_error_msg("packet size %d, ignored", r);
    393533            continue;
    394534        }
    395         r = process_packet(buf);
     535        if (OPT_verbose)
     536            bb_error_msg("got UDP packet");
     537        buf[r] = '\0'; /* paranoia */
     538        r = process_packet(conf_data, conf_ttl, buf);
    396539        if (r <= 0)
    397540            continue;
    398         sendto(udps, buf, r, 0, &lsa->sa, fromlen);
     541        send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);
    399542    }
    400543    return 0;
Note: See TracChangeset for help on using the changeset viewer.