home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / msvp98b1.lzh / MSNDNS.C < prev    next >
Text File  |  1993-05-14  |  16KB  |  580 lines

  1. /* File MSNDNS.C
  2.  * Domain name server requester
  3.  *
  4.  * Copyright (C) 1991, University of Waterloo.
  5.  * Copyright (C) 1985, 1992, Trustees of Columbia University in the 
  6.  * City of New York.  Permission is granted to any individual or institution
  7.  * to use this software as long as it is not sold for profit.  This copyright
  8.  * notice must be retained.  This software may not be included in commercial
  9.  * products without written permission of Columbia University.
  10.  *
  11.  * Original version created by Erick Engelke of the University of
  12.  *  Waterloo, Waterloo, Ontario, Canada.
  13.  * Adapted and modified for MS-DOS Kermit by Joe R. Doupnik, 
  14.  *  Utah State University, jrd@cc.usu.edu, jrd@usu.Bitnet.
  15.  *
  16.  * Last edit
  17.  * 4 March 1992
  18.  *
  19.  * Originally based on NCSA Telnet
  20.  *
  21.  */
  22.  
  23. #include "msntcp.h"
  24. #include "msnlib.h"
  25.  
  26. byte *def_domain;
  27.  
  28. longword def_nameservers[ MAX_NAMESERVERS ];
  29. int last_nameserver;
  30. extern int icmp_unreach;        /* catch ICMP unreachable msgs */
  31.  
  32. static udp_Socket *dom_sock;
  33.  
  34. #define DOMSIZE 512         /* maximum domain message size to mess with */
  35.  
  36. /*
  37.  *  Header for the DOMAIN queries
  38.  *  ALL OF THESE ARE BYTE SWAPPED QUANTITIES!
  39.  */
  40. struct dhead {
  41.     word    ident,        /* unique identifier */
  42.         flags,
  43.         qdcount,    /* question section, # of entries */
  44.         ancount,    /* answers, how many */
  45.         nscount,    /* count of name server Respsonse Records */
  46.         arcount;    /* number of "additional" records */
  47. };
  48.  
  49. /*
  50.  *  flag masks for the flags field of the DOMAIN header
  51.  */
  52. #define DQR        0x8000    /* query = 0, response = 1 */
  53. #define DOPCODE        0x7100    /* opcode, see below */
  54. #define DAA        0x0400    /* Authoritative answer */
  55. #define DTC        0x0200    /* Truncation, response was cut off at 512 */
  56. #define DRD        0x0100    /* Recursion desired */
  57. #define DRA        0x0080    /* Recursion available */
  58. #define DRCODE        0x000F    /* response code, see below */
  59.  
  60. /* opcode possible values: */
  61. #define DOPQUERY    0    /* a standard query */
  62. #define DOPIQ        1    /* an inverse query */
  63. #define DOPCQM        2    /* a completion query, multiple reply */
  64. #define DOPCQU        3         /* a completion query, single reply */
  65. /* the rest reserved for future */
  66.  
  67. /* legal response codes: */
  68. #define DROK    0        /* okay response */
  69. #define DRFORM    1        /* format error */
  70. #define DRFAIL    2        /* their problem, server failed */
  71. #define DRNAME    3        /* name error, we know name doesn't exist */
  72. #define DRNOPE    4        /* no can do request */
  73. #define DRNOWAY    5        /* name server refusing to do request */
  74.  
  75. #define DTYPEA        1    /* host address resource record (RR) */
  76. #define DTYPEPTR    12    /* a domain name ptr */
  77.  
  78. #define DIN        1    /* ARPA internet class */
  79. #define DWILD        255    /* wildcard for several classifications */
  80.  
  81. /*
  82.  *  a resource record is made up of a compressed domain name followed by
  83.  *  this structure.  All of these ints need to be byteswapped before use.
  84.  */
  85. struct rrpart {
  86.     word       rtype,        /* resource record type = DTYPEA */
  87.         rclass;        /* RR class = DIN */
  88.     longword    ttl;        /* time-to-live, changed to 32 bits */
  89.     word    rdlength;    /* length of next field */
  90.     byte     rdata[DOMSIZE];    /* data field */
  91. };
  92.  
  93. /*
  94.  *  data for domain name lookup
  95.  */
  96. static struct useek {
  97.     struct    dhead h;
  98.     byte    x[DOMSIZE];
  99. } *question;
  100.  
  101. static void
  102. qinit() {
  103.     question->h.flags = htons(DRD);
  104.     question->h.qdcount = htons(1);
  105.     question->h.ancount = 0;
  106.     question->h.nscount = 0;
  107.     question->h.arcount = 0;
  108. }
  109.  
  110. int 
  111. add_server(int *counter, int max, longword *array, longword value)
  112. {
  113.     if (array == NULL) return (0);            /* failure */
  114.     if (value && (*counter < max))
  115.         array[ (*counter)++ ] = value;
  116.     return (1);
  117. }
  118.  
  119. /*********************************************************************/
  120. /*  packdom
  121.  *   pack a regular text string into a packed domain name, suitable
  122.  *   for the name server.
  123.  *
  124.  *   returns length
  125. */
  126. static int
  127. packdom(dst, src) byte *src, *dst; {
  128.     register byte *p, *q;
  129.     byte *savedst;
  130.     int i, dotflag, defflag;
  131.  
  132.     if (dst == NULL || src == NULL) return (0);        /* failure */
  133.     dotflag = defflag = 0;
  134.     p = src;
  135.     savedst = dst;
  136.  
  137.     do {            /* copy whole string */
  138.     *dst = 0;
  139.     q = dst + 1;
  140.     while (*p && (*p != '.'))
  141.         *q++ = *p++;
  142.  
  143.     i = p - src;
  144.     if (i > 0x3f)            /* if string is too long */
  145.         return (-1);
  146.     *dst = i;            /* leading length byte */
  147.     *q = 0;
  148.  
  149.     if (*p) {            /* if a next field */
  150.         dotflag = 1;        /* say dot seen in string */
  151.         src = ++p;
  152.         dst = q;
  153.     }
  154.     else if ((dotflag == 0) && (defflag == 0) && (def_domain != NULL)) {
  155.         p = def_domain;        /* continue packing with default */
  156.         defflag = 1;        /* say using default domain ext */
  157.         src = p;
  158.         dst = q;
  159.     }
  160.     }
  161.     while (*p);
  162.     q++;
  163.     return (q - savedst);        /* length of packed string */
  164. }
  165.  
  166. /*********************************************************************/
  167. /*  unpackdom
  168.  *  Unpack a compressed domain name that we have received from another
  169.  *  host.  Handles pointers to continuation domain names -- buf is used
  170.  *  as the base for the offset of any pointer which is present.
  171.  *  returns the number of bytes at src which should be skipped over.
  172.  *  Includes the NULL terminator in its length count.
  173.  */
  174. static int
  175. unpackdom(dst, src, buf) byte *src, *dst, buf[]; {
  176.     register word i, j;
  177.     int retval;
  178.     byte *savesrc;
  179.  
  180.     if (src == NULL || dst == NULL || buf == NULL)
  181.         return (-1);    /* failure */
  182.     savesrc = src;
  183.     retval = 0;
  184.  
  185.     while (*src) {
  186.     j = *src & 0xff;            /* length byte */
  187.     while ((j & 0xC0) == 0xC0) {         /* while 14-bit pointer */
  188.         if (retval == 0)
  189.         retval = src - savesrc + 2;
  190.         src++;
  191.         src = &buf[(j & 0x3f)*256+(*src & 0xff)]; /* 14-bit pointer deref */
  192.         j = *src & 0xff;            /* new length byte */
  193.     }
  194.  
  195.     src++;                    /* assumes 6-bit count */
  196.     for (i = 0; i < (j & 0x3f); i++)
  197.         *dst++ = *src++;            /* copy counted string */
  198.     *dst++ = '.';                /* append a dot */
  199.     }
  200.     *(--dst) = 0;            /* add terminator */
  201.     src++;                /* account for terminator on src */
  202.  
  203.     if (retval == 0)
  204.     retval = src - savesrc;
  205.     return (retval);
  206. }
  207.  
  208. /*********************************************************************/
  209. /*  sendom
  210.  *   put together a domain lookup packet and send it
  211.  *   uses UDP port 53
  212.  *    num is used as identifier
  213.  */
  214. static word
  215. sendom(s, towho, num) byte *s; longword towho; word num; {
  216.     word i,ulen;
  217.     register byte *psave;
  218.     register byte *p;
  219.  
  220.     psave = question->x;
  221.     i = packdom(question->x, s);    /* i = length of packed string */
  222.  
  223.     p = &(question->x[i]);
  224.     *p++ = 0;                /* high byte of qtype */
  225.     *p++ = DTYPEA;        /* number is < 256, so we know high byte=0 */
  226.     *p++ = 0;                /* high byte of qclass */
  227.     *p++ = DIN;                /* qtype is < 256 */
  228.  
  229.     question->h.ident = htons(num);
  230.     ulen = sizeof(struct dhead) + (p - psave);
  231.     if (udp_open(dom_sock, 997, towho, 53, NULL) == 0)        /* failure */
  232.         return (0);                         /* fail*/
  233.  
  234.     if (sock_write(dom_sock, (byte *)question, ulen) != ulen)
  235.         return (0);                        /* fail */
  236.  
  237.     return (ulen);
  238. }
  239.  
  240. static int 
  241. countpaths(pathstring) byte *pathstring; {
  242.     register int count = 0;
  243.     register byte *p;
  244.  
  245.     for (p = pathstring; (*p != 0) || (*(p+1) != 0); p++)
  246.     if (*p == '.')
  247.         count++;
  248.  
  249.     return (++count);
  250. }
  251.  
  252. static byte *
  253. getpath(pathstring, whichone)
  254. byte *pathstring;        /* the path list to search */
  255. int   whichone;            /* which path to get, starts at 1 */
  256. {
  257.     register byte *retval;
  258.  
  259.     if (pathstring == NULL) return (NULL);    /* failure */
  260.  
  261.     if (whichone > countpaths(pathstring))
  262.         return (NULL);
  263.     whichone--;
  264.     for (retval = pathstring; whichone > 0; retval++)
  265.         if (*retval == '.')
  266.             whichone--;
  267.     return (retval);
  268. }
  269.  
  270. /*********************************************************************/
  271. /*  ddextract
  272.  *   Extract the ip number from a response message.
  273.  *   Returns the appropriate status code and if the ip number is available,
  274.  *   and copies it into mip.
  275.  */
  276. static longword 
  277. ddextract(qp, mip)
  278. struct useek *qp;
  279. longword *mip;
  280. {
  281.     register int i;
  282.     int j, nans, rcode;
  283.     struct rrpart *rrp;
  284.     register byte *p;
  285.     byte space[260];
  286.  
  287.     if (qp == NULL || mip == NULL) return (0);    /* failure */
  288.     memset(space, 0, sizeof(space));
  289.     nans = ntohs(qp->h.ancount);        /* number of answers */
  290.     rcode = DRCODE & ntohs(qp->h.flags);    /* return code for message*/
  291.  
  292.     if (rcode != 0)
  293.         return (rcode);
  294.  
  295.     if (nans == 0 || (ntohs(qp->h.flags) & DQR) == 0)
  296.         return (-1);         /* if no answer or no response flag */
  297.  
  298.     p = qp->x;                /* where question starts */
  299.     if ((i = unpackdom(space, p, qp)) == -1) /* unpack question name */
  300.         return (-1);            /* failure to unpack */
  301.  
  302.     /*  spec defines name then  QTYPE + QCLASS = 4 bytes */
  303.     p += i + 4;
  304. /*
  305.  *  At this point, there may be several answers.  We will take the first
  306.  *  one which has an IP number.  There may be other types of answers that
  307.  *  we want to support later.
  308.  */
  309.     while (nans-- > 0) {            /* look at each answer */
  310.         if ((i = unpackdom(space,p,qp)) == -1) /* answer name to unpack */
  311.             return (-1);            /* failure to unpack */
  312.         p += i;                /* account for string */
  313.         rrp = (struct rrpart *)p;        /* resource record here */
  314.         if (*p == 0 && *(p+1) == DTYPEA &&     /* correct type and class */
  315.         *(p+2) == 0 && *(p+3) == DIN) {
  316.         bcopy(&rrp->rdata, mip, 4);    /* save binary IP # */
  317.         return (0);            /* successful return */
  318.         }
  319.         p += 10 + ntohs(rrp->rdlength);    /* length of rest of RR */
  320.     }
  321.     return (-1);                /* generic failed to parse */
  322. }
  323.  
  324. /*********************************************************************/
  325. /*  getdomain
  326.  *   Look at the results to see if our DOMAIN request is ready.
  327.  *   It may be a timeout, which requires another query.
  328.  */
  329.  
  330. static longword 
  331. udpdom() {
  332.     register int i,uret;
  333.     longword desired;
  334.  
  335.     uret = sock_fastread(dom_sock, (byte *)question, sizeof(struct useek));
  336.                         /* this does not happen */
  337.     if (uret < 0)
  338.         return (-1);
  339.  
  340.     if (uret == 0) return (0);        /* fastread failed to read */
  341.  
  342.     /* check if the necessary information was in the UDP response */
  343.     i = ddextract(question, &desired);
  344.     switch (i)
  345.         {
  346.             case 0: return (ntohl(desired)); /* we found the IP number */
  347.             case 3:                /* name does not exist */
  348.             case -1:        /* strange ret code from ddextract */
  349.             default:return (0);        /* dunno */
  350.         }
  351. }
  352.  
  353.  
  354. /**************************************************************************/
  355. /*  Sdomain
  356.  *   DOMAIN based name lookup
  357.  *   query a domain name server to get an IP number
  358.  *    Returns the machine number of the machine record for future reference.
  359.  *   Events generated will have this number tagged with them.
  360.  *   Returns various negative numbers on error conditions.
  361.  *
  362.  *   if adddom is nonzero, add default domain
  363.  */
  364. static longword
  365. Sdomain(mname, adddom, nameserver, timedout)
  366.     byte *mname;
  367.     int adddom;
  368.     longword nameserver;
  369.     int *timedout;            /* Set to 1 on timeout */
  370. {
  371. #define NAMBUFSIZ 512
  372.     byte namebuff[NAMBUFSIZ];
  373.     int namlen;
  374.     register int i;
  375.     register byte *p;
  376.     byte *nextdomain(byte *, int);
  377.     longword response;
  378.  
  379.     response = 0;
  380.     *timedout = 1;            /* presume a timeout */
  381.  
  382.     if (nameserver == 0L)
  383.         {            /* no nameserver, give up now */
  384.         outs("\r\n No nameserver defined!");
  385.         return (0);
  386.         }
  387.  
  388.     while (*mname == ' ' || *mname == '\t') mname++;
  389.                         /* kill leading spaces */
  390.     if (*mname == '\0')        /* no host name, fail */
  391.         return (0L);
  392.  
  393.     qinit();            /* initialize some flag fields */
  394.  
  395.     namlen = strlen(mname);        /* Get length of name */
  396.     if (namlen >= NAMBUFSIZ || namlen == 0)    /* Check it before copying */
  397.         return (0L);
  398.  
  399.     strcpy(namebuff, mname);            /* OK to copy */
  400.     if(namebuff[strlen(namebuff) - 1] == '.')
  401.         namebuff[strlen(namebuff) - 1] = '\0';
  402.  
  403.     if (adddom > 0 && adddom <= countpaths(def_domain))
  404.         {                 /* there is a search list */
  405.         p = getpath(def_domain, adddom); /* get end of def_domain */
  406.         if (p != NULL)            /* if got something */
  407.             {
  408.             if (strlen(p) > (NAMBUFSIZ - namlen - 1))
  409.                 return (0L);        /* if too big */
  410.             if (*p != '.')            /* one dot please */
  411.                 strcat(namebuff, ".");
  412.             strcat(namebuff, p);    /* new name to try */
  413.             }
  414.             }
  415.  
  416.     outs("\r\n  trying name "); outs(namebuff); /* hand holder */
  417.  
  418.     /*
  419.      * This is not terribly good, but it attempts to use a binary
  420.      * exponentially increasing delays.
  421.      */
  422.     for (i = 2; i < 17; i *= 2)
  423.         {
  424.         if (sendom(namebuff, nameserver, 0xf001) == 0)    /* try UDP */
  425.             goto sock_err;            /* sendom() failed */
  426.         ip_timer_init(dom_sock, i);
  427.         do
  428.             {
  429.             if (icmp_unreach != 0)        /* unreachable? */
  430.                  goto sock_err;
  431.             if (tcp_tick(dom_sock) == 0)     /* read packets */
  432.                 goto sock_err;        /* socket is closed */
  433.             if (ip_timer_expired(dom_sock))
  434.                 break;            /* timeout */
  435.             if (sock_dataready(dom_sock))    /* have response */
  436.                 *timedout = 0;        /* say no timeout */
  437.             } while (*timedout);
  438.  
  439.         if (*timedout == 0) break;    /* got an answer */
  440.         }
  441.  
  442.     if (*timedout == 0)            /* if answer, else fall thru*/
  443.         {
  444.         response = udpdom();        /* process the received data*/
  445.         sock_close(dom_sock);
  446.         return (response);
  447.         }
  448.  
  449. sock_err:
  450.     outs("\r\n  Cannot reach name server ");
  451.     ntoa(namebuff, nameserver);    /* nameserver IP to dotted decimal */
  452.     outs(namebuff);            /* display nameserver's IP */
  453.     *timedout = 1;            /* say timeout */
  454.     sock_close(dom_sock);        /* do for safety's sake */
  455.     return (0);
  456. }
  457.  
  458. /*
  459.  * nextdomain - given domain and count = 0,1,2,..., return next larger
  460.  *        domain or NULL when no more are available
  461.  */
  462. static byte *
  463. nextdomain(byte *domain, int count)
  464. {
  465.     register byte *p;
  466.     register int i;
  467.  
  468.     if ((p = domain) == NULL) return (NULL);    /* failure */
  469.     if (count < 0) return (NULL);
  470.  
  471.     for (i = 0; i < count; i++)
  472.         {
  473.         p = strchr(p, '.');
  474.         if (p == NULL) return (NULL);
  475.         p++;
  476.         }
  477.     return (p);
  478. }
  479.  
  480. static longword
  481. resolve2(byte *name)
  482. {            /* detailed worker for resolve() */
  483.     longword ip_address;
  484.     register int count;
  485.     register int i;
  486.     byte timeout;
  487.     struct useek qp;            /* temp buffer */
  488.     udp_Socket ds;                  /* working socket (big!) */
  489.  
  490.     question = &qp;
  491.     dom_sock = &ds;
  492.  
  493.     for (i = 0; i < last_nameserver; i++)    /* for each nameserver */
  494.         {
  495.         icmp_unreach = 0;    /* clear ICMP unreachable msg */
  496.         count = 0;        /* number domain extensions to add */
  497.         do            /* try name then name.extensions */
  498.             {
  499.             if (ip_address = Sdomain(name, count,
  500.                 def_nameservers[i], &timeout))
  501.                     return (ip_address);
  502.             if (timeout != 0)        /* no nameserver */
  503.                 break;             /* exit do-while */
  504.             } 
  505.         while (nextdomain(def_domain, count++) != NULL); /* are ext */
  506.         }
  507.     return (0L);            /* return failure, IP of 0L */
  508. }
  509.  
  510.  
  511. /*
  512.  * resolve()
  513.  *     convert domain name -> address resolution.
  514.  *     returns 0 if name is unresolvable right now
  515.  */
  516.  
  517. longword 
  518. resolve(name) byte *name; {
  519.     if (name == NULL) return (0L);
  520.  
  521.     rip(name);            /* terminate on cr and lf's */
  522.     if (isaddr(name) != 0)
  523.         return (aton(name));    /* IP numerical address */
  524.     return (resolve2(name));    /* call upon the worker */
  525. }
  526.  
  527. /*
  528.  * aton()
  529.  *    - converts [a.b.c.d] or a.b.c.d to 32 bit long
  530.  *    - returns 0 on error (safer than -1)
  531.  */
  532.  
  533. longword 
  534. aton(text)
  535. byte *text;
  536. {
  537.     register int i;
  538.     longword ip, j;
  539.  
  540.     ip = 0;
  541.     if (text == NULL) return (0L);        /* failure */
  542.  
  543.     if (*text == '[')
  544.         text++;
  545.     for (i = 24; i >= 0; i -= 8)
  546.         {
  547.         j = atoi(text) & 0xff;
  548.         ip |= (j << i);
  549.         while (*text != '\0' && *text != '.') text++;
  550.         if (*text == '\0')
  551.             break;
  552.         text++;
  553.         }
  554.     return (ip);
  555. }
  556.  
  557. /*
  558.  * isaddr
  559.  *    - returns nonzero if text is simply ip address
  560.  * such as 123.456.789.012 or [same] or 123 456 789 012 or [same]
  561.  */
  562. int 
  563. isaddr(text)
  564. byte *text;
  565. {
  566.     register byte ch;
  567.  
  568.     if (text == NULL) return (0);        /* failure */
  569.     while (ch = *text++)
  570.         {
  571.         if (('0' <= ch) && (ch <= '9'))
  572.             continue;    /* in digits */
  573.         if ((ch == '.') || (ch == ' ') || (ch == '[') || (ch == ']'))
  574.                 continue;            /* and in punct */
  575.         return (0);                /* failure */
  576.         }
  577.     return (1);
  578. }
  579.  
  580.