Merge from appliance-head:
[ira/wip.git] / source3 / libsmb / namequery.c
index 290a91f7b5c8080c8b9ecd980c5c204ba85e3901..6bf34c730cc9bb67b3adedd441ad313bedce5fec 100644 (file)
@@ -22,8 +22,6 @@
 
 #include "includes.h"
 
-extern int DEBUGLEVEL;
-
 /* nmbd.c sets this to True. */
 BOOL global_in_nmbd = False;
 
@@ -35,106 +33,235 @@ static int generate_trn_id(void)
        static int trn_id;
 
        if (trn_id == 0) {
-               srandom(getpid());
+               sys_srandom(sys_getpid());
        }
 
-       trn_id = random();
+       trn_id = sys_random();
 
        return trn_id % (unsigned)0x7FFF;
 }
 
 
 /****************************************************************************
- Interpret a node status response.
+ parse a node status response into an array of structures
 ****************************************************************************/
+static struct node_status *parse_node_status(char *p, int *num_names)
+{
+       struct node_status *ret;
+       int i;
+
+       *num_names = CVAL(p,0);
+
+       if (*num_names == 0) return NULL;
+
+       ret = (struct node_status *)malloc(sizeof(struct node_status)* (*num_names));
+       if (!ret) return NULL;
+
+       p++;
+       for (i=0;i< *num_names;i++) {
+               StrnCpy(ret[i].name,p,15);
+               trim_string(ret[i].name,NULL," ");
+               ret[i].type = CVAL(p,15);
+               ret[i].flags = p[16];
+               p += 18;
+       }
+       return ret;
+}
 
-static void _interpret_node_status(char *p, char *master,char *rname)
+
+/****************************************************************************
+do a NBT node status query on an open socket and return an array of
+structures holding the returned names or NULL if the query failed
+**************************************************************************/
+struct node_status *node_status_query(int fd,struct nmb_name *name,
+                                     struct in_addr to_ip, int *num_names)
 {
-  int numnames = CVAL(p,0);
-  DEBUG(1,("received %d names\n",numnames));
-
-  if (rname) *rname = 0;
-  if (master) *master = 0;
-
-  p += 1;
-  while (numnames--) {
-    char qname[17];
-    int type;
-    fstring flags;
-    int i;
-    *flags = 0;
-    StrnCpy(qname,p,15);
-    type = CVAL(p,15);
-    p += 16;
-
-    fstrcat(flags, (p[0] & 0x80) ? "<GROUP> " : "        ");
-    if ((p[0] & 0x60) == 0x00) fstrcat(flags,"B ");
-    if ((p[0] & 0x60) == 0x20) fstrcat(flags,"P ");
-    if ((p[0] & 0x60) == 0x40) fstrcat(flags,"M ");
-    if ((p[0] & 0x60) == 0x60) fstrcat(flags,"H ");
-    if (p[0] & 0x10) fstrcat(flags,"<DEREGISTERING> ");
-    if (p[0] & 0x08) fstrcat(flags,"<CONFLICT> ");
-    if (p[0] & 0x04) fstrcat(flags,"<ACTIVE> ");
-    if (p[0] & 0x02) fstrcat(flags,"<PERMANENT> ");
-
-    if (master && !*master && type == 0x1d) {
-      StrnCpy(master,qname,15);
-      trim_string(master,NULL," ");
-    }
+       BOOL found=False;
+       int retries = 2;
+       int retry_time = 2000;
+       struct timeval tval;
+       struct packet_struct p;
+       struct packet_struct *p2;
+       struct nmb_packet *nmb = &p.packet.nmb;
+       struct node_status *ret;
+
+       ZERO_STRUCT(p);
+
+       nmb->header.name_trn_id = generate_trn_id();
+       nmb->header.opcode = 0;
+       nmb->header.response = False;
+       nmb->header.nm_flags.bcast = False;
+       nmb->header.nm_flags.recursion_available = False;
+       nmb->header.nm_flags.recursion_desired = False;
+       nmb->header.nm_flags.trunc = False;
+       nmb->header.nm_flags.authoritative = False;
+       nmb->header.rcode = 0;
+       nmb->header.qdcount = 1;
+       nmb->header.ancount = 0;
+       nmb->header.nscount = 0;
+       nmb->header.arcount = 0;
+       nmb->question.question_name = *name;
+       nmb->question.question_type = 0x21;
+       nmb->question.question_class = 0x1;
+
+       p.ip = to_ip;
+       p.port = NMB_PORT;
+       p.fd = fd;
+       p.timestamp = time(NULL);
+       p.packet_type = NMB_PACKET;
+       
+       GetTimeOfDay(&tval);
+  
+       if (!send_packet(&p)) 
+               return NULL;
 
-    if (rname && !*rname && type == 0x20 && !(p[0]&0x80)) {
-      StrnCpy(rname,qname,15);
-      trim_string(rname,NULL," ");
-    }
-      
-    for (i = strlen( qname) ; --i >= 0 ; ) {
-      if (!isprint((int)qname[i])) qname[i] = '.';
-    }
-    DEBUG(1,("\t%-15s <%02x> - %s\n",qname,type,flags));
-    p+=2;
-  }
+       retries--;
 
-  DEBUG(1,("num_good_sends=%d num_good_receives=%d\n",
-              IVAL(p,20),IVAL(p,24)));
+       while (1) {
+               struct timeval tval2;
+               GetTimeOfDay(&tval2);
+               if (TvalDiff(&tval,&tval2) > retry_time) {
+                       if (!retries)
+                               break;
+                       if (!found && !send_packet(&p))
+                               return NULL;
+                       GetTimeOfDay(&tval);
+                       retries--;
+               }
+
+               if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {     
+                       struct nmb_packet *nmb2 = &p2->packet.nmb;
+                       debug_nmb_packet(p2);
+                       
+                       if (nmb2->header.opcode != 0 ||
+                           nmb2->header.nm_flags.bcast ||
+                           nmb2->header.rcode ||
+                           !nmb2->header.ancount ||
+                           nmb2->answers->rr_type != 0x21) {
+                               /* XXXX what do we do with this? could be a
+                                  redirect, but we'll discard it for the
+                                  moment */
+                               free_packet(p2);
+                               continue;
+                       }
+
+                       ret = parse_node_status(&nmb2->answers->rdata[0], num_names);
+                       free_packet(p2);
+                       return ret;
+               }
+       }
+       
+       return NULL;
 }
 
