home *** CD-ROM | disk | FTP | other *** search
/ PC-Online 1996 May / PCOnline_05_1996.bin / linux / source / n / bind / bind-4.001 / bind-4~ / bind-4.9.3-BETA9 / named / ns_req.c < prev    next >
C/C++ Source or Header  |  1994-07-23  |  46KB  |  1,794 lines

  1. #if !defined(lint) && !defined(SABER)
  2. static char sccsid[] = "@(#)ns_req.c    4.47 (Berkeley) 7/1/91";
  3. static char rcsid[] = "$Id: ns_req.c,v 4.9.1.22 1994/07/23 23:23:56 vixie Exp $";
  4. #endif /* not lint */
  5.  
  6. /*
  7.  * ++Copyright++ 1986, 1988, 1990
  8.  * -
  9.  * Copyright (c) 1986, 1988, 1990
  10.  *    The Regents of the University of California.  All rights reserved.
  11.  * 
  12.  * Redistribution and use in source and binary forms, with or without
  13.  * modification, are permitted provided that the following conditions
  14.  * are met:
  15.  * 1. Redistributions of source code must retain the above copyright
  16.  *    notice, this list of conditions and the following disclaimer.
  17.  * 2. Redistributions in binary form must reproduce the above copyright
  18.  *    notice, this list of conditions and the following disclaimer in the
  19.  *    documentation and/or other materials provided with the distribution.
  20.  * 3. All advertising materials mentioning features or use of this software
  21.  *    must display the following acknowledgement:
  22.  *     This product includes software developed by the University of
  23.  *     California, Berkeley and its contributors.
  24.  * 4. Neither the name of the University nor the names of its contributors
  25.  *    may be used to endorse or promote products derived from this software
  26.  *    without specific prior written permission.
  27.  * 
  28.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  29.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  30.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  31.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  32.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  33.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  34.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  37.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  38.  * SUCH DAMAGE.
  39.  * -
  40.  * Portions Copyright (c) 1993 by Digital Equipment Corporation.
  41.  * 
  42.  * Permission to use, copy, modify, and distribute this software for any
  43.  * purpose with or without fee is hereby granted, provided that the above
  44.  * copyright notice and this permission notice appear in all copies, and that
  45.  * the name of Digital Equipment Corporation not be used in advertising or
  46.  * publicity pertaining to distribution of the document or software without
  47.  * specific, written prior permission.
  48.  * 
  49.  * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL
  50.  * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES
  51.  * OF MERCHANTABILITY AND FITNESS.   IN NO EVENT SHALL DIGITAL EQUIPMENT
  52.  * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  53.  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  54.  * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
  55.  * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
  56.  * SOFTWARE.
  57.  * -
  58.  * --Copyright--
  59.  */
  60.  
  61. #include <sys/param.h>
  62. #include <sys/uio.h>
  63. #include <sys/file.h>
  64. #include <sys/socket.h>
  65. #include <netinet/in.h>
  66. #include <arpa/nameser.h>
  67. #include <arpa/inet.h>
  68. #include <fcntl.h>
  69. #include <syslog.h>
  70. #include <errno.h>
  71. #include <stdio.h>
  72. #include <resolv.h>
  73.  
  74. #include "named.h"
  75.  
  76. struct addinfo {
  77.     char    *a_dname;        /* domain name */
  78.     u_int    a_class;        /* class for address */
  79. };
  80.  
  81. enum req_action { Finish, Refuse, Return };
  82.  
  83. static enum req_action    req_query __P((HEADER *hp, u_char **cpp, u_char *eom,
  84.                        struct qstream *qsp,
  85.                        int *buflenp, int *msglenp,
  86.                        u_char *msg, int dfd,
  87.                        struct sockaddr_in *from));
  88.  
  89. #ifdef INVQ
  90. static enum req_action    req_iquery __P((HEADER *hp, u_char **cpp, u_char *eom,
  91.                     int *buflenp, u_char *msg,
  92.                     struct sockaddr_in *from));
  93. #endif
  94.  
  95. static void        fwritemsg __P((FILE *, u_char *, int)),
  96.             doaxfr __P((struct namebuf *, FILE *,
  97.                     struct namebuf *, int)),
  98.             startxfr __P((struct qstream *, struct namebuf *,
  99.                       u_char *, int, int, const char *)),
  100.             printSOAdata __P((struct databuf));
  101.  
  102. #ifdef ALLOW_UPDATES
  103. static int        InitDynUpdate __P((register HEADER *hp,
  104.                        char *msg,
  105.                        int msglen,
  106.                        u_char *startcp,
  107.                        struct sockaddr_in *from,
  108.                        struct qstream *qsp,
  109.                        int dfd));
  110. #endif
  111.  
  112. static struct addinfo    addinfo[NADDRECS];
  113. static void        addname __P((char *, u_int16_t));
  114.  
  115. /*
  116.  * Process request using database; assemble and send response.
  117.  */
  118. void
  119. ns_req(msg, msglen, buflen, qsp, from, dfd)
  120.     u_char *msg;
  121.     int msglen, buflen;
  122.     struct qstream *qsp;
  123.     struct sockaddr_in *from;
  124.     int dfd;
  125. {
  126.     register HEADER *hp = (HEADER *) msg;
  127.     u_char *cp, *eom;
  128.     enum req_action action;
  129.  
  130. #ifdef DEBUG
  131.     if (debug > 3) {
  132.         fprintf(ddt, "ns_req(from=[%s].%d)\n",
  133.             inet_ntoa(from->sin_addr), ntohs(from->sin_port));
  134.         fp_query(msg, ddt);
  135.     }
  136. #endif
  137.  
  138.     /*
  139.      * XXX - this decision should be made by our caller, not by us.
  140.      */
  141.     if (hp->qr) {
  142.         ns_resp(msg, msglen);
  143.  
  144.         /* Now is a safe time for housekeeping */
  145.         if (needs_prime_cache)
  146.             prime_cache();
  147.  
  148.         return;
  149.     }
  150.  
  151.     /* its a query and these bits have no business
  152.      * being set. will later simplify work if we can
  153.      * safely assume these are always 0 when a query
  154.      * comes in
  155.      */
  156.     hp->aa = hp->ra = 0;
  157.  
  158.     hp->rcode = NOERROR;
  159.     cp = msg + HFIXEDSZ;
  160.     eom = msg + msglen;
  161.  
  162.     dnptrs[0] = msg;
  163.     dnptrs[1] = NULL;
  164.  
  165.     free_addinfo();    /* sets addcount to zero */
  166.     dnptrs[0] = NULL;
  167.  
  168.     switch (hp->opcode) {
  169.     case QUERY:
  170.         action = req_query(hp, &cp, eom, qsp,
  171.                    &buflen, &msglen,
  172.                    msg, dfd, from);
  173.         break;
  174.  
  175. #ifdef INVQ
  176.     case IQUERY:
  177.         action = req_iquery(hp, &cp, eom, &buflen, msg, from);
  178.         break;
  179. #endif
  180.  
  181. #ifdef ALLOW_UPDATES
  182. #define FORWARDED 1000
  183. /*
  184.  * In a sense the following constant should be defined in <arpa/nameser.h>,
  185.  * since it is returned here in place of a response code if the update was
  186.  * forwarded, and the response codes are defined in nameser.h.  On the other
  187.  * hand, though, this constant is only seen in this file.  The assumption
  188.  * here is that none of the other return codes equals this one (a good
  189.  * assumption, since they only occupy 4 bits over-the-wire)
  190.  */
  191.         /* Call InitDynUpdate for all dynamic update requests */
  192.         case UPDATEM:
  193.         case UPDATEMA:
  194.         case UPDATED:
  195.         case UPDATEDA:
  196.         case UPDATEA:
  197.                 n = InitDynUpdate(hp, msg, msglen, cp, from, qsp, dfd);
  198.                 if (n == FORWARDED) {
  199.             /* Return directly because InitDynUpdate
  200.              * forwarded the query to the primary, so we
  201.              * will send response later
  202.              */
  203.             action = Return;
  204.         } else {
  205.             /* Either sucessful primary update or failure;
  206.              * return response code to client
  207.              */
  208.             action = Finish;
  209.         }
  210. #endif /* ALLOW_UPDATES */
  211.  
  212.     case ZONEREF:
  213.         dprintf(1, (ddt, "Refresh Zone\n"));
  214.         /*FALLTHROUGH*/
  215.  
  216.     default:
  217.         dprintf(1, (ddt, "ns_req: Opcode %d not implemented\n",
  218.                 hp->opcode));
  219.         /* XXX - should syslog, limited by haveComplained */
  220.         hp->qdcount = 0;
  221.         hp->ancount = 0;
  222.         hp->nscount = 0;
  223.         hp->arcount = 0;
  224.         hp->rcode = NOTIMP;
  225.         action = Finish;
  226.     }
  227.  
  228.     /*
  229.      * vector via internal opcode.  (yes, it was even uglier before.)
  230.      */
  231.     switch (action) {
  232.     case Return:
  233.         return;
  234.     case Refuse:
  235.         hp->rcode = REFUSED;
  236.         /*FALLTHROUGH*/
  237.     case Finish:
  238.         /* rest of the function handles this case */
  239.         break;
  240.     default:
  241.         syslog(LOG_CRIT, "bad action variable in ns_req() -- %d",
  242.                (int) action);
  243.         return;    /* XXX - should really exit here */
  244.     }
  245.  
  246.     /*
  247.      * apply final polish
  248.      */
  249.     hp->qr = 1;        /* set Response flag */
  250.     if (NoRecurse)
  251.         hp->ra = 0;    /* No recursion; maybe we're a root server */
  252.     else
  253.         hp->ra = 1;    /* Recursion is Available */
  254.     hp->ancount = htons(hp->ancount);
  255.     if (addcount) {
  256.         int n = doaddinfo(hp, cp, buflen);
  257.         cp += n;
  258.         buflen -= n;
  259.     }
  260.  
  261.     dprintf(1, (ddt, "ns_req: answer -> [%s].%d fd=%d id=%d %s\n",
  262.             inet_ntoa(from->sin_addr), 
  263.             ntohs(from->sin_port),
  264.             (qsp == QSTREAM_NULL) ?dfd :qsp->s_rfd, 
  265.             ntohs(hp->id), local(from) == NULL ? "Remote" : "Local"));
  266. #ifdef DEBUG
  267.     if (debug >= 10)
  268.         fp_query(msg, ddt);
  269. #endif
  270.     if (qsp == QSTREAM_NULL) {
  271.         if (sendto(dfd, msg, cp - msg, 0,
  272.                (struct sockaddr *)from,
  273.                sizeof(*from)) < 0) {
  274.             if (!haveComplained((char*)from->sin_addr.s_addr,
  275.                         sendtoStr))
  276.                 syslog(LOG_NOTICE,
  277.                        "ns_req: sendto([%s].%d): %m",
  278.                        inet_ntoa(from->sin_addr),
  279.                        ntohs(from->sin_port));
  280.             nameserIncr(from->sin_addr, nssSendtoErr);
  281.         }
  282.         nameserIncr(from->sin_addr, nssSentAns);
  283.     } else {
  284.         (void) writemsg(qsp->s_rfd, msg, cp - msg);
  285.         sq_done(qsp);
  286.     }
  287.  
  288.     if (needs_prime_cache) {
  289.         prime_cache();        /* Now is a safe time */
  290.     }
  291. }
  292.  
  293. static enum req_action
  294. req_query(hp, cpp, eom, qsp, buflenp, msglenp, msg, dfd, from)
  295.     HEADER *hp;
  296.     u_char **cpp;
  297.     u_char *eom;
  298.     struct qstream *qsp;
  299.     u_char *msg;
  300.     int *buflenp, *msglenp, dfd;
  301.     struct sockaddr_in *from;
  302. {
  303.     int n, class, type, count, foundname, founddata, omsglen, cname;
  304.     u_int16_t id;
  305.     u_char **dpp, *omsg, *answers;
  306.     char dnbuf[MAXDNAME], *dname, *fname;
  307.     struct hashbuf *htp;
  308.     struct databuf *nsp[NSMAX];
  309.     struct namebuf *np;
  310.     struct qinfo *qp;
  311.     struct netinfo *lp;
  312.  
  313.     nameserIncr(from->sin_addr, nssRcvdQ);
  314. #ifdef DATUMREFCNT
  315.     nsp[0] = NULL;
  316. #endif
  317.  
  318.     dpp = dnptrs;
  319.     *dpp++ = msg;
  320.     *dpp = NULL;
  321.  
  322.     /* valid queries have one question and zero answers */
  323.     if ((ntohs(hp->qdcount) != 1)
  324.         || hp->ancount
  325.         || hp->nscount
  326.         || hp->arcount) {
  327.         dprintf(1, (ddt, "FORMERR Query header counts wrong\n"));
  328.         hp->qdcount = 0;
  329.         hp->ancount = 0;
  330.         hp->nscount = 0;
  331.         hp->arcount = 0;
  332.         hp->rcode = FORMERR;
  333.         return (Finish);
  334.     }
  335.  
  336.     /*
  337.      * Get domain name, class, and type.
  338.      */
  339.     if ((**cpp & INDIR_MASK) == 0) {
  340.         *dpp++ = *cpp;    /* remember name for compression */
  341.     }
  342.     *dpp = NULL;
  343.     n = dn_expand(msg, eom, *cpp, dnbuf, sizeof dnbuf);
  344.     if (n < 0) {
  345.         dprintf(1, (ddt, "FORMERR Query expand name failed\n"));
  346.         hp->rcode = FORMERR;
  347.         return (Finish);
  348.     }
  349.     *cpp += n;
  350.     GETSHORT(type, *cpp);
  351.     GETSHORT(class, *cpp);
  352.     if (*cpp > eom) {
  353.         dprintf(1, (ddt, "FORMERR Query message length short\n"));
  354.         hp->rcode = FORMERR;
  355.         return (Finish);
  356.     }
  357.     if (*cpp < eom) {
  358.         dprintf(6, (ddt,"message length > received message\n"));
  359.         *msglenp = *cpp - msg;
  360.     }
  361.  
  362.     qtypeIncr(type);
  363.  
  364.     /*
  365.      * Process query.
  366.      */
  367.     if (type == T_AXFR) {
  368.         /* refuse request if not a TCP connection */
  369.         if (qsp == QSTREAM_NULL) {
  370.             syslog(LOG_INFO,
  371.                    "rejected UDP AXFR from [%s].%u for \"%s\"",
  372.                    inet_ntoa(from->sin_addr),
  373.                    ntohs(from->sin_port),
  374.                    *dnbuf ? dnbuf : ".");
  375.             return (Refuse);
  376.         }
  377.         /* the position of this is subtle. */
  378.         nameserIncr(from->sin_addr, nssRcvdAXFR);
  379. #ifdef XFRNETS
  380.         if (xfrnets) {
  381.             /* if xfrnets was specified, peer address
  382.              * must be on it.  should probably allow
  383.              * for negation some day.
  384.              */
  385.             if (!addr_on_netlist(from->sin_addr, xfrnets)) {
  386.                 syslog(LOG_INFO,
  387.                        "unapproved AXFR from [%s].%u for %s",
  388.                        inet_ntoa(from->sin_addr),
  389.                        ntohs(from->sin_port),
  390.                        *dnbuf ? dnbuf : ".");
  391.                 return (Refuse);
  392.             }
  393.         }
  394. #endif /*XFRNETS*/
  395.         dnptrs[0] = NULL;    /* don't compress names */
  396.         hp->rd = 0;        /* recursion not possible */
  397.         syslog(LOG_INFO, "approved AXFR from [%s].%d for \"%s\"",
  398.                inet_ntoa(from->sin_addr),
  399.                ntohs(from->sin_port),
  400.                *dnbuf ? dnbuf : ".");
  401.     }
  402.     *buflenp -= *msglenp;
  403.     count = 0;
  404.     foundname = 0;
  405.     founddata = 0;
  406.     dname = dnbuf;
  407.     cname = 0;
  408.  
  409. #ifdef QRYLOG
  410.     if (qrylog) {
  411.         syslog(LOG_INFO, "XX /%s/%s/%s",
  412.                inet_ntoa(from->sin_addr), 
  413.                (dname[0] == '\0') ?"." :dname, 
  414.                p_type(type));
  415.     }
  416. #endif /*QRYLOG*/
  417.  
  418. try_again:
  419.     dprintf(1, (ddt, "req: nlookup(%s) id %d type=%d\n",
  420.             dname, hp->id, type));
  421.     htp = hashtab;        /* lookup relative to root */
  422.     if ((np = nlookup(dname, &htp, &fname, 0)) == NULL)
  423.         fname = "";
  424.     dprintf(1, (ddt, "req: %s '%s' as '%s' (cname=%d)\n",
  425.             np == NULL ? "missed" : "found",
  426.             dname, fname, cname));
  427.  
  428. #ifdef LOCALDOM
  429.     /*
  430.      * if nlookup failed to find the name then
  431.      * see if there are any '.''s in the name
  432.      * if not then add local domain name to the
  433.      * name and try again.
  434.      */
  435.     if (!np && localdomain && !strchr(dname, '.')) {
  436.         (void) strcat(dname, ".");
  437.         (void) strcat(dname, localdomain);
  438.         dprintf(1, (ddt,"req: nlookup(%s) type=%d\n", dname, type));
  439.         htp = hashtab;
  440.         np = nlookup(dname, &htp, &fname, 0);
  441.         }
  442. #endif /*LOCALDOM*/
  443.  
  444. #ifdef YPKLUDGE
  445.     /* Some braindamaged resolver software will not 
  446.        recognize internet addresses in dot notation and 
  447.        send out address  queries for "names" such as 
  448.        128.93.8.1.  This kludge will prevent those 
  449.        from flooding higher level servers.
  450.        We simply claim to be authoritative and that
  451.        the domain doesn't exist.
  452.        Note that we could return the address but we
  453.        don't do that in order to encourage that broken
  454.        software is fixed.
  455.     */
  456.  
  457.     if (!np && type == T_A && class == C_IN && dname) {
  458.         struct in_addr ina;
  459.  
  460.         if (inet_aton(dname, &ina)) {
  461.             hp->rcode = NXDOMAIN;
  462.             hp->aa = 1;
  463.             dprintf(3, (ddt, "ypkludge: hit as '%s'\n", dname));
  464.             return (Finish);
  465.         }
  466.     }
  467. #endif /*YPKLUDGE*/
  468.  
  469.     if ((!np) || (fname != dname))
  470.         goto fetchns;
  471.  
  472. #ifdef SECURE_ZONES
  473.     if (np->n_data) {
  474.         struct zoneinfo *zp;
  475.  
  476.         zp = &zones[np->n_data->d_zone];
  477.         if (zp->secure_nets
  478.             && !addr_on_netlist(from->sin_addr, zp->secure_nets)) {
  479.             dprintf(1, (ddt,
  480.                     "REFUSED Unauthorized request from %s\n", 
  481.                     inet_ntoa(from->sin_addr)));
  482.             syslog(LOG_INFO, "Unauthorized request %s from %s",
  483.                    dname, inet_ntoa(from->sin_addr));
  484.             return (Refuse);
  485.         }
  486.     }
  487. #endif
  488.     foundname++;
  489.     answers = *cpp;
  490.     count = *cpp - msg;
  491.  
  492. #ifdef NCACHE
  493.     /* if this is a NXDOMAIN, will have only one databuf
  494.      * whose d_rcode field will be NXDOMAIN. So we can go home
  495.      * right here. -ve $ing: anant@isi.edu
  496.      */
  497.     if (np->n_data != NULL && !stale(np->n_data)) {
  498.         if (np->n_data->d_rcode == NXDOMAIN) {
  499. #ifdef RETURNSOA
  500.             n = finddata(np, class, T_SOA, hp, &dname,
  501.                 buflenp, &count);
  502.             if (n != 0 ) {
  503.                 if (hp->rcode == NOERROR_NODATA) {
  504.                     /* this should not occur */
  505.                     hp->rcode = NOERROR;
  506.                     return (Finish);
  507.                 }
  508.                 *cpp += n;
  509.                 *buflenp -= n;
  510.                 *msglenp += n;
  511.                 hp->rcode = NXDOMAIN;
  512.                 hp->nscount = htons((u_int16_t)count);
  513.                 hp->aa = 1;    
  514.                 return (Finish);
  515.             }
  516.             else
  517.                 goto fetchns;
  518. #else
  519.             hp->rcode = NXDOMAIN;
  520.             hp->aa = 1;
  521.             return (Finish);
  522. #endif
  523.         }
  524.     }
  525.  
  526.     /* if not NXDOMAIN, the NOERROR_NODATA record might be
  527.      * anywhere in the chain. have to go through the grind.
  528.      */
  529. #endif /*NCACHE*/
  530.  
  531.     n = finddata(np, class, type, hp, &dname, buflenp, &count);
  532.     if (n == 0) {
  533.         /* NO data available.  Refuse AXFR requests, or
  534.          * look for better servers for other requests.
  535.          */
  536.         if (type == T_AXFR) {
  537.             dprintf(1, (ddt, "T_AXFR refused: no data\n"));
  538.             return (Refuse);
  539.         } else {
  540.             goto fetchns;
  541.         }
  542.     }
  543.  
  544. #ifdef NCACHE
  545.     if (hp->rcode == NOERROR_NODATA) {
  546.         hp->rcode = NOERROR;
  547.         founddata = 1;
  548.         return (Finish);
  549.     }
  550. #endif
  551.  
  552.     *cpp += n;
  553.     *buflenp -= n;
  554.     *msglenp += n;
  555.     hp->ancount += count;
  556.     if (fname != dname && type != T_CNAME && type != T_ANY) {
  557.         if (cname++ >= MAXCNAMES) {
  558.             dprintf(3, (ddt,
  559.                     "resp: leaving, MAXCNAMES exceeded\n"));
  560.             hp->rcode = SERVFAIL;
  561.             return (Finish);
  562.         }
  563.         goto try_again;
  564.     }
  565.     founddata = 1;
  566.     dprintf(3, (ddt,
  567.             "req: foundname=%d, count=%d, founddata=%d, cname=%d\n",
  568.             foundname, count, founddata, cname));
  569.  
  570.     if ((lp = local(from)) != NULL) 
  571.         sort_response(answers, count, lp, *cpp);
  572.     if (type == T_AXFR) {
  573.         hp->ancount = htons(hp->ancount);
  574.         startxfr(qsp, np, msg, *cpp - msg, class, dname);
  575.         sqrm(qsp);
  576.         return (Return);
  577.     }
  578.  
  579. #ifdef notdef
  580.     /*
  581.      * If we found an authoritative answer,
  582.      * we're done.
  583.      */
  584.     if (hp->aa)
  585.         return (Finish);
  586. #endif
  587.  
  588. fetchns:
  589.     /*
  590.       * Look for name servers to refer to and fill in the authority
  591.       * section or record the address for forwarding the query
  592.       * (recursion desired).
  593.       */
  594. #ifdef DATUMREFCNT
  595.     free_nsp(nsp);
  596. #endif
  597.     nsp[0] = NULL;
  598.     count = 0;
  599.     switch (findns(&np, class, nsp, &count, 0)) {
  600.     case NXDOMAIN:
  601.         if (!foundname) {
  602.             hp->rcode = NXDOMAIN;
  603.         }
  604.         dprintf(3, (ddt, "req: leaving (%s, rcode %d)\n",
  605.                 dname, hp->rcode));
  606.         if (class != C_ANY) {
  607.             hp->aa = 1;
  608.             /* XXX:    should return SOA if founddata == 0,
  609.              *    but old named's are confused by an SOA
  610.              *    in the auth. section if there's no error.
  611.              */
  612.             if (foundname == 0 && np) {
  613.                 n = doaddauth(hp, *cpp, *buflenp, np, nsp[0]);
  614.                 *cpp += n;
  615.                 *buflenp -= n;
  616. #ifdef ADDAUTH
  617.             } else if (hp->ancount) {
  618.                 /* don't add NS records for NOERROR NODATA
  619.                    as some severs can get confused */
  620. #ifdef DATUMREFCNT
  621.                 free_nsp(nsp);
  622. #endif
  623.                 switch (findns(&np, class, nsp, &count, 1)) {
  624.                 case NXDOMAIN:
  625.                 case SERVFAIL:
  626.                     break;
  627.                 default:
  628.                     if (np) {
  629.                         n = add_data(np, nsp, *cpp,
  630.                                  *buflenp);
  631.                         if (n < 0) {
  632.                             hp->tc = 1;
  633.                             n = (-n);
  634.                         }
  635.                         *cpp += n;
  636.                         *buflenp -= n;
  637.                         hp->nscount = 
  638.                             htons((u_int16_t)
  639.                                   count);
  640.                     }
  641.                 }
  642. #endif /*ADDAUTH*/
  643.             }
  644.         }
  645. #ifdef DATUMREFCNT
  646.         free_nsp(nsp);
  647. #endif
  648.         return (Finish);
  649.  
  650.     case SERVFAIL:
  651.         if (!founddata && !(forward_only && fwdtab)) {
  652.             hp->rcode = SERVFAIL;
  653. #ifdef DATUMREFCNT
  654.             free_nsp(nsp);
  655. #endif
  656.             return (Finish);
  657.         }
  658.     }
  659.  
  660.     /*
  661.      *  If we successfully found the answer in the cache,
  662.      *  or this is not a recursive query, or we are purposely
  663.      *  never recursing, then add the nameserver references
  664.      *  ("authority section") here and we're done.
  665.      */
  666.     if (founddata || (!hp->rd) || NoRecurse) {
  667.         n = add_data(np, nsp, *cpp, *buflenp);
  668.         if (n < 0) {
  669.             hp->tc = 1;
  670.             n = (-n);
  671.         }
  672.         *cpp += n;
  673.         *buflenp -= n;
  674.         hp->nscount = htons((u_int16_t)count);
  675. #ifdef DATUMREFCNT
  676.         free_nsp(nsp);
  677. #endif
  678.         return (Finish);
  679.     }
  680.  
  681.     /*
  682.      *  At this point, we don't have the answer, but we do
  683.      *  have some NS's to try.  If the user would like us
  684.      *  to recurse, create the initial query.  If a cname
  685.      *  is involved, we need to build a new query and save
  686.      *  the old one in cmsg/cmsglen.
  687.      */
  688.     if (cname) {
  689.         omsg = (u_char *)malloc((unsigned) *msglenp);
  690.         if (omsg == (u_char *)NULL) {
  691.             dprintf(1, (ddt, "ns_req: malloc fail\n"));
  692.             syslog(LOG_ERR, "ns_req: Out Of Memory");
  693.             hp->rcode = SERVFAIL;
  694. #ifdef DATUMREFCNT
  695.             free_nsp(nsp);
  696. #endif
  697.             return (Finish);
  698.         }
  699.         id = hp->id;
  700.         hp->ancount = htons(hp->ancount);
  701.         omsglen = *msglenp;
  702.         bcopy(msg, omsg, omsglen);
  703.         *msglenp = res_mkquery(QUERY, dname, class, type,
  704.                        NULL, 0, NULL, msg,
  705.                        *msglenp + *buflenp);
  706.     }
  707.     n = ns_forw(nsp, msg, *msglenp, from, qsp, dfd, &qp, dname, np);
  708.     if (n != FW_OK && cname)
  709.         free(omsg);
  710.     switch (n) {
  711.     case FW_OK:
  712.         if (cname) {
  713.             qp->q_cname = cname;
  714.             qp->q_cmsg = omsg;
  715.             qp->q_cmsglen = omsglen;
  716.             qp->q_id = id;
  717.         }
  718.         break;
  719.     case FW_DUP:
  720.         break;        /* Duplicate request dropped */
  721.     case FW_NOSERVER:
  722.         /* 
  723.         ** Don't go into an infinite loop if 
  724.         ** the admin gave root NS records in the cache
  725.         ** file without giving address records
  726.         ** for the root servers.
  727.         */
  728.         if (np) {
  729.             if (np->n_dname[0] == '\0') {
  730.                 dprintf(1, (ddt,
  731.                         "ns_req: no address for root NS\n"
  732.                         ));
  733.                 syslog(LOG_ERR, 
  734.                        "ns_req: no address for root server");
  735.                 hp->rcode = SERVFAIL;
  736. #ifdef DATUMREFCNT
  737.                 free_nsp(nsp);
  738. #endif
  739.                 return (Finish);
  740.             }
  741. #ifdef    VALIDATE
  742.             /*
  743.              * we need to kill all the NS records here as
  744.              * validate will fail as we are talking to the parent
  745.              * server
  746.              */
  747.             delete_all(np, class, T_NS);
  748. #endif
  749.             np = np->n_parent;
  750.         }
  751.         goto fetchns;    /* Try again. */
  752.     case FW_SERVFAIL:
  753.         hp->rcode = SERVFAIL;
  754. #ifdef DATUMREFCNT
  755.         free_nsp(nsp);
  756. #endif
  757.         return (Finish);
  758.     }
  759. #ifdef DATUMREFCNT
  760.     free_nsp(nsp);
  761. #endif
  762.     return (Return);
  763. }
  764.  
  765. #ifdef INVQ
  766. static enum req_action
  767. req_iquery(hp, cpp, eom, buflenp, msg, from)
  768.     HEADER *hp;
  769.     u_char **cpp, *eom;
  770.     int *buflenp;
  771.     u_char *msg;
  772.     struct sockaddr_in *from;
  773. {
  774.     register struct invbuf *ip;
  775.     int dlen, alen, i, n, type, class, count;
  776.     char dnbuf[MAXDNAME], anbuf[PACKETSZ], *data, *fname;
  777.     struct namebuf *np;
  778.     struct qinfo *qp;
  779.     struct databuf *dp;
  780.  
  781.     nameserIncr(from->sin_addr, nssRcvdIQ);
  782.  
  783.     hp->ancount = htons(hp->ancount);
  784.     if ((hp->ancount != 1)
  785.         || hp->qdcount
  786.         || hp->nscount
  787.         || hp->arcount) {
  788.         dprintf(1, (ddt, "FORMERR IQuery header counts wrong\n"));
  789.         hp->qdcount = 0;
  790.         hp->ancount = 0;
  791.         hp->nscount = 0;
  792.         hp->arcount = 0;
  793.         hp->rcode = FORMERR;
  794.         return (Finish);
  795.     }
  796.  
  797.     /*
  798.      * Skip domain name, get class, and type.
  799.      */
  800.     if ((n = dn_skipname(*cpp, eom)) < 0) {
  801.         dprintf(1, (ddt, "FORMERR IQuery packet name problem\n"));
  802.         hp->rcode = FORMERR;
  803.         return (Finish);
  804.     }
  805.     *cpp += n;
  806.     GETSHORT(type, *cpp);
  807.     GETSHORT(class, *cpp);
  808.     *cpp += INT32SZ;    /* ttl */
  809.     GETSHORT(dlen, *cpp);
  810.     *cpp += dlen;
  811.     if (*cpp != eom) {
  812.         dprintf(1, (ddt, "FORMERR IQuery message length off\n"));
  813.         hp->rcode = FORMERR;
  814.         return (Finish);
  815.     }
  816.  
  817.     /*
  818.      * not all inverse queries are handled.
  819.      */
  820.     switch (type) {
  821.     case T_A:
  822.     case T_UID:
  823.     case T_GID:
  824.         break;
  825.     default:
  826.         return (Refuse);
  827.     }
  828.     dprintf(1, (ddt, "req: IQuery class %d type %d\n", class, type));
  829.  
  830.     fname = (char *)msg + HFIXEDSZ;
  831.     bcopy(fname, anbuf, alen = (char *)*cpp - fname);
  832.     data = anbuf + alen - dlen;
  833.     *cpp = (u_char *)fname;
  834.     *buflenp -= HFIXEDSZ;
  835.     count = 0;
  836.     for (ip = invtab[dhash((u_char *)data, dlen)];
  837.          ip != NULL;
  838.          ip = ip->i_next) {
  839.         for (i = 0; i < INVBLKSZ; i++) {
  840.             if ((np = ip->i_dname[i]) == NULL)
  841.                 break;
  842.             dprintf(5, (ddt, "dname = %d\n", np->n_dname));
  843.             for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
  844.                 if (!match(dp, class, type))
  845.                     continue;
  846.                 if (dp->d_size != dlen ||
  847.                     bcmp(dp->d_data, data, dlen))
  848.                     continue;
  849.                 getname(np, dnbuf, sizeof(dnbuf));
  850.                 dprintf(2, (ddt, "req: IQuery found %s\n",
  851.                         dnbuf));
  852.                 *buflenp -= QFIXEDSZ;
  853.                 n = dn_comp(dnbuf, *cpp, *buflenp, NULL, NULL);
  854.                 if (n < 0) {
  855.                     hp->tc = 1;
  856.                     return (Finish);
  857.                 }
  858.                 *cpp += n;
  859.                 PUTSHORT((u_int16_t)dp->d_type, *cpp);
  860.                 PUTSHORT((u_int16_t)dp->d_class, *cpp);
  861.                 *buflenp -= n;
  862.                 count++;
  863.             }
  864.         }
  865.     }
  866.     dprintf(1, (ddt, "req: IQuery %d records\n", count));
  867.     hp->qdcount = htons((u_int16_t)count);
  868.     if (alen > *buflenp) {
  869.         hp->tc = 1;
  870.         return (Finish);
  871.     }
  872.     bcopy(anbuf, *cpp, alen);
  873.     *cpp += alen;
  874.     return (Finish);
  875. }
  876. #endif
  877.  
  878. static void
  879. fwritemsg(rfp, msg, msglen)
  880.     FILE *rfp;
  881.     u_char *msg;
  882.     int msglen;
  883. {
  884.     u_char len[INT16SZ];
  885.  
  886.     __putshort(msglen, len);
  887.     if (fwrite((char *)len, INT16SZ, 1, rfp) != 1 ||
  888.         fwrite((char *)msg, msglen, 1, rfp) != 1) {
  889.         dprintf(1, (ddt, "fwrite failed %d\n", errno));
  890.     }
  891. }
  892.  
  893. /*
  894.  *  Test a datum for validity and return non-zero if it is out of date.
  895.  */
  896. int
  897. stale(dp)
  898.     register struct databuf *dp;
  899. {
  900.     register struct zoneinfo *zp = &zones[dp->d_zone];
  901.  
  902.     switch (zp->z_type) {
  903.  
  904.     case Z_PRIMARY:
  905.         return (0);
  906.  
  907.     case Z_SECONDARY:
  908. #ifdef STUBS
  909.     case Z_STUB:
  910. #endif
  911.         /*
  912.          * Check to see whether a secondary zone
  913.          * has expired; if so clear authority flag
  914.          * for zone and return true.  If lastupdate
  915.          * is in the future, assume zone is up-to-date.
  916.          */
  917.         if ((int32_t)(tt.tv_sec - zp->z_lastupdate)
  918.             > (int32_t)zp->z_expire) {
  919.             dprintf(1, (ddt,
  920.                     "stale: secondary zone %s expired\n",
  921.                     zp->z_origin));
  922.             if (!haveComplained(zp->z_origin, (char*)stale)) {
  923.                 syslog(LOG_ERR,
  924.                        "secondary zone \"%s\" expired",
  925.                        zp->z_origin);
  926.             }
  927.             zp->z_flags &= ~Z_AUTH;
  928.             return (1);
  929.         }
  930.         return (0);
  931.  
  932.     case Z_CACHE:
  933.         if (dp->d_flags & DB_F_HINT || dp->d_ttl >= tt.tv_sec)
  934.             return (0);
  935.         dprintf(3, (ddt, "stale: ttl %d %d (x%x)\n",
  936.                 dp->d_ttl, dp->d_ttl - tt.tv_sec, dp->d_flags));
  937.         return (1);
  938.  
  939.     default:
  940.         /* FALLTHROUGH */ ;
  941.  
  942.     }
  943.     abort();
  944.     /* NOTREACHED */
  945. }
  946.  
  947. /*
  948.  * Copy databuf into a resource record for replies.
  949.  * Return size of RR if OK, -1 if buffer is full.
  950.  */
  951. int
  952. make_rr(name, dp, buf, buflen, doadd)
  953.     char *name;
  954.     register struct databuf *dp;
  955.     u_char *buf;
  956.     int buflen, doadd;
  957. {
  958.     register u_char *cp;
  959.     u_char *cp1, *sp;
  960.     struct zoneinfo *zp;
  961.     register int32_t n;
  962.     register int32_t ttl;
  963.     u_char **edp = dnptrs + sizeof dnptrs / sizeof dnptrs[0];
  964.  
  965.     dprintf(5, (ddt, "make_rr(%s, %x, %x, %d, %d) %d zone %d ttl %d\n",
  966.             name, dp, buf,
  967.             buflen, doadd, dp->d_size, dp->d_zone, dp->d_ttl));
  968.  
  969. #ifdef    NCACHE
  970.     if (dp->d_rcode
  971. #ifdef RETURNSOA
  972.     && dp->d_rcode != NXDOMAIN
  973. #endif
  974.     ) {
  975.         syslog(LOG_CRIT, "make_rr d_rcode %d", dp->d_rcode);
  976. #ifdef DEBUG
  977.         if (debug) abort();
  978. #endif
  979.         return (-1);    /* XXX We should exit here */
  980.     }
  981. #endif
  982.     zp = &zones[dp->d_zone];
  983.     /* check for outdated RR before updating dnptrs by dn_comp() (???) */
  984.     if (zp->z_type == Z_CACHE) {
  985.         ttl = dp->d_ttl - (u_int32_t) tt.tv_sec;
  986.         if ((dp->d_flags & DB_F_HINT) || (ttl < 0)) {
  987.             dprintf(3, (ddt,
  988.                     "make_rr: %d=>0, x%x\n",
  989.                     ttl, dp->d_flags));        /* XXX */
  990.             ttl = 0;
  991.         }
  992.     } else {
  993.         if (dp->d_ttl)
  994.             ttl = dp->d_ttl;
  995.         else
  996.             ttl = zp->z_minimum;        /* really default */
  997. #ifdef notdef /* don't decrease ttl based on time since verification */
  998.         if (zp->z_type == Z_SECONDARY) {
  999.             /*
  1000.              * Set ttl to value received from primary,
  1001.              * less time since we verified it (but never
  1002.              * less than a small positive value).
  1003.              */
  1004.             ttl -= tt.tv_sec - zp->z_lastupdate;
  1005.             if (ttl <= 0)
  1006.                 ttl = 120;
  1007.         }
  1008. #endif
  1009.     }
  1010.  
  1011.     buflen -= RRFIXEDSZ;
  1012. #if defined(RETURNSOA) && defined(NCACHE)
  1013.     if (dp->d_rcode == NXDOMAIN) {
  1014.         name = (char *)dp->d_data;
  1015.         name += strlen(name) +1;
  1016.         name += strlen(name) +1;
  1017.         name += 5 * INT32SZ;
  1018.     }
  1019. #endif
  1020.     if ((n = dn_comp(name, buf, buflen, dnptrs, edp)) < 0)
  1021.         return (-1);
  1022.     cp = buf + n;
  1023.     buflen -= n;
  1024.     PUTSHORT((u_int16_t)dp->d_type, cp);
  1025.     PUTSHORT((u_int16_t)dp->d_class, cp);
  1026.     PUTLONG(ttl, cp);
  1027.     sp = cp;
  1028.     cp += INT16SZ;
  1029.     switch (dp->d_type) {
  1030.     case T_CNAME:
  1031.     case T_MG:
  1032.     case T_MR:
  1033.     case T_PTR:
  1034.         n = dn_comp((char *)dp->d_data, cp, buflen, dnptrs, edp);
  1035.         if (n < 0)
  1036.             return (-1);
  1037.         PUTSHORT((u_int16_t)n, sp);
  1038.         cp += n;
  1039.         break;
  1040.  
  1041.     case T_MB:
  1042.     case T_NS:
  1043.         /* Store domain name in answer */
  1044.         n = dn_comp((char *)dp->d_data, cp, buflen, dnptrs, edp);
  1045.         if (n < 0)
  1046.             return (-1);
  1047.         PUTSHORT((u_int16_t)n, sp);
  1048.         cp += n;
  1049.         if (doadd)
  1050.             addname((char*)dp->d_data, dp->d_class);
  1051.         break;
  1052.  
  1053.     case T_SOA:
  1054.     case T_MINFO:
  1055.     case T_RP:
  1056.         cp1 = dp->d_data;
  1057.         n = dn_comp((char *)cp1, cp, buflen, dnptrs, edp);
  1058.         if (n < 0)
  1059.             return (-1);
  1060.         cp += n;
  1061.         buflen -= dp->d_type == T_SOA ? n + 5 * INT32SZ : n;
  1062.         cp1 += strlen((char *)cp1) + 1;
  1063.         n = dn_comp((char *)cp1, cp, buflen, dnptrs, edp);
  1064.         if (n < 0)
  1065.             return (-1);
  1066.         cp += n;
  1067.         if (dp->d_type == T_SOA) {
  1068.             cp1 += strlen((char *)cp1) + 1;
  1069.             bcopy(cp1, cp, (n = 5 * INT32SZ));
  1070.             cp += n;
  1071.         }
  1072.         n = (u_int16_t)((cp - sp) - INT16SZ);
  1073.         PUTSHORT((u_int16_t)n, sp);
  1074.         break;
  1075.  
  1076.     case T_MX:
  1077.     case T_AFSDB:
  1078.     case T_RT:
  1079.         /* cp1 == our data/ cp == data of RR */
  1080.         cp1 = dp->d_data;
  1081.  
  1082.          /* copy preference */
  1083.          bcopy(cp1, cp, INT16SZ);
  1084.          cp += INT16SZ;
  1085.          cp1 += INT16SZ;
  1086.          buflen -= INT16SZ;
  1087.  
  1088.         n = dn_comp((char *)cp1, cp, buflen, dnptrs, edp);
  1089.           if (n < 0)
  1090.               return (-1);
  1091.           cp += n;
  1092.  
  1093.           /* save data length */
  1094.         n = (u_int16_t)((cp - sp) - INT16SZ);
  1095.           PUTSHORT((u_int16_t)n, sp);
  1096.         if (doadd)
  1097.             addname((char*)cp1, dp->d_class);
  1098.         break;
  1099.  
  1100.     default:
  1101.         if (dp->d_size > buflen)
  1102.             return (-1);
  1103.         bcopy(dp->d_data, cp, dp->d_size);
  1104.         PUTSHORT((u_int16_t)dp->d_size, sp);
  1105.         cp += dp->d_size;
  1106.     }
  1107.     return (cp - buf);
  1108. }
  1109.  
  1110. #if defined(__STDC__) || defined(__GNUC__)
  1111. static void
  1112. addname(register char *name,
  1113.     u_int16_t class)
  1114. #else
  1115. static void
  1116. addname(name, class)
  1117.     register char    *name;
  1118.     u_int16_t    class;
  1119. #endif
  1120. {
  1121.     register struct addinfo *ap;
  1122.     register int n;
  1123.  
  1124.     for (ap = addinfo, n = addcount; --n >= 0; ap++)
  1125.         if (strcasecmp(ap->a_dname, name) == 0)
  1126.             return;
  1127.     
  1128.  
  1129.     /* add domain name to additional section */
  1130.     if (addcount < NADDRECS) {
  1131.         addcount++;
  1132.         ap->a_dname = (char *)malloc(strlen(name)+1);
  1133.         strcpy(ap->a_dname,name);
  1134.         ap->a_class = class;
  1135.     }
  1136. }
  1137.  
  1138. /*
  1139.  * Lookup addresses for names in addinfo and put into the message's
  1140.  * additional section.
  1141.  */
  1142. int
  1143. doaddinfo(hp, msg, msglen)
  1144.     HEADER *hp;
  1145.     u_char *msg;
  1146.     int msglen;
  1147. {
  1148.     register struct namebuf *np;
  1149.     register struct databuf *dp;
  1150.     register struct addinfo *ap;
  1151.     register u_char *cp;
  1152.     struct hashbuf *htp;
  1153.     char *fname;
  1154.     int n, count;
  1155.  
  1156.     dprintf(3, (ddt, "doaddinfo() addcount = %d\n", addcount));
  1157.  
  1158.     if (hp->tc) {
  1159.         dprintf(4, (ddt, "doaddinfo(): tc already set, bailing\n"));
  1160.         return (0);
  1161.     }
  1162.  
  1163.     count = 0;
  1164.     cp = msg;
  1165.     for (ap = addinfo; --addcount >= 0; ap++) {
  1166.         int    foundstale = 0,
  1167.             foundany = 0,
  1168.             save_count = count,
  1169.             save_msglen = msglen;
  1170.         u_char    *save_cp = cp;
  1171.  
  1172.         dprintf(3, (ddt, "do additional '%s'\n", ap->a_dname));
  1173.         htp = hashtab;    /* because "nlookup" stomps on arg. */
  1174.         np = nlookup(ap->a_dname, &htp, &fname, 0);
  1175.         if (np == NULL || fname != ap->a_dname)
  1176.             goto next_rr;
  1177.         dprintf(3, (ddt, "found it\n"));
  1178.         /* look for the data */
  1179.         for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
  1180.             if ( (!match(dp, (int)ap->a_class, T_A))
  1181.               && (!match(dp, C_IN, T_A))
  1182.                ) {
  1183.                 continue;
  1184.             }
  1185.             foundany++;
  1186.             if (stale(dp)) {
  1187.                 foundstale++;
  1188.                 dprintf(1, (ddt,
  1189.                         "doaddinfo: stale entry '%s'%s\n",
  1190.                         np->n_dname,
  1191.                         (dp->d_flags&DB_F_HINT)
  1192.                             ? " hint"
  1193.                             : ""
  1194.                         ));
  1195.                 continue;
  1196.             }
  1197. #ifdef    NCACHE
  1198.             if (dp->d_rcode)
  1199.                 continue;
  1200. #endif
  1201.             /*
  1202.              *  Should be smart and eliminate duplicate
  1203.              *  data here.    XXX
  1204.              */
  1205.             if ((n = make_rr(ap->a_dname, dp, cp, msglen, 0)) < 0){
  1206.                 /* truncation in the additional-data section
  1207.                  * is not all that serious.  we do not set TC,
  1208.                  * since the answer and authority sections are
  1209.                  * OK; however, since we're not setting TC we
  1210.                  * have to make sure that none of the RR's for
  1211.                  * this name go out (!TC implies that all
  1212.                  * {name,type} appearances are complete -- and
  1213.                  * since we only do A RR's here, the name is
  1214.                  * the key).    vixie, 23apr93
  1215.                  */
  1216.                 cp = save_cp;
  1217.                 msglen = save_msglen;
  1218.                 count = save_count;
  1219.                 break;
  1220.             }
  1221.             dprintf(5, (ddt,
  1222.                     "addinfo: adding address data n = %d\n",
  1223.                     n));
  1224.             cp += n;
  1225.             msglen -= n;
  1226.             count++;
  1227.         }
  1228. next_rr:    if (foundstale) {
  1229.             /* Cache invalidate the address RR's */
  1230.             delete_all(np, (int)ap->a_class, T_A);
  1231.         }
  1232.         if (foundstale || !foundany) {
  1233.             /* ask a real server for this info */
  1234.             (void) sysquery(ap->a_dname, (int)ap->a_class, T_A,
  1235.                     NULL, 0);
  1236.         }
  1237.         free(ap->a_dname);
  1238.     }
  1239.     hp->arcount = htons((u_int16_t)count);
  1240.     return (cp - msg);
  1241. }
  1242.  
  1243. int
  1244. doaddauth(hp, cp, buflen, np, dp)
  1245.     register HEADER *hp;
  1246.     u_char *cp;
  1247.     int buflen;
  1248.     struct namebuf *np;
  1249.     struct databuf *dp;
  1250. {
  1251.     char dnbuf[MAXDNAME];
  1252.     int n;
  1253.  
  1254.     getname(np, dnbuf, sizeof(dnbuf));
  1255.     if (stale(dp)) {
  1256.         dprintf(1, (ddt,
  1257.                 "doaddauth: can't add stale '%s' (%d)\n",
  1258.                 dnbuf, buflen));
  1259.         return (0);
  1260.     }
  1261.     n = make_rr(dnbuf, dp, cp, buflen, 1);
  1262.     if (n <= 0) {
  1263.         dprintf(1, (ddt,
  1264.                 "doaddauth: can't add oversize '%s' (%d) (n=%d)\n",
  1265.                 dnbuf, buflen, n));
  1266.         if (n < 0) {
  1267.             hp->tc = 1;
  1268.         }
  1269.         return (0);
  1270.     }
  1271.     hp->nscount = htons((u_int16_t)1);
  1272.     return (n);
  1273. }
  1274.  
  1275. /*
  1276.  * Do a zone transfer (or a recursive part of a zone transfer).
  1277.  * SOA record already sent.
  1278.  *
  1279.  * top always refers to the domain at the top of the zone being transferred.
  1280.  * np refers to a domain inside the zone being transferred,
  1281.  *    which will be equal to top if this is the first call,
  1282.  *    or will be a subdomain below top if this is a recursive call,
  1283.  * rfp is a stdio file to which output is sent.
  1284.  */
  1285. static void
  1286. doaxfr(np, rfp, top, class)
  1287.     register struct namebuf *np;
  1288.     FILE *rfp;
  1289.     struct namebuf *top;
  1290.     int class;        /* Class to transfer */
  1291. {
  1292.     register struct databuf *dp;
  1293.     register int n;
  1294.     struct hashbuf *htp;
  1295.     struct databuf *gdp;    /* glue databuf */
  1296.     struct namebuf *gnp;    /* glue namebuf */
  1297.     struct namebuf *tnp;    /* top namebuf */
  1298.     struct databuf *tdp;    /* top databuf */
  1299.     struct namebuf **npp, **nppend;
  1300.     u_char msg[PACKETSZ];
  1301.     u_char *cp;
  1302.     char *fname;
  1303.     char dname[MAXDNAME];
  1304.     HEADER *hp = (HEADER *) msg;
  1305.     int fndns;
  1306.  
  1307.     if (np == top)
  1308.         dprintf(1, (ddt, "doaxfr()\n"));
  1309.     fndns = 0;
  1310.     hp->id = 0;
  1311.     hp->opcode = QUERY;
  1312.     hp->aa = hp->tc = hp->ra = hp->pr = hp->rd = 0;
  1313.     hp->qr = 1;
  1314.     hp->rcode = NOERROR;
  1315.     hp->qdcount = 0;
  1316.     hp->ancount = htons(1);
  1317.     hp->nscount = 0;
  1318.     hp->arcount = 0;
  1319.     cp = (u_char *) (msg + HFIXEDSZ);
  1320.     getname(np, dname, sizeof(dname));
  1321.  
  1322.     /* first do the NS records (del@harris) */
  1323.     for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
  1324. #ifdef GEN_AXFR
  1325.         if (dp->d_class != class && class != C_ANY)
  1326.         continue;
  1327. #endif
  1328. #ifdef        NCACHE
  1329.         if (dp->d_rcode)
  1330.         continue;
  1331. #endif
  1332.         if (dp->d_type == T_NS) {
  1333.         fndns = 1;
  1334.         n = make_rr(dname, dp, cp, sizeof(msg)-HFIXEDSZ, 0);
  1335.         if (n < 0)
  1336.             continue;
  1337.         fwritemsg(rfp, msg, n + HFIXEDSZ);
  1338. #ifdef NO_GLUE
  1339.         if ((np != top) || (top->n_dname[0] == '\0')) {
  1340. #endif /*NO_GLUE*/
  1341.             /*  Glue the sub domains together by sending 
  1342.              *  the address records for the sub domain
  1343.              *  name servers along if necessary.
  1344.              *  Glue is necessary if the server is in any zone
  1345.              *  delegated from the current (top) zone.  Such
  1346.              *  a delegated zone might or might not be that
  1347.              *  referred to by the NS record now being handled.
  1348.              */
  1349.              htp = hashtab;
  1350.             cp = (u_char *) (msg + HFIXEDSZ);
  1351.              gnp = nlookup((char *)dp->d_data, &htp, &fname, 0);
  1352.              if (gnp == NULL || fname != (char *)dp->d_data)
  1353.              continue;
  1354. #ifdef NO_GLUE
  1355.             for (tnp = gnp; tnp != NULL; tnp = tnp->n_parent)
  1356.             if ( tnp == top )
  1357.                 break;
  1358.             if ( (tnp == NULL) && (top->n_dname[0] != '\0') )
  1359.             continue;  /* name server is not below top domain */
  1360.             for (tnp = gnp; tnp != top; tnp = tnp->n_parent) {
  1361.             for (tdp = tnp->n_data;
  1362.                  tdp != NULL;
  1363.                  tdp = tdp->d_next) {
  1364. #ifdef GEN_AXFR
  1365.                 if (tdp->d_class != class && class != C_ANY)
  1366.                 continue;
  1367. #endif
  1368.                 if (tdp->d_type == T_NS)
  1369.                 break;
  1370.             }
  1371.             if (tdp != NULL)
  1372.                 break; /* found a zone cut */
  1373.             }
  1374.             if (tnp == top)
  1375.             continue;  /* name server is not in a delegated zone */
  1376.             /* now we know glue records are needed.  send them. */
  1377. #endif /*NO_GLUE*/
  1378.              for (gdp=gnp->n_data; gdp != NULL; gdp=gdp->d_next) {
  1379. #ifdef GEN_AXFR
  1380.             if (gdp->d_class != class && class != C_ANY)
  1381.                 continue;
  1382. #endif
  1383.              if (gdp->d_type != T_A || stale(gdp))
  1384.                  continue;
  1385. #ifdef NCACHE
  1386.             if (gdp->d_rcode)
  1387.                 continue;
  1388. #endif
  1389.              n = make_rr(fname, gdp, cp, sizeof(msg)-HFIXEDSZ, 0);
  1390.             if (n < 0)
  1391.                 continue;
  1392.              fwritemsg(rfp, msg, n + HFIXEDSZ);
  1393.              }
  1394. #ifdef NO_GLUE
  1395.         }
  1396. #endif /*NO_GLUE*/
  1397.         }
  1398.     }
  1399.     /* no need to send anything else if a delegation appeared */
  1400.     if ((np != top) && fndns)
  1401.         return;
  1402.  
  1403.     /* do the rest of the data records */
  1404.     for (dp = np->n_data; dp != NULL; dp = dp->d_next) {
  1405. #ifdef GEN_AXFR
  1406.         if (dp->d_class != class && class != C_ANY)
  1407.             continue;
  1408. #endif
  1409.         /*
  1410.          * Skip the top SOA record (marks end of data);
  1411.          * don't send SOA for subdomains, as we're not sending them;
  1412.          * skip the NS records because we did them first.
  1413.          */
  1414.         if (dp->d_type == T_SOA || dp->d_type == T_NS)
  1415.             continue;
  1416.         if (dp->d_zone == 0 || stale(dp))
  1417.             continue;
  1418. #ifdef NCACHE
  1419.         if (dp->d_rcode)
  1420.             continue;
  1421. #endif
  1422.         if ((n = make_rr(dname, dp, cp, sizeof(msg)-HFIXEDSZ, 0)) < 0)
  1423.             continue;
  1424.         fwritemsg(rfp, msg, n + HFIXEDSZ);
  1425.     }
  1426.  
  1427.     /* Finally do non-delegated subdomains.  Delegated subdomains
  1428.      * have already been handled.
  1429.      */
  1430.     /*
  1431.      * We find the subdomains by looking in the hash table for this
  1432.      * domain, but the root domain needs special treatment, because
  1433.      * of the following wart in the database design:
  1434.      *
  1435.      * The top level hash table (pointed to by the global `hashtab'
  1436.      * variable) contains pointers to the namebuf's for the root as
  1437.      * well as for the top-level domains below the root, in contrast
  1438.      * to the usual situation where a hash table contains entries
  1439.      * for domains at the same level.  The n_hash member of the
  1440.      * namebuf for the root domain is NULL instead of pointing to a
  1441.      * hashbuf for the top-level domains.  The n_parent members of
  1442.      * the namebufs for the top-level domains are NULL instead of
  1443.      * pointing to the namebuf for the root.
  1444.      *
  1445.      * We work around the wart as follows:
  1446.      *
  1447.      * If we are not dealing with the root zone then we just set
  1448.      * htp = np->n_hash, pointing to the hash table for the current
  1449.      * domain, and we walk through the hash table as usual,
  1450.      * processing the namebufs for all the subdomains.
  1451.      *
  1452.      * If we are dealing with the root zone, then we set
  1453.      * htp = hashtab, pointing to the global hash table (because
  1454.      * there is no hash table associated with the root domain's
  1455.      * namebuf.  While we walk this hash table, we take care not to
  1456.      * recursively process the entry for the root namebuf.
  1457.      *
  1458.      * (apb@und nov1990)
  1459.      */
  1460.     htp = ((dname[0] == '\0') ? hashtab : np->n_hash);
  1461.     if (htp == NULL) {
  1462.         return; /* no subdomains */
  1463.     }
  1464.     npp = htp->h_tab;
  1465.     nppend = npp + htp->h_size;
  1466.     while (npp < nppend) {
  1467.         for (np = *npp++; np != NULL; np = np->n_next) {
  1468.             if (np->n_dname[0] != '\0') { /* don't redo root domain */
  1469.             doaxfr(np, rfp, top, class);
  1470.             }
  1471.         }
  1472.     }
  1473.     if (np == top)
  1474.         dprintf(1, (ddt, "exit doaxfr()\n"));
  1475. }
  1476.  
  1477. #ifdef ALLOW_UPDATES
  1478. /*
  1479.  * Called by UPDATE{A,D,DA,M,MA} to initiate a dynamic update.  If this is the
  1480.  * primary server for the zone being updated, we update the zone's serial
  1481.  * number and then call doupdate directly. If this is a secondary, we just
  1482.  * forward the update; this way, if the primary update fails (e.g., if the
  1483.  * primary is unavailable), we don't update the secondary; if the primary
  1484.  * update suceeds, ns_resp will get called with the response (when it comes
  1485.  * in), and then update the secondary's copy.
  1486.  */
  1487. static int
  1488. InitDynUpdate(hp, msg, msglen, startcp, from, qsp, dfd)
  1489.     register HEADER *hp;
  1490.     char *msg;
  1491.     int msglen;
  1492.     u_char *startcp;
  1493.     struct sockaddr_in *from;
  1494.     struct qstream *qsp;
  1495.     int dfd;
  1496. {
  1497.     struct databuf *nsp[NSMAX];
  1498.     struct zoneinfo *zp;
  1499.     char dnbuf[MAXDNAME];
  1500.     struct hashbuf *htp = hashtab;    /* lookup relative to root */
  1501.     struct namebuf *np;
  1502.     struct databuf *olddp, *newdp, *dp;
  1503.     struct databuf **nspp;
  1504.     char *fname;
  1505.     register u_char *cp = startcp;
  1506.     u_int16_t class, type;
  1507.     int n, size, zonenum;
  1508.     char ZoneName[MAXDNAME], *znp;
  1509.  
  1510. #ifdef     DATUMREFCNT
  1511.     nsp[0] = NULL;
  1512. #endif
  1513.     if ((n = dn_expand(msg, msg + msglen, cp, dnbuf, sizeof(dnbuf))) < 0) {
  1514.         dprintf(1, (ddt,"FORMERR InitDynUpdate expand name failed\n"));
  1515.         hp->rcode = FORMERR;
  1516.         return (FORMERR);
  1517.     }
  1518.     cp += n;
  1519.     GETSHORT(type, cp);
  1520.     if (type == T_SOA) {    /* T_SOA updates not allowed */
  1521.         hp->rcode = REFUSED;
  1522.         dprintf(1, (ddt, "InitDynUpdate: REFUSED - SOA update\n"));
  1523.         return (REFUSED);
  1524.     }
  1525.     GETSHORT(class, cp);
  1526.     cp += INT32SZ;
  1527.     GETSHORT(size, cp);
  1528. /****XXX - need bounds checking here ****/
  1529.     cp += size;
  1530.  
  1531.     if ((zonenum = findzone(dnbuf, class)) == 0) {  /* zone not found */
  1532.         hp->rcode = NXDOMAIN;
  1533.         return (NXDOMAIN);
  1534.     }
  1535.     zp = &zones[zonenum];
  1536.  
  1537.     /* Disallow updates for which we aren't authoratative.  Note: the
  1538.        following test doesn't work right:  If it's for a non-local zone,
  1539.        we will think it's a primary but be unable to lookup the namebuf,
  1540.        thus returning 'NXDOMAIN' */
  1541.     if (zp->z_type != Z_PRIMARY && zp->z_type != Z_SECONDARY) {
  1542.         hp->rcode = REFUSED;
  1543.         dprintf(1, (ddt,
  1544.          "InitDynUpdate: REFUSED - non-{primary,secondary} update\n"));
  1545.         return (REFUSED);
  1546.     }
  1547.     if (!(zp->z_flags & Z_DYNAMIC)) {
  1548.         hp->rcode = REFUSED;
  1549.         dprintf(1, (ddt,
  1550.          "InitDynUpdate: REFUSED - dynamic flag not set for zone\n"));
  1551.         return (REFUSED);
  1552.     }
  1553.  
  1554.     /*
  1555.      * Lookup the zone namebuf.  Lookup "xyz" not "xyz.", since
  1556.      * otherwise the lookup fails, because '.' may have a nil n_hash
  1557.      * associated with it.
  1558.      */
  1559.     strcpy(ZoneName, zp->z_origin);
  1560.     znp = &ZoneName[strlen(ZoneName) - 1];
  1561.     if (*znp == '.')
  1562.         *znp = NULL;
  1563.     np = nlookup(ZoneName, &htp, &fname, 0);
  1564.     if ((np == NULL) || (fname != ZoneName)) {
  1565.         dprintf(1, (ddt, "InitDynUpdate: lookup failed on zone (%s)\n",
  1566.                 ZoneName));
  1567.             syslog(LOG_ERR, "InitDynUpdate: lookup failed on zone (%s)\n",
  1568.                ZoneName);
  1569.         hp->rcode = NXDOMAIN;
  1570.         return (NXDOMAIN);
  1571.     }
  1572.  
  1573.     /*
  1574.      * If this is the primary copy increment the serial number.  Don't
  1575.      * increment the serial number if this is a secondary; this way, if 2
  1576.      * different secondaries both update the primary, they will both have
  1577.      * lower serial numbers than the primary has, and hence eventually
  1578.      * refresh and get all updates and become consistent.
  1579.      *
  1580.      * Note that the serial number must be incremented in both the zone
  1581.      * data structure and the zone's namebuf.
  1582.      */
  1583.     switch (zp->z_type) {
  1584.     case Z_SECONDARY:        /* forward update to primary */
  1585.         nspp = nsp;
  1586.         dp = np->n_data;
  1587.         while (dp != NULL) {
  1588.             if (match(dp, class, T_NS)) {
  1589.                 if (nspp < &nsp[NSMAX-1]) {
  1590.                     *nspp++ = dp;
  1591. #ifdef    DATUMREFCNT
  1592.                     dp->d_rcnt++;
  1593. #endif
  1594.                 } else
  1595.                     break;
  1596.             }
  1597.             dp = dp->d_next;
  1598.         }
  1599.         *nspp = NULL; /* Delimiter */
  1600.         if (ns_forw(nsp, msg, msglen, from, qsp, dfd, NULL, dnbuf, np)
  1601.             <
  1602.             0) {
  1603.             hp->rcode = SERVFAIL;
  1604. #ifdef    DATUMREFCNT
  1605.             free_nsp(nsp);
  1606. #endif
  1607.             return (SERVFAIL);
  1608.         }
  1609. #ifdef    DATUMREFCNT
  1610.         free_nsp(nsp);
  1611. #endif
  1612.         return (FORWARDED);
  1613.  
  1614.     case Z_PRIMARY:
  1615.         zp->z_serial++;
  1616.         /* Find the SOA record */
  1617.         for (olddp = np->n_data; olddp != NULL; olddp = olddp->d_next)
  1618.             if (match(olddp, class, T_SOA))
  1619.                 break;
  1620.         if (olddp == NULL) {
  1621.             dprintf(1, (ddt,
  1622.              "InitDynUpdate: Couldn't find SOA record for '%s'\n",
  1623.                     ZoneName));
  1624.             syslog(LOG_ERR,
  1625.                "InitDynUpdate: Couldn't find SOA record for '%s'\n"
  1626. ,
  1627.                ZoneName);
  1628.             hp->rcode = NXDOMAIN;
  1629. #ifdef    DATUMREFCNT
  1630.             free_nsp(nsp);
  1631. #endif
  1632.             return (NXDOMAIN);
  1633.         }
  1634.         newdp = savedata(olddp->d_class, olddp->d_type, olddp->d_ttl,
  1635.                  olddp->d_data, olddp->d_size);
  1636.         newdp->d_zone = olddp->d_zone;
  1637.         newdp->d_cred = DB_C_AUTH;    /* XXX - it may not be so */
  1638.         newdp->d_clev = db_getclev(zp->z_origin);
  1639.         cp = (u_char *)newdp->d_data;
  1640.         cp += strlen(cp) + 1; /* skip origin string */
  1641.         cp += strlen(cp) + 1; /* skip in-charge string */
  1642.         putlong((u_int32_t)(zp->z_serial), cp);
  1643.         dprintf(4, (ddt, "after stuffing data into newdp:\n"));
  1644. #ifdef DEBUG
  1645.         if (debug >= 4)
  1646.             printSOAdata(newdp);
  1647. #endif
  1648.  
  1649.         if ((n = db_update(ZoneName, olddp, newdp, DB_DELETE,
  1650.                    hashtab)) != NOERROR) {    /* XXX */
  1651.             dprintf(1, (ddt,
  1652.                     "InitDynUpdate: SOA update failed\n"));
  1653.             hp->rcode = NOCHANGE;
  1654.             free((char*) dp);
  1655. #ifdef    DATUMREFCNT
  1656.             free_nsp(nsp);
  1657. #endif
  1658.             return (NOCHANGE);
  1659.         }
  1660.  
  1661.         /* Now update the RR itself */
  1662.         /* XXX - DB_C_AUTH may be wrong */
  1663.         if (doupdate(msg, msglen, msg + HFIXEDSZ, zonenum,
  1664.                  (struct databuf *)0, DB_NODATA, DB_C_AUTH) < 0) {
  1665.             dprintf(1, (ddt, "InitDynUpdate: doupdate failed\n"));
  1666.             /* doupdate fills in rcode */
  1667. #ifdef    DATUMREFCNT
  1668.             free_nsp(nsp);
  1669. #endif
  1670.             return (hp->rcode);
  1671.         }
  1672.         zp->z_flags |= Z_CHANGED;
  1673. #ifdef    DATUMREFCNT
  1674.             free_nsp(nsp);
  1675. #endif
  1676.         return (NOERROR);
  1677.     }
  1678. }
  1679.  
  1680. #ifdef DEBUG
  1681. /*
  1682.  * Print the contents of the data in databuf pointed to by dp for an SOA record
  1683.  */
  1684. static void
  1685. printSOAdata(dp)
  1686.     struct databuf *dp;
  1687. {
  1688.     register u_char *cp;
  1689.  
  1690.     if (!debug)
  1691.         return;  /* Otherwise fprintf to ddt will bomb */
  1692.     cp = (u_char *)dp->d_data;
  1693.     fprintf(ddt, "printSOAdata(%x): origin(%x)='%s'\n", dp, cp, cp);
  1694.     cp += strlen(cp) + 1; /* skip origin string */
  1695.     fprintf(ddt, "printSOAdata: in-charge(%x)='%s'\n", cp, cp);
  1696.     cp += strlen(cp) + 1; /* skip in-charge string */
  1697.     fprintf(ddt, "printSOAdata: serial(%x)=%d\n", cp, _getlong(cp));
  1698. }
  1699. #endif
  1700. #endif
  1701.  
  1702. static void
  1703. startxfr(qsp, np, soa, soalen, class, dname)
  1704.     struct qstream    *qsp;
  1705.     struct namebuf    *np;
  1706.     u_char        *soa;
  1707.     int        soalen;
  1708.     int        class;
  1709.     const char    *dname;
  1710. {
  1711.     FILE *rfp;
  1712.     int fdstat;
  1713.     pid_t pid;
  1714.  
  1715.     dprintf(5, (ddt, "startxfr()\n"));
  1716.  
  1717.     /*
  1718.      * child does the work while
  1719.      * the parent continues
  1720.      */
  1721.     switch (pid = fork()) {
  1722.     case -1:
  1723.         syslog(LOG_ERR, "startxfr(%s -> [%s]) failing; fork: %m",
  1724.                dname, inet_ntoa(qsp->s_from.sin_addr));
  1725.         return;
  1726.     case 0:
  1727.         /* child */
  1728.         break;
  1729.     default:
  1730.         /* parent */
  1731.         syslog(LOG_DEBUG, "zone transfer of \"%s\" to [%s] (pid %lu)",
  1732.                dname, inet_ntoa(qsp->s_from.sin_addr), pid);
  1733.         return;
  1734.     }
  1735.  
  1736.     /*
  1737.      * Child.
  1738.      *
  1739.      * XXX:    this should be a vfork/exec since on non-copy-on-write
  1740.      *    systems with huge nameserver images, this is very expensive.
  1741.      */
  1742.     close(vs);
  1743.     sqflush(/*allbut*/ qsp);
  1744.     dqflush((time_t)0);
  1745.  
  1746. #ifdef RENICE
  1747.     nice(-40);  nice(20);  nice(0);        /* back to "normal" */
  1748. #endif
  1749.     dprintf(5, (ddt, "startxfr: child pid %lu\n", (u_long)pid));
  1750.  
  1751.     if (!(rfp = fdopen(qsp->s_rfd, "w"))) {
  1752.         syslog(LOG_ERR, "fdopen: %m");
  1753.         _exit(1);
  1754.     }
  1755.     ns_setproctitle("zone XFR to", qsp->s_rfd);
  1756.     if (-1 == (fdstat = fcntl(qsp->s_rfd, F_GETFL, 0))) {
  1757.         syslog(LOG_ERR, "fcntl(F_GETFL): %m");
  1758.         _exit(1);
  1759.     }
  1760.     (void) fcntl(qsp->s_rfd, F_SETFL, fdstat & ~PORT_NONBLOCK);
  1761.     fwritemsg(rfp, soa, soalen);
  1762.     doaxfr(np, rfp, np, class);
  1763.     fwritemsg(rfp, soa, soalen);
  1764.     (void) fflush(rfp);
  1765.     _exit(0);
  1766. }
  1767.  
  1768. free_addinfo() {
  1769.     struct addinfo *ap;
  1770.  
  1771.     for (ap = addinfo; --addcount >= 0; ap++) {
  1772.         free(ap->a_dname);
  1773.     }
  1774.     addcount = 0;
  1775. }
  1776.  
  1777. #ifdef DATUMREFCNT
  1778. free_nsp(nsp)
  1779. struct databuf **nsp;
  1780. {
  1781.     while (*nsp) {
  1782.         if (--((*nsp)->d_rcnt)) {
  1783.             dprintf(3, (ddt, "free_nsp: %s rcnt %d\n",
  1784.             (*nsp)->d_data, (*nsp)->d_rcnt));
  1785.         } else {
  1786.             dprintf(3, (ddt, "free_nsp: %s rcnt %d delayed\n",
  1787.                 (*nsp)->d_data, (*nsp)->d_rcnt));
  1788.             free(*nsp);    /* delayed free */
  1789.         }
  1790.         *nsp++ = NULL;
  1791.     }
  1792. }
  1793. #endif
  1794.