+
 /****************************************************************************
- Internal function handling a netbios name status query on a host.
+find the first type XX name in a node status reply - used for finding
+a servers name given its IP
+return the matched name in *name
 **************************************************************************/
-static BOOL internal_name_status(int fd,char *name,int name_type,BOOL recurse,
-                                struct in_addr to_ip,char *master,
-                                char *rname, BOOL verbose,
-                                void (*fn_interpret_node_status)(char *, char *,char *))
+
+BOOL name_status_find(const char *q_name, int q_type, int type, struct in_addr to_ip, char *name)
 {
-  BOOL found=False;
-  int retries = 2;
-  int retry_time = 5000;
+       struct node_status *status;
+       struct nmb_name nname;
+       int count, i;
+       int sock;
+
+       sock = open_socket_in(SOCK_DGRAM, 0, 3, interpret_addr(lp_socket_address()), True);
+       if (sock == -1)
+               return False;
+
+       /* W2K PDC's seem not to respond to '*'#0. JRA */
+       make_nmb_name(&nname, q_name, q_type);
+       status = node_status_query(sock, &nname, to_ip, &count);
+       close(sock);
+       if (!status)
+               return False;
+
+       for (i=0;i<count;i++) {
+               if (status[i].type == type)
+                       break;
+       }
+       if (i == count)
+               return False;
+
+       pull_ascii(name, status[i].name, 15, 0, STR_TERMINATE);
+
+       SAFE_FREE(status);
+       return True;
+}
+
+/****************************************************************************
+ Do a NetBIOS name registation to try to claim a name ...
+***************************************************************************/
+BOOL name_register(int fd, const char *name, int name_type,
+                  struct in_addr name_ip, int opcode,
+                  BOOL bcast, 
+                  struct in_addr to_ip, int *count)
+{
+  int retries = 3;
   struct timeval tval;
   struct packet_struct p;
   struct packet_struct *p2;
   struct nmb_packet *nmb = &p.packet.nmb;
+  struct in_addr register_ip;
 
-  memset((char *)&p,'\0',sizeof(p));
+  DEBUG(4, ("name_register: %s as %s on %s\n", name, inet_ntoa(name_ip), inet_ntoa(to_ip)));
+
+  register_ip.s_addr = name_ip.s_addr;  /* Fix this ... */
+  
+  memset((char *)&p, '\0', sizeof(p));
+
+  *count = 0;
 
   nmb->header.name_trn_id = generate_trn_id();
-  nmb->header.opcode = 0;
+  nmb->header.opcode = opcode;
   nmb->header.response = False;
   nmb->header.nm_flags.bcast = False;
   nmb->header.nm_flags.recursion_available = False;
-  nmb->header.nm_flags.recursion_desired = False;
+  nmb->header.nm_flags.recursion_desired = True;  /* ? */
   nmb->header.nm_flags.trunc = False;
-  nmb->header.nm_flags.authoritative = False;
-  nmb->header.rcode = 0;
+  nmb->header.nm_flags.authoritative = True;
+
   nmb->header.qdcount = 1;
   nmb->header.ancount = 0;
   nmb->header.nscount = 0;
-  nmb->header.arcount = 0;
+  nmb->header.arcount = 1;
 
-  make_nmb_name(&nmb->question.question_name,name,name_type);
+  make_nmb_name(&nmb->question.question_name, name, name_type);
 
-  nmb->question.question_type = 0x21;
+  nmb->question.question_type = 0x20;
   nmb->question.question_class = 0x1;
 
+  /* Now, create the additional stuff for a registration request */
+
+  if ((nmb->additional = (struct res_rec *)malloc(sizeof(struct res_rec))) == NULL) {
+
+    DEBUG(0, ("name_register: malloc fail for additional record.\n"));
+    return False;
+
+  }
+
+  memset((char *)nmb->additional, '\0', sizeof(struct res_rec));
+
+  nmb->additional->rr_name  = nmb->question.question_name;
+  nmb->additional->rr_type  = RR_TYPE_NB;
+  nmb->additional->rr_class = RR_CLASS_IN;
+
+  /* See RFC 1002, sections 5.1.1.1, 5.1.1.2 and 5.1.1.3 */
+  if (nmb->header.nm_flags.bcast)
+    nmb->additional->ttl = PERMANENT_TTL;
+  else
+    nmb->additional->ttl = lp_max_ttl();
+
+  nmb->additional->rdlength = 6;
+
+  nmb->additional->rdata[0] = NB_MFLAG & 0xFF;
+
+  /* Set the address for the name we are registering. */
+  putip(&nmb->additional->rdata[2], &register_ip);
+
   p.ip = to_ip;
   p.port = NMB_PORT;
   p.fd = fd;
@@ -143,62 +270,17 @@ static BOOL internal_name_status(int fd,char *name,int name_type,BOOL recurse,
 
   GetTimeOfDay(&tval);
 
-  if (!send_packet(&p)) 
-    return(False);
+  if (!send_packet(&p))
+    return False;
 
   retries--;
 
-  while (1) {
-         struct timeval tval2;
-         GetTimeOfDay(&tval2);
-         if (TvalDiff(&tval,&tval2) > retry_time) {
-                 if (!retries)
-                         break;
-                 if (!found && !send_packet(&p))
-                         return False;
-                 GetTimeOfDay(&tval);
-                 retries--;
-         }
-
-         if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {     
-                 struct nmb_packet *nmb2 = &p2->packet.nmb;
-                 debug_nmb_packet(p2);
-
-                 if (nmb2->header.opcode != 0 ||
-                     nmb2->header.nm_flags.bcast ||
-                     nmb2->header.rcode ||
-                     !nmb2->header.ancount ||
-                     nmb2->answers->rr_type != 0x21) {
-                         /* XXXX what do we do with this? could be a
-                            redirect, but we'll discard it for the
-                            moment */
-                         free_packet(p2);
-                         continue;
-                 }
-
-                 if(fn_interpret_node_status)
-                         (*fn_interpret_node_status)(&nmb2->answers->rdata[0],master,rname);
-                 free_packet(p2);
-                 return(True);
-         }
+  if ((p2 = receive_nmb_packet(fd, 10, nmb->header.name_trn_id))) {
+    debug_nmb_packet(p2);
+    SAFE_FREE(p2);  /* No memory leaks ... */
   }
 
-  if(verbose)
-         DEBUG(0,("No status response (this is not unusual)\n"));
-
-  return(False);
-}
-
-/****************************************************************************
- Do a netbios name status query on a host.
- The "master" parameter is a hack used for finding workgroups.
-**************************************************************************/
-BOOL name_status(int fd,char *name,int name_type,BOOL recurse,
-                struct in_addr to_ip,char *master,char *rname)
-{
-       return internal_name_status(fd,name,name_type,recurse,
-                                   to_ip,master,rname,True,
-                                   _interpret_node_status);
+  return True;
 }
 
 /****************************************************************************
@@ -206,7 +288,6 @@ BOOL name_status(int fd,char *name,int name_type,BOOL recurse,
  Returns an array of IP addresses or NULL if none.
  *count will be set to the number of addresses returned.
 ****************************************************************************/
-
 struct in_addr *name_query(int fd,const char *name,int name_type, 
                           BOOL bcast,BOOL recurse,
                           struct in_addr to_ip, int *count)
@@ -255,9 +336,10 @@ struct in_addr *name_query(int fd,const char *name,int name_type,
 
   retries--;
 
-  while (1)
-  {
+       while (1) {
          struct timeval tval2;
+      struct in_addr *tmp_ip_list;
+
          GetTimeOfDay(&tval2);
          if (TvalDiff(&tval,&tval2) > retry_time) {
                  if (!retries)
@@ -271,7 +353,43 @@ struct in_addr *name_query(int fd,const char *name,int name_type,
          if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {     
                  struct nmb_packet *nmb2 = &p2->packet.nmb;
                  debug_nmb_packet(p2);
-                 
+
+                 /* If we get a Negative Name Query Response from a WINS
+                  * server, we should report it and give up.
+                  */
+                 if( 0 == nmb2->header.opcode          /* A query response   */
+                     && !(bcast)                       /* from a WINS server */
+                     && nmb2->header.rcode             /* Error returned     */
+                   ) {
+
+                   if( DEBUGLVL( 3 ) ) {
+                     /* Only executed if DEBUGLEVEL >= 3 */
+                                       dbgtext( "Negative name query response, rcode 0x%02x: ", nmb2->header.rcode );
+                     switch( nmb2->header.rcode ) {
+                       case 0x01:
+                         dbgtext( "Request was invalidly formatted.\n" );
+                         break;
+                       case 0x02:
+                         dbgtext( "Problem with NBNS, cannot process name.\n");
+                         break;
+                       case 0x03:
+                         dbgtext( "The name requested does not exist.\n" );
+                         break;
+                       case 0x04:
+                         dbgtext( "Unsupported request error.\n" );
+                         break;
+                       case 0x05:
+                         dbgtext( "Query refused error.\n" );
+                         break;
+                       default:
+                         dbgtext( "Unrecognized error code.\n" );
+                         break;
+                     }
+                   }
+                   free_packet(p2);
+                   return( NULL );
+                 }
+
                  if (nmb2->header.opcode != 0 ||
                      nmb2->header.nm_flags.bcast ||
                      nmb2->header.rcode ||
@@ -279,22 +397,30 @@ struct in_addr *name_query(int fd,const char *name,int name_type,
                          /* 
                           * XXXX what do we do with this? Could be a
                           * redirect, but we'll discard it for the
-                          * moment.  */
+                                * moment.
+                                */
                          free_packet(p2);
                          continue;
                  }
 
-                 ip_list = (struct in_addr *)Realloc(ip_list, sizeof(ip_list[0]) * 
-                                                     ((*count)+nmb2->answers->rdlength/6));
+          tmp_ip_list = (struct in_addr *)Realloc( ip_list, sizeof( ip_list[0] )
+                                                * ( (*count) + nmb2->answers->rdlength/6 ) );
+          if (!tmp_ip_list) {
+              DEBUG(0,("name_query: Realloc failed.\n"));
+              SAFE_FREE(ip_list);
+          }
+          ip_list = tmp_ip_list;
+
                  if (ip_list) {
-                         DEBUG(2,("Got a positive name query response from %s ( ",
-                                  inet_ntoa(p2->ip)));
+                               DEBUG(2,("Got a positive name query response from %s ( ", inet_ntoa(p2->ip)));
                          for (i=0;i<nmb2->answers->rdlength/6;i++) {
                                  putip((char *)&ip_list[(*count)],&nmb2->answers->rdata[2+i*6]);
-                                 DEBUG(2,("%s ",inet_ntoa(ip_list[(*count)])));
+                                 DEBUGADD(2,("%s ",inet_ntoa(ip_list[(*count)])));
                                  (*count)++;
                          }
-                         DEBUG(2,(")\n"));
+                         DEBUGADD(2,(")\n"));
                  }
 
                  found=True;
@@ -310,6 +436,12 @@ struct in_addr *name_query(int fd,const char *name,int name_type,
          }
   }
 
+  /* Reach here if we've timed out waiting for replies.. */
+       if( !bcast && !found ) {
+    /* Timed out wating for WINS server to respond.  Mark it dead. */
+    wins_srv_died( to_ip );
+    }
+
   return ip_list;
 }
 
@@ -317,26 +449,26 @@ struct in_addr *name_query(int fd,const char *name,int name_type,
  Start parsing the lmhosts file.
 *********************************************************/
 
-FILE *startlmhosts(char *fname)
+XFILE *startlmhosts(char *fname)
 {
-  FILE *fp = sys_fopen(fname,"r");
-  if (!fp) {
-    DEBUG(4,("startlmhosts: Can't open lmhosts file %s. Error was %s\n",
-             fname, strerror(errno)));
-    return NULL;
-  }
-  return fp;
+       XFILE *fp = x_fopen(fname,O_RDONLY, 0);
+       if (!fp) {
+               DEBUG(4,("startlmhosts: Can't open lmhosts file %s. Error was %s\n",
+                        fname, strerror(errno)));
+               return NULL;
+       }
+       return fp;
 }
 
 /********************************************************
  Parse the next line in the lmhosts file.
 *********************************************************/
 
-BOOL getlmhostsent( FILE *fp, pstring name, int *name_type, struct in_addr *ipaddr)
+BOOL getlmhostsent( XFILE *fp, pstring name, int *name_type, struct in_addr *ipaddr)
 {
   pstring line;
 
-  while(!feof(fp) && !ferror(fp)) {
+  while(!x_feof(fp) && !x_ferror(fp)) {
     pstring ip,flags,extra;
     char *ptr;
     int count = 0;
@@ -381,7 +513,7 @@ BOOL getlmhostsent( FILE *fp, pstring name, int *name_type, struct in_addr *ipad
 
     DEBUG(4, ("getlmhostsent: lmhost entry: %s %s %s\n", ip, name, flags));
 
-    if (strchr(flags,'G') || strchr(flags,'S'))
+    if (strchr_m(flags,'G') || strchr_m(flags,'S'))
     {
       DEBUG(0,("getlmhostsent: group flag in lmhosts ignored (obsolete)\n"));
       continue;
@@ -391,7 +523,7 @@ BOOL getlmhostsent( FILE *fp, pstring name, int *name_type, struct in_addr *ipad
 
     /* Extra feature. If the name ends in '#XX', where XX is a hex number,
        then only add that name type. */
-    if((ptr = strchr(name, '#')) != NULL)
+    if((ptr = strchr_m(name, '#')) != NULL)
     {
       char *endptr;
 
@@ -417,17 +549,87 @@ BOOL getlmhostsent( FILE *fp, pstring name, int *name_type, struct in_addr *ipad
  Finish parsing the lmhosts file.
 *********************************************************/
 
-void endlmhosts(FILE *fp)
+void endlmhosts(XFILE *fp)
 {
-  fclose(fp);
+       x_fclose(fp);
+}
+
+BOOL name_register_wins(const char *name, int name_type)
+{
+  int sock, i, return_count;
+  int num_interfaces = iface_count();
+  struct in_addr sendto_ip;
+
+  /* 
+   * Check if we have any interfaces, prevents a segfault later
+   */
+
+  if (num_interfaces <= 0)
+    return False;         /* Should return some indication of the problem */
+
+  /*
+   * Do a broadcast register ...
+   */
+
+  if (0 == wins_srv_count())
+    return False;
+
+  if( DEBUGLVL( 4 ) )
+    {
+    dbgtext( "name_register_wins: Registering my name %s ", name );
+    dbgtext( "with WINS server %s.\n", wins_srv_name() );
+    }
+
+  sock = open_socket_in( SOCK_DGRAM, 0, 3, 
+                        interpret_addr("0.0.0.0"), True );
+
+  if (sock == -1) return False;
+
+  set_socket_options(sock, "SO_BROADCAST");     /* ????! crh */
+
+  sendto_ip = wins_srv_ip();
+
+  if (num_interfaces > 1) {
+
+    for (i = 0; i < num_interfaces; i++) {
+      
+      if (!name_register(sock, name, name_type, *iface_n_ip(i), 
+                        NMB_NAME_MULTIHOMED_REG_OPCODE,
+                        True, sendto_ip, &return_count)) {
+
+       close(sock);
+       return False;
+
+      }
+
+    }
+
+  }
+  else {
+
+    if (!name_register(sock, name, name_type, *iface_n_ip(0),
+                      NMB_NAME_REG_OPCODE,
+                      True, sendto_ip, &return_count)) {
+
+      close(sock);
+      return False;
+
+    }
+
+  }
+
+  close(sock);
+
+  return True;
+
 }
 
 /********************************************************
  Resolve via "bcast" method.
 *********************************************************/
 
-static BOOL resolve_bcast(const char *name, int name_type,
-                               struct in_addr **return_ip_list, int *return_count)
+BOOL name_resolve_bcast(const char *name, int name_type,
+                       struct in_addr **return_ip_list, int *return_count)
 {
        int sock, i;
        int num_interfaces = iface_count();
@@ -439,7 +641,7 @@ static BOOL resolve_bcast(const char *name, int name_type,
         * "bcast" means do a broadcast lookup on all the local interfaces.
         */
 
-       DEBUG(3,("resolve_bcast: Attempting broadcast lookup for name %s<0x%x>\n", name, name_type));
+       DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup for name %s<0x%x>\n", name, name_type));
 
        sock = open_socket_in( SOCK_DGRAM, 0, 3,
                               interpret_addr(lp_socket_address()), True );
@@ -491,21 +693,32 @@ static BOOL resolve_wins(const char *name, int name_type,
 
        DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n", name, name_type));
 
-       if(!*lp_wins_server()) {
-               DEBUG(3,("resolve_wins: WINS server resolution selected and no WINS server present.\n"));
+       if (lp_wins_support()) {
+               /*
+                * We're providing WINS support. Call ourselves so
+                * long as we're not nmbd.
+                */
+               extern struct in_addr loopback_ip;
+               wins_ip = loopback_ip;
+               wins_ismyip = True;
+       } else if( wins_srv_count() < 1 ) {
+               DEBUG(3,("resolve_wins: WINS server resolution selected and no WINS servers listed.\n"));
                return False;
+       } else {
+               wins_ip     = wins_srv_ip();
+               wins_ismyip = ismyip(wins_ip);
        }
 
-       wins_ip = *interpret_addr2(lp_wins_server());
-       wins_ismyip = ismyip(wins_ip);
-
+       DEBUG(3, ("resolve_wins: WINS server == <%s>\n", inet_ntoa(wins_ip)) );
        if((wins_ismyip && !global_in_nmbd) || !wins_ismyip) {
-               sock = open_socket_in( SOCK_DGRAM, 0, 3,
-                                                       interpret_addr(lp_socket_address()), True );
-             
+               sock = open_socket_in(  SOCK_DGRAM, 0, 3,
+                                       interpret_addr(lp_socket_address()),
+                                       True );
                if (sock != -1) {
-                       *return_iplist = name_query(sock, name, name_type, False, 
-                                                               True, wins_ip, return_count);
+                       *return_iplist = name_query( sock,      name,
+                                                    name_type, False, 
+                                                    True,      wins_ip,
+                                                    return_count);
                        if(*return_iplist != NULL) {
                                close(sock);
                                return True;
@@ -528,7 +741,7 @@ static BOOL resolve_lmhosts(const char *name, int name_type,
         * "lmhosts" means parse the local lmhosts file.
         */
        
-       FILE *fp;
+       XFILE *fp;
        pstring lmhost_name;
        int name_type2;
        struct in_addr return_ip;
@@ -538,7 +751,7 @@ static BOOL resolve_lmhosts(const char *name, int name_type,
 
        DEBUG(3,("resolve_lmhosts: Attempting lmhosts lookup for name %s<0x%x>\n", name, name_type));
 
-       fp = startlmhosts( LMHOSTSFILE );
+       fp = startlmhosts(dyn_LMHOSTSFILE);
        if(fp) {
                while (getlmhostsent(fp, lmhost_name, &name_type2, &return_ip)) {
                        if (strequal(name, lmhost_name) && 
@@ -578,7 +791,7 @@ static BOOL resolve_hosts(const char *name,
 
        DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x20>\n", name));
        
-       if (((hp = Get_Hostbyname(name)) != NULL) && (hp->h_addr != NULL)) {
+       if (((hp = sys_gethostbyname(name)) != NULL) && (hp->h_addr != NULL)) {
                struct in_addr return_ip;
                putip((char *)&return_ip,(char *)hp->h_addr);
                *return_iplist = (struct in_addr *)malloc(sizeof(struct in_addr));
@@ -609,9 +822,15 @@ static BOOL internal_resolve_name(const char *name, int name_type,
   BOOL allones = (strcmp(name,"255.255.255.255") == 0);
   BOOL allzeros = (strcmp(name,"0.0.0.0") == 0);
   BOOL is_address = is_ipaddress(name);
+  BOOL result = False;
+  struct in_addr *nodupes_iplist;
+  int i;
+
   *return_iplist = NULL;
   *return_count = 0;
 
+  DEBUG(10, ("internal_resolve_name: looking up %s#%x\n", name, name_type));
+
   if (allzeros || allones || is_address) {
        *return_iplist = (struct in_addr *)malloc(sizeof(struct in_addr));
        if(*return_iplist == NULL) {
@@ -636,32 +855,91 @@ static BOOL internal_resolve_name(const char *name, int name_type,
   while (next_token(&ptr, tok, LIST_SEP, sizeof(tok))) {
          if((strequal(tok, "host") || strequal(tok, "hosts"))) {
                  if (name_type == 0x20 && resolve_hosts(name, return_iplist, return_count)) {
-                         return True;
+                   result = True;
+                   goto done;
                  }
          } else if(strequal( tok, "lmhosts")) {
                  if (resolve_lmhosts(name, name_type, return_iplist, return_count)) {
-                         return True;
+                   result = True;
+                   goto done;
                  }
          } else if(strequal( tok, "wins")) {
                  /* don't resolve 1D via WINS */
                  if (name_type != 0x1D &&
                      resolve_wins(name, name_type, return_iplist, return_count)) {
-                         return True;
+                   result = True;
+                   goto done;
                  }
          } else if(strequal( tok, "bcast")) {
-                 if (resolve_bcast(name, name_type, return_iplist, return_count)) {
-                         return True;
+                 if (name_resolve_bcast(name, name_type, return_iplist, return_count)) {
+                   result = True;
+                   goto done;
                  }
          } else {
                  DEBUG(0,("resolve_name: unknown name switch type %s\n", tok));
          }
   }
 
-  if((*return_iplist) != NULL) {
-    free((char *)(*return_iplist));
-    *return_iplist = NULL;
-  }
+  /* All of the resolve_* functions above have returned false. */
+
+  SAFE_FREE(*return_iplist);
+  *return_count = 0;
+
   return False;
+
+ done:
+
+  /* Remove duplicate entries.  Some queries, notably #1c (domain
+     controllers) return the PDC in iplist[0] and then all domain
+     controllers including the PDC in iplist[1..n].  Iterating over
+     the iplist when the PDC is down will cause two sets of timeouts. */
+
+  if ((nodupes_iplist = (struct in_addr *)
+       malloc(sizeof(struct in_addr) * (*return_count)))) {
+         int nodupes_count = 0;
+
+         /* Iterate over return_iplist looking for duplicates */
+
+         for (i = 0; i < *return_count; i++) {
+                 BOOL is_dupe = False;
+                 int j;
+
+                 for (j = i + 1; j < *return_count; j++) {
+                         if (ip_equal((*return_iplist)[i], 
+                                      (*return_iplist)[j])) {
+                                 is_dupe = True;
+                                 break;
+                         }
+                 }
+
+                 if (!is_dupe) {
+
+                         /* This one not a duplicate */
+
+                         nodupes_iplist[nodupes_count] = (*return_iplist)[i];
+                         nodupes_count++;
+                 }
+         }
+         
+         /* Switcheroo with original list */
+         
+         free(*return_iplist);
+
+         *return_iplist = nodupes_iplist;
+         *return_count = nodupes_count;
+  }
+
+  /* Display some debugging info */
+
+  DEBUG(10, ("internal_resolve_name: returning %d addresses: ", 
+            *return_count));
+
+  for (i = 0; i < *return_count; i++)
+         DEBUGADD(10, ("%s ", inet_ntoa((*return_iplist)[i])));
+
+  DEBUG(10, ("\n"));
+
+  return result;
 }
 
 /********************************************************
@@ -678,14 +956,59 @@ BOOL resolve_name(const char *name, struct in_addr *return_ip, int name_type)
 
        if(internal_resolve_name(name, name_type, &ip_list, &count)) {
                *return_ip = ip_list[0];
-               free((char *)ip_list);
+               SAFE_FREE(ip_list);
                return True;
        }
-       if(ip_list != NULL)
-               free((char *)ip_list);
+       SAFE_FREE(ip_list);
        return False;
 }
 
+
+/********************************************************
+ resolve a name of format \\server_name or \\ipaddress
+ into a name.  also, cut the \\ from the front for us.
+*********************************************************/
+
+BOOL resolve_srv_name(const char* srv_name, fstring dest_host,
+                                struct in_addr *ip)
+{
+        BOOL ret;
+        const char *sv_name = srv_name;
+
+        DEBUG(10,("resolve_srv_name: %s\n", srv_name));
+
+        if (srv_name == NULL || strequal("\\\\.", srv_name))
+        {
+                extern pstring global_myname;
+                fstrcpy(dest_host, global_myname);
+                ip = interpret_addr2("127.0.0.1");
+                return True;
+        }
+
+        if (strnequal("\\\\", srv_name, 2))
+        {
+                sv_name = &srv_name[2];
+        }
+
+        fstrcpy(dest_host, sv_name);
+        /* treat the '*' name specially - it is a magic name for the PDC */
+        if (strcmp(dest_host,"*") == 0) {
+                extern pstring global_myname;
+                ret = resolve_name(lp_workgroup(), ip, 0x1B);
+                lookup_dc_name(global_myname, lp_workgroup(), ip, dest_host);
+        } else {
+                ret = resolve_name(dest_host, ip, 0x20);
+        }
+        
+        if (is_ipaddress(dest_host))
+        {
+                fstrcpy(dest_host, "*SMBSERVER");
+        }
+        
+        return ret;
+}
+
+
 /********************************************************
  Find the IP address of the master browser or DMB for a workgroup.
 *********************************************************/
@@ -697,26 +1020,52 @@ BOOL find_master_ip(char *group, struct in_addr *master_ip)
 
        if (internal_resolve_name(group, 0x1D, &ip_list, &count)) {
                *master_ip = ip_list[0];
-               free((char *)ip_list);
+               SAFE_FREE(ip_list);
                return True;
        }
        if(internal_resolve_name(group, 0x1B, &ip_list, &count)) {
                *master_ip = ip_list[0];
-               free((char *)ip_list);
+               SAFE_FREE(ip_list);
                return True;
        }
 
-       if(ip_list != NULL)
-               free((char *)ip_list);
+       SAFE_FREE(ip_list);
        return False;
 }
 
-
 /********************************************************
- Lookup a PDC name given a Domain name and IP address.
+ Lookup a DC name given a Domain name and IP address.
 *********************************************************/
-BOOL lookup_pdc_name(const char *srcname, const char *domain, struct in_addr *pdc_ip, char *ret_name)
+
+BOOL lookup_dc_name(const char *srcname, const char *domain, 
+                   struct in_addr *dc_ip, char *ret_name)
 {
+#if !defined(I_HATE_WINDOWS_REPLY_CODE)
+       
+       fstring dc_name;
+       BOOL ret;
+       
+       /*
+        * Due to the fact win WinNT *sucks* we must do a node status
+        * query here... JRA.
+        */
+       
+       *dc_name = '\0';
+       
+       ret = name_status_find(domain, 0x1c, 0x20, *dc_ip, dc_name);
+
+       if(ret && *dc_name) {
+               fstrcpy(ret_name, dc_name);
+               return True;
+       }
+       
+       return False;
+
+#else /* defined(I_HATE_WINDOWS_REPLY_CODE) */
+
+JRA - This code is broken with BDC rollover - we need to do a full
+NT GETDC call, UNICODE, NT domain SID and uncle tom cobbley and all...
+
        int retries = 3;
        int retry_time = 2000;
        struct timeval tval;
@@ -727,7 +1076,7 @@ BOOL lookup_pdc_name(const char *srcname, const char *domain, struct in_addr *pd
        int len;
        struct sockaddr_in sock_name;
        int sock_len = sizeof(sock_name);
-       const char *mailslot = "\\MAILSLOT\\NET\\NETLOGON";
+       const char *mailslot = NET_LOGON_MAILSLOT;
        char *mailslot_name;
        char buffer[1024];
        char *bufp;
@@ -755,11 +1104,12 @@ BOOL lookup_pdc_name(const char *srcname, const char *domain, struct in_addr *pd
        bufp += 2;
        fstrcpy(bufp,srcname);
        bufp += (strlen(bufp) + 1);
-       slprintf(bufp, sizeof(fstring), "\\MAILSLOT\\NET\\GETDC%d", dgm_id);
+       slprintf(bufp, sizeof(fstring)-1, "\\MAILSLOT\\NET\\GETDC%d", dgm_id);
        mailslot_name = bufp;
        bufp += (strlen(bufp) + 1);
-       bufp = align2(bufp, buffer);
-       bufp += dos_PutUniCode(bufp, srcname, sizeof(buffer) - (bufp - buffer) - 1, True);
+       bufp = ALIGN2(bufp, buffer);
+       bufp += push_ucs2(NULL, bufp, srcname, sizeof(buffer) - (bufp - buffer), STR_TERMINATE);        
+       
        SIVAL(bufp,0,1);
        SSVAL(bufp,4,0xFFFF); 
        SSVAL(bufp,6,0xFFFF); 
@@ -780,7 +1130,7 @@ BOOL lookup_pdc_name(const char *srcname, const char *domain, struct in_addr *pd
        dgram->header.packet_offset = 0;
        
        make_nmb_name(&dgram->source_name,srcname,0);
-       make_nmb_name(&dgram->dest_name,domain,0x1B);
+       make_nmb_name(&dgram->dest_name,domain,0x1C);
        
        ptr = &dgram->data[0];
        
@@ -887,13 +1237,65 @@ BOOL lookup_pdc_name(const char *srcname, const char *domain, struct in_addr *pd
        
        close(sock);
        return False;
+#endif /* defined(I_HATE_WINDOWS_REPLY_CODE) */
 }
 
 
 /********************************************************
  Get the IP address list of the PDC/BDC's of a Domain.
 *********************************************************/
-BOOL get_dc_list(char *group, struct in_addr **ip_list, int *count)
+
+BOOL get_dc_list(BOOL pdc_only, const char *group, struct in_addr **ip_list, int *count)
+{
+       int name_type = pdc_only ? 0x1B : 0x1C;
+
+       /*
+        * If it's our domain then
+        * use the 'password server' parameter.
+        */
+
+       if (strequal(group, lp_workgroup())) {
+               char *p;
+               char *pserver = lp_passwordserver();
+               fstring name;
+               int num_adresses = 0;
+               struct in_addr *return_iplist = NULL;
+
+               if (! *pserver)
+                       return internal_resolve_name(group, name_type, ip_list, count);
+
+               p = pserver;
+               while (next_token(&p,name,LIST_SEP,sizeof(name))) {
+                       if (strequal(name, "*"))
+                               return internal_resolve_name(group, name_type, ip_list, count);
+                       num_adresses++;
+               }
+               if (num_adresses == 0)
+                       return internal_resolve_name(group, name_type, ip_list, count);
+
+               return_iplist = (struct in_addr *)malloc(num_adresses * sizeof(struct in_addr));
+               if(return_iplist == NULL) {
+                       DEBUG(3,("get_dc_list: malloc fail !\n"));
+                       return False;
+               }
+               p = pserver;
+               *count = 0;
+               while (next_token(&p,name,LIST_SEP,sizeof(name))) {
+                       struct in_addr name_ip;
+                       if (resolve_name( name, &name_ip, 0x20) == False)
+                               continue;
+                       return_iplist[(*count)++] = name_ip;
+               }
+               *ip_list = return_iplist;
+               return (*count != 0);
+       } else
+               return internal_resolve_name(group, name_type, ip_list, count);
+}
+
+/********************************************************
+  Get the IP address list of the Local Master Browsers
+ ********************************************************/ 
+BOOL get_lmb_list(struct in_addr **ip_list, int *count)
 {
-       return internal_resolve_name(group, 0x1C, ip_list, count);
+    return internal_resolve_name( MSBROWSE, 0x1, ip_list, count);
 }