Merge branch 'v3-2-test' of ssh://git.samba.org/data/git/samba into v3-2-simo
[ira/wip.git] / source3 / libsmb / namequery.c
1 /*
2    Unix SMB/CIFS implementation.
3    name query routines
4    Copyright (C) Andrew Tridgell 1994-1998
5    Copyright (C) Jeremy Allison 2007.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22
23 /* nmbd.c sets this to True. */
24 bool global_in_nmbd = False;
25
26 /****************************
27  * SERVER AFFINITY ROUTINES *
28  ****************************/
29
30  /* Server affinity is the concept of preferring the last domain
31     controller with whom you had a successful conversation */
32
33 /****************************************************************************
34 ****************************************************************************/
35 #define SAFKEY_FMT      "SAF/DOMAIN/%s"
36 #define SAF_TTL         900
37
38 static char *saf_key(const char *domain)
39 {
40         char *keystr;
41
42         asprintf_strupper_m(&keystr, SAFKEY_FMT, domain);
43
44         return keystr;
45 }
46
47 /****************************************************************************
48 ****************************************************************************/
49
50 bool saf_store( const char *domain, const char *servername )
51 {
52         char *key;
53         time_t expire;
54         bool ret = False;
55
56         if ( !domain || !servername ) {
57                 DEBUG(2,("saf_store: "
58                         "Refusing to store empty domain or servername!\n"));
59                 return False;
60         }
61
62         if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
63                 DEBUG(0,("saf_store: "
64                         "refusing to store 0 length domain or servername!\n"));
65                 return False;
66         }
67
68         if ( !gencache_init() )
69                 return False;
70
71         key = saf_key( domain );
72         expire = time( NULL ) + SAF_TTL;
73
74         DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
75                 domain, servername, (unsigned int)expire ));
76
77         ret = gencache_set( key, servername, expire );
78
79         SAFE_FREE( key );
80
81         return ret;
82 }
83
84 bool saf_delete( const char *domain )
85 {
86         char *key;
87         bool ret = False;
88
89         if ( !domain ) {
90                 DEBUG(2,("saf_delete: Refusing to delete empty domain\n"));
91                 return False;
92         }
93
94         if ( !gencache_init() )
95                 return False;
96
97         key = saf_key(domain);
98         ret = gencache_del(key);
99
100         if (ret) {
101                 DEBUG(10,("saf_delete: domain = [%s]\n", domain ));
102         }
103
104         SAFE_FREE( key );
105
106         return ret;
107 }
108
109 /****************************************************************************
110 ****************************************************************************/
111
112 char *saf_fetch( const char *domain )
113 {
114         char *server = NULL;
115         time_t timeout;
116         bool ret = False;
117         char *key = NULL;
118
119         if ( !domain || strlen(domain) == 0) {
120                 DEBUG(2,("saf_fetch: Empty domain name!\n"));
121                 return NULL;
122         }
123
124         if ( !gencache_init() )
125                 return False;
126
127         key = saf_key( domain );
128
129         ret = gencache_get( key, &server, &timeout );
130
131         SAFE_FREE( key );
132
133         if ( !ret ) {
134                 DEBUG(5,("saf_fetch: failed to find server for \"%s\" domain\n",
135                                         domain ));
136         } else {
137                 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
138                         server, domain ));
139         }
140
141         return server;
142 }
143
144 /****************************************************************************
145  Generate a random trn_id.
146 ****************************************************************************/
147
148 static int generate_trn_id(void)
149 {
150         uint16 id;
151
152         generate_random_buffer((uint8 *)&id, sizeof(id));
153
154         return id % (unsigned)0x7FFF;
155 }
156
157 /****************************************************************************
158  Parse a node status response into an array of structures.
159 ****************************************************************************/
160
161 static NODE_STATUS_STRUCT *parse_node_status(char *p,
162                                 int *num_names,
163                                 struct node_status_extra *extra)
164 {
165         NODE_STATUS_STRUCT *ret;
166         int i;
167
168         *num_names = CVAL(p,0);
169
170         if (*num_names == 0)
171                 return NULL;
172
173         ret = SMB_MALLOC_ARRAY(NODE_STATUS_STRUCT,*num_names);
174         if (!ret)
175                 return NULL;
176
177         p++;
178         for (i=0;i< *num_names;i++) {
179                 StrnCpy(ret[i].name,p,15);
180                 trim_char(ret[i].name,'\0',' ');
181                 ret[i].type = CVAL(p,15);
182                 ret[i].flags = p[16];
183                 p += 18;
184                 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
185                            ret[i].type, ret[i].flags));
186         }
187         /*
188          * Also, pick up the MAC address ...
189          */
190         if (extra) {
191                 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
192         }
193         return ret;
194 }
195
196
197 /****************************************************************************
198  Do a NBT node status query on an open socket and return an array of
199  structures holding the returned names or NULL if the query failed.
200 **************************************************************************/
201
202 NODE_STATUS_STRUCT *node_status_query(int fd,
203                                         struct nmb_name *name,
204                                         const struct sockaddr_storage *to_ss,
205                                         int *num_names,
206                                         struct node_status_extra *extra)
207 {
208         bool found=False;
209         int retries = 2;
210         int retry_time = 2000;
211         struct timeval tval;
212         struct packet_struct p;
213         struct packet_struct *p2;
214         struct nmb_packet *nmb = &p.packet.nmb;
215         NODE_STATUS_STRUCT *ret;
216
217         ZERO_STRUCT(p);
218
219         if (to_ss->ss_family != AF_INET) {
220                 /* Can't do node status to IPv6 */
221                 return NULL;
222         }
223         nmb->header.name_trn_id = generate_trn_id();
224         nmb->header.opcode = 0;
225         nmb->header.response = false;
226         nmb->header.nm_flags.bcast = false;
227         nmb->header.nm_flags.recursion_available = false;
228         nmb->header.nm_flags.recursion_desired = false;
229         nmb->header.nm_flags.trunc = false;
230         nmb->header.nm_flags.authoritative = false;
231         nmb->header.rcode = 0;
232         nmb->header.qdcount = 1;
233         nmb->header.ancount = 0;
234         nmb->header.nscount = 0;
235         nmb->header.arcount = 0;
236         nmb->question.question_name = *name;
237         nmb->question.question_type = 0x21;
238         nmb->question.question_class = 0x1;
239
240         p.ip = ((const struct sockaddr_in *)to_ss)->sin_addr;
241         p.port = NMB_PORT;
242         p.fd = fd;
243         p.timestamp = time(NULL);
244         p.packet_type = NMB_PACKET;
245
246         GetTimeOfDay(&tval);
247
248         if (!send_packet(&p))
249                 return NULL;
250
251         retries--;
252
253         while (1) {
254                 struct timeval tval2;
255                 GetTimeOfDay(&tval2);
256                 if (TvalDiff(&tval,&tval2) > retry_time) {
257                         if (!retries)
258                                 break;
259                         if (!found && !send_packet(&p))
260                                 return NULL;
261                         GetTimeOfDay(&tval);
262                         retries--;
263                 }
264
265                 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
266                         struct nmb_packet *nmb2 = &p2->packet.nmb;
267                         debug_nmb_packet(p2);
268
269                         if (nmb2->header.opcode != 0 ||
270                             nmb2->header.nm_flags.bcast ||
271                             nmb2->header.rcode ||
272                             !nmb2->header.ancount ||
273                             nmb2->answers->rr_type != 0x21) {
274                                 /* XXXX what do we do with this? could be a
275                                    redirect, but we'll discard it for the
276                                    moment */
277                                 free_packet(p2);
278                                 continue;
279                         }
280
281                         ret = parse_node_status(&nmb2->answers->rdata[0],
282                                         num_names, extra);
283                         free_packet(p2);
284                         return ret;
285                 }
286         }
287
288         return NULL;
289 }
290
291 /****************************************************************************
292  Find the first type XX name in a node status reply - used for finding
293  a servers name given its IP. Return the matched name in *name.
294 **************************************************************************/
295
296 bool name_status_find(const char *q_name,
297                         int q_type,
298                         int type,
299                         const struct sockaddr_storage *to_ss,
300                         fstring name)
301 {
302         char addr[INET6_ADDRSTRLEN];
303         struct sockaddr_storage ss;
304         NODE_STATUS_STRUCT *status = NULL;
305         struct nmb_name nname;
306         int count, i;
307         int sock;
308         bool result = false;
309
310         if (lp_disable_netbios()) {
311                 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n",
312                                         q_name, q_type));
313                 return False;
314         }
315
316         print_sockaddr(addr, sizeof(addr), to_ss);
317
318         DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
319                    q_type, addr));
320
321         /* Check the cache first. */
322
323         if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
324                 return True;
325         }
326
327         if (to_ss->ss_family != AF_INET) {
328                 /* Can't do node status to IPv6 */
329                 return false;
330         }
331
332         if (!interpret_string_addr(&ss, lp_socket_address(),
333                                 AI_NUMERICHOST|AI_PASSIVE)) {
334                 zero_addr(&ss);
335         }
336
337         sock = open_socket_in(SOCK_DGRAM, 0, 3, &ss, True);
338         if (sock == -1)
339                 goto done;
340
341         /* W2K PDC's seem not to respond to '*'#0. JRA */
342         make_nmb_name(&nname, q_name, q_type);
343         status = node_status_query(sock, &nname, to_ss, &count, NULL);
344         close(sock);
345         if (!status)
346                 goto done;
347
348         for (i=0;i<count;i++) {
349                 if (status[i].type == type)
350                         break;
351         }
352         if (i == count)
353                 goto done;
354
355         pull_ascii_nstring(name, sizeof(fstring), status[i].name);
356
357         /* Store the result in the cache. */
358         /* but don't store an entry for 0x1c names here.  Here we have
359            a single host and DOMAIN<0x1c> names should be a list of hosts */
360
361         if ( q_type != 0x1c ) {
362                 namecache_status_store(q_name, q_type, type, to_ss, name);
363         }
364
365         result = true;
366
367  done:
368         SAFE_FREE(status);
369
370         DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
371
372         if (result)
373                 DEBUGADD(10, (", name %s ip address is %s", name, addr));
374
375         DEBUG(10, ("\n"));
376
377         return result;
378 }
379
380 /*
381   comparison function used by sort_addr_list
382 */
383
384 static int addr_compare(const struct sockaddr_storage *ss1,
385                 const struct sockaddr_storage *ss2)
386 {
387         int max_bits1=0, max_bits2=0;
388         int num_interfaces = iface_count();
389         int i;
390
391         /* Sort IPv6 addresses first. */
392         if (ss1->ss_family != ss2->ss_family) {
393                 if (ss2->ss_family == AF_INET) {
394                         return -1;
395                 } else {
396                         return 1;
397                 }
398         }
399
400         /* Here we know both addresses are of the same
401          * family. */
402
403         for (i=0;i<num_interfaces;i++) {
404                 const struct sockaddr_storage *pss = iface_n_bcast(i);
405                 unsigned char *p_ss1 = NULL;
406                 unsigned char *p_ss2 = NULL;
407                 unsigned char *p_if = NULL;
408                 size_t len = 0;
409                 int bits1, bits2;
410
411                 if (pss->ss_family != ss1->ss_family) {
412                         /* Ignore interfaces of the wrong type. */
413                         continue;
414                 }
415                 if (pss->ss_family == AF_INET) {
416                         p_if = (unsigned char *)
417                                 &((const struct sockaddr_in *)pss)->sin_addr;
418                         p_ss1 = (unsigned char *)
419                                 &((const struct sockaddr_in *)ss1)->sin_addr;
420                         p_ss2 = (unsigned char *)
421                                 &((const struct sockaddr_in *)ss2)->sin_addr;
422                         len = 4;
423                 }
424 #if defined(HAVE_IPV6)
425                 if (pss->ss_family == AF_INET6) {
426                         p_if = (unsigned char *)
427                                 &((const struct sockaddr_in6 *)pss)->sin6_addr;
428                         p_ss1 = (unsigned char *)
429                                 &((const struct sockaddr_in6 *)ss1)->sin6_addr;
430                         p_ss2 = (unsigned char *)
431                                 &((const struct sockaddr_in6 *)ss2)->sin6_addr;
432                         len = 16;
433                 }
434 #endif
435                 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
436                         continue;
437                 }
438                 bits1 = matching_len_bits(p_ss1, p_if, len);
439                 bits2 = matching_len_bits(p_ss2, p_if, len);
440                 max_bits1 = MAX(bits1, max_bits1);
441                 max_bits2 = MAX(bits2, max_bits2);
442         }
443
444         /* Bias towards directly reachable IPs */
445         if (iface_local(ss1)) {
446                 if (ss1->ss_family == AF_INET) {
447                         max_bits1 += 32;
448                 } else {
449                         max_bits1 += 128;
450                 }
451         }
452         if (iface_local(ss2)) {
453                 if (ss2->ss_family == AF_INET) {
454                         max_bits2 += 32;
455                 } else {
456                         max_bits2 += 128;
457                 }
458         }
459         return max_bits2 - max_bits1;
460 }
461
462 /*******************************************************************
463  compare 2 ldap IPs by nearness to our interfaces - used in qsort
464 *******************************************************************/
465
466 int ip_service_compare(struct ip_service *ss1, struct ip_service *ss2)
467 {
468         int result;
469
470         if ((result = addr_compare(&ss1->ss, &ss2->ss)) != 0) {
471                 return result;
472         }
473
474         if (ss1->port > ss2->port) {
475                 return 1;
476         }
477
478         if (ss1->port < ss2->port) {
479                 return -1;
480         }
481
482         return 0;
483 }
484
485 /*
486   sort an IP list so that names that are close to one of our interfaces
487   are at the top. This prevents the problem where a WINS server returns an IP
488   that is not reachable from our subnet as the first match
489 */
490
491 static void sort_addr_list(struct sockaddr_storage *sslist, int count)
492 {
493         if (count <= 1) {
494                 return;
495         }
496
497         qsort(sslist, count, sizeof(struct sockaddr_storage),
498                         QSORT_CAST addr_compare);
499 }
500
501 static void sort_service_list(struct ip_service *servlist, int count)
502 {
503         if (count <= 1) {
504                 return;
505         }
506
507         qsort(servlist, count, sizeof(struct ip_service),
508                         QSORT_CAST ip_service_compare);
509 }
510
511 /**********************************************************************
512  Remove any duplicate address/port pairs in the list
513  *********************************************************************/
514
515 static int remove_duplicate_addrs2(struct ip_service *iplist, int count )
516 {
517         int i, j;
518
519         DEBUG(10,("remove_duplicate_addrs2: "
520                         "looking for duplicate address/port pairs\n"));
521
522         /* one loop to remove duplicates */
523         for ( i=0; i<count; i++ ) {
524                 if ( is_zero_addr(&iplist[i].ss)) {
525                         continue;
526                 }
527
528                 for ( j=i+1; j<count; j++ ) {
529                         if (addr_equal(&iplist[i].ss, &iplist[j].ss) &&
530                                         iplist[i].port == iplist[j].port) {
531                                 zero_addr(&iplist[j].ss);
532                         }
533                 }
534         }
535
536         /* one loop to clean up any holes we left */
537         /* first ip should never be a zero_ip() */
538         for (i = 0; i<count; ) {
539                 if (is_zero_addr(&iplist[i].ss) ) {
540                         if (i != count-1) {
541                                 memmove(&iplist[i], &iplist[i+1],
542                                         (count - i - 1)*sizeof(iplist[i]));
543                         }
544                         count--;
545                         continue;
546                 }
547                 i++;
548         }
549
550         return count;
551 }
552
553 /****************************************************************************
554  Do a netbios name query to find someones IP.
555  Returns an array of IP addresses or NULL if none.
556  *count will be set to the number of addresses returned.
557  *timed_out is set if we failed by timing out
558 ****************************************************************************/
559
560 struct sockaddr_storage *name_query(int fd,
561                         const char *name,
562                         int name_type,
563                         bool bcast,
564                         bool recurse,
565                         const struct sockaddr_storage *to_ss,
566                         int *count,
567                         int *flags,
568                         bool *timed_out)
569 {
570         bool found=false;
571         int i, retries = 3;
572         int retry_time = bcast?250:2000;
573         struct timeval tval;
574         struct packet_struct p;
575         struct packet_struct *p2;
576         struct nmb_packet *nmb = &p.packet.nmb;
577         struct sockaddr_storage *ss_list = NULL;
578
579         if (lp_disable_netbios()) {
580                 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
581                                         name, name_type));
582                 return NULL;
583         }
584
585         if (to_ss->ss_family != AF_INET) {
586                 return NULL;
587         }
588
589         if (timed_out) {
590                 *timed_out = false;
591         }
592
593         memset((char *)&p,'\0',sizeof(p));
594         (*count) = 0;
595         (*flags) = 0;
596
597         nmb->header.name_trn_id = generate_trn_id();
598         nmb->header.opcode = 0;
599         nmb->header.response = false;
600         nmb->header.nm_flags.bcast = bcast;
601         nmb->header.nm_flags.recursion_available = false;
602         nmb->header.nm_flags.recursion_desired = recurse;
603         nmb->header.nm_flags.trunc = false;
604         nmb->header.nm_flags.authoritative = false;
605         nmb->header.rcode = 0;
606         nmb->header.qdcount = 1;
607         nmb->header.ancount = 0;
608         nmb->header.nscount = 0;
609         nmb->header.arcount = 0;
610
611         make_nmb_name(&nmb->question.question_name,name,name_type);
612
613         nmb->question.question_type = 0x20;
614         nmb->question.question_class = 0x1;
615
616         p.ip = ((struct sockaddr_in *)to_ss)->sin_addr;
617         p.port = NMB_PORT;
618         p.fd = fd;
619         p.timestamp = time(NULL);
620         p.packet_type = NMB_PACKET;
621
622         GetTimeOfDay(&tval);
623
624         if (!send_packet(&p))
625                 return NULL;
626
627         retries--;
628
629         while (1) {
630                 struct timeval tval2;
631
632                 GetTimeOfDay(&tval2);
633                 if (TvalDiff(&tval,&tval2) > retry_time) {
634                         if (!retries)
635                                 break;
636                         if (!found && !send_packet(&p))
637                                 return NULL;
638                         GetTimeOfDay(&tval);
639                         retries--;
640                 }
641
642                 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
643                         struct nmb_packet *nmb2 = &p2->packet.nmb;
644                         debug_nmb_packet(p2);
645
646                         /* If we get a Negative Name Query Response from a WINS
647                          * server, we should report it and give up.
648                          */
649                         if( 0 == nmb2->header.opcode    /* A query response   */
650                             && !(bcast)                 /* from a WINS server */
651                             && nmb2->header.rcode       /* Error returned     */
652                                 ) {
653
654                                 if( DEBUGLVL( 3 ) ) {
655                                         /* Only executed if DEBUGLEVEL >= 3 */
656                                         dbgtext( "Negative name query "
657                                                 "response, rcode 0x%02x: ",
658                                                 nmb2->header.rcode );
659                                         switch( nmb2->header.rcode ) {
660                                         case 0x01:
661                                                 dbgtext( "Request "
662                                                 "was invalidly formatted.\n" );
663                                                 break;
664                                         case 0x02:
665                                                 dbgtext( "Problem with NBNS, "
666                                                 "cannot process name.\n");
667                                                 break;
668                                         case 0x03:
669                                                 dbgtext( "The name requested "
670                                                 "does not exist.\n" );
671                                                 break;
672                                         case 0x04:
673                                                 dbgtext( "Unsupported request "
674                                                 "error.\n" );
675                                                 break;
676                                         case 0x05:
677                                                 dbgtext( "Query refused "
678                                                 "error.\n" );
679                                                 break;
680                                         default:
681                                                 dbgtext( "Unrecognized error "
682                                                 "code.\n" );
683                                                 break;
684                                         }
685                                 }
686                                 free_packet(p2);
687                                 return( NULL );
688                         }
689
690                         if (nmb2->header.opcode != 0 ||
691                             nmb2->header.nm_flags.bcast ||
692                             nmb2->header.rcode ||
693                             !nmb2->header.ancount) {
694                                 /*
695                                  * XXXX what do we do with this? Could be a
696                                  * redirect, but we'll discard it for the
697                                  * moment.
698                                  */
699                                 free_packet(p2);
700                                 continue;
701                         }
702
703                         ss_list = SMB_REALLOC_ARRAY(ss_list,
704                                                 struct sockaddr_storage,
705                                                 (*count) +
706                                                 nmb2->answers->rdlength/6);
707
708                         if (!ss_list) {
709                                 DEBUG(0,("name_query: Realloc failed.\n"));
710                                 free_packet(p2);
711                                 return NULL;
712                         }
713
714                         DEBUG(2,("Got a positive name query response "
715                                         "from %s ( ",
716                                         inet_ntoa(p2->ip)));
717
718                         for (i=0;i<nmb2->answers->rdlength/6;i++) {
719                                 struct in_addr ip;
720                                 putip((char *)&ip,&nmb2->answers->rdata[2+i*6]);
721                                 in_addr_to_sockaddr_storage(&ss_list[(*count)],
722                                                 ip);
723                                 DEBUGADD(2,("%s ",inet_ntoa(ip)));
724                                 (*count)++;
725                         }
726                         DEBUGADD(2,(")\n"));
727
728                         found=true;
729                         retries=0;
730                         /* We add the flags back ... */
731                         if (nmb2->header.response)
732                                 (*flags) |= NM_FLAGS_RS;
733                         if (nmb2->header.nm_flags.authoritative)
734                                 (*flags) |= NM_FLAGS_AA;
735                         if (nmb2->header.nm_flags.trunc)
736                                 (*flags) |= NM_FLAGS_TC;
737                         if (nmb2->header.nm_flags.recursion_desired)
738                                 (*flags) |= NM_FLAGS_RD;
739                         if (nmb2->header.nm_flags.recursion_available)
740                                 (*flags) |= NM_FLAGS_RA;
741                         if (nmb2->header.nm_flags.bcast)
742                                 (*flags) |= NM_FLAGS_B;
743                         free_packet(p2);
744                         /*
745                          * If we're doing a unicast lookup we only
746                          * expect one reply. Don't wait the full 2
747                          * seconds if we got one. JRA.
748                          */
749                         if(!bcast && found)
750                                 break;
751                 }
752         }
753
754         /* only set timed_out if we didn't fund what we where looking for*/
755
756         if ( !found && timed_out ) {
757                 *timed_out = true;
758         }
759
760         /* sort the ip list so we choose close servers first if possible */
761         sort_addr_list(ss_list, *count);
762
763         return ss_list;
764 }
765
766 /********************************************************
767  Start parsing the lmhosts file.
768 *********************************************************/
769
770 XFILE *startlmhosts(const char *fname)
771 {
772         XFILE *fp = x_fopen(fname,O_RDONLY, 0);
773         if (!fp) {
774                 DEBUG(4,("startlmhosts: Can't open lmhosts file %s. "
775                         "Error was %s\n",
776                         fname, strerror(errno)));
777                 return NULL;
778         }
779         return fp;
780 }
781
782 /********************************************************
783  Parse the next line in the lmhosts file.
784 *********************************************************/
785
786 bool getlmhostsent(TALLOC_CTX *ctx, XFILE *fp, char **pp_name, int *name_type,
787                 struct sockaddr_storage *pss)
788 {
789         char line[1024];
790
791         *pp_name = NULL;
792
793         while(!x_feof(fp) && !x_ferror(fp)) {
794                 char *ip = NULL;
795                 char *flags = NULL;
796                 char *extra = NULL;
797                 char *name = NULL;
798                 const char *ptr;
799                 char *ptr1 = NULL;
800                 int count = 0;
801
802                 *name_type = -1;
803
804                 if (!fgets_slash(line,sizeof(line),fp)) {
805                         continue;
806                 }
807
808                 if (*line == '#') {
809                         continue;
810                 }
811
812                 ptr = line;
813
814                 if (next_token_talloc(ctx, &ptr, &ip, NULL))
815                         ++count;
816                 if (next_token_talloc(ctx, &ptr, &name, NULL))
817                         ++count;
818                 if (next_token_talloc(ctx, &ptr, &flags, NULL))
819                         ++count;
820                 if (next_token_talloc(ctx, &ptr, &extra, NULL))
821                         ++count;
822
823                 if (count <= 0)
824                         continue;
825
826                 if (count > 0 && count < 2) {
827                         DEBUG(0,("getlmhostsent: Ill formed hosts line [%s]\n",
828                                                 line));
829                         continue;
830                 }
831
832                 if (count >= 4) {
833                         DEBUG(0,("getlmhostsent: too many columns "
834                                 "in lmhosts file (obsolete syntax)\n"));
835                         continue;
836                 }
837
838                 if (!flags) {
839                         flags = talloc_strdup(ctx, "");
840                         if (!flags) {
841                                 continue;
842                         }
843                 }
844
845                 DEBUG(4, ("getlmhostsent: lmhost entry: %s %s %s\n",
846                                         ip, name, flags));
847
848                 if (strchr_m(flags,'G') || strchr_m(flags,'S')) {
849                         DEBUG(0,("getlmhostsent: group flag "
850                                 "in lmhosts ignored (obsolete)\n"));
851                         continue;
852                 }
853
854                 if (!interpret_string_addr(pss, ip, AI_NUMERICHOST)) {
855                         DEBUG(0,("getlmhostsent: invalid address "
856                                 "%s.\n", ip));
857                 }
858
859                 /* Extra feature. If the name ends in '#XX',
860                  * where XX is a hex number, then only add that name type. */
861                 if((ptr1 = strchr_m(name, '#')) != NULL) {
862                         char *endptr;
863                         ptr1++;
864
865                         *name_type = (int)strtol(ptr1, &endptr, 16);
866                         if(!*ptr1 || (endptr == ptr1)) {
867                                 DEBUG(0,("getlmhostsent: invalid name "
868                                         "%s containing '#'.\n", name));
869                                 continue;
870                         }
871
872                         *(--ptr1) = '\0'; /* Truncate at the '#' */
873                 }
874
875                 *pp_name = talloc_strdup(ctx, name);
876                 if (!*pp_name) {
877                         return false;
878                 }
879                 return true;
880         }
881
882         return false;
883 }
884
885 /********************************************************
886  Finish parsing the lmhosts file.
887 *********************************************************/
888
889 void endlmhosts(XFILE *fp)
890 {
891         x_fclose(fp);
892 }
893
894 /********************************************************
895  convert an array if struct sockaddr_storage to struct ip_service
896  return false on failure.  Port is set to PORT_NONE;
897 *********************************************************/
898
899 static bool convert_ss2service(struct ip_service **return_iplist,
900                 const struct sockaddr_storage *ss_list,
901                 int count)
902 {
903         int i;
904
905         if ( count==0 || !ss_list )
906                 return False;
907
908         /* copy the ip address; port will be PORT_NONE */
909         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) ==
910                         NULL) {
911                 DEBUG(0,("convert_ip2service: malloc failed "
912                         "for %d enetries!\n", count ));
913                 return False;
914         }
915
916         for ( i=0; i<count; i++ ) {
917                 (*return_iplist)[i].ss   = ss_list[i];
918                 (*return_iplist)[i].port = PORT_NONE;
919         }
920
921         return true;
922 }
923
924 /********************************************************
925  Resolve via "bcast" method.
926 *********************************************************/
927
928 NTSTATUS name_resolve_bcast(const char *name,
929                         int name_type,
930                         struct ip_service **return_iplist,
931                         int *return_count)
932 {
933         int sock, i;
934         int num_interfaces = iface_count();
935         struct sockaddr_storage *ss_list;
936         struct sockaddr_storage ss;
937         NTSTATUS status;
938
939         if (lp_disable_netbios()) {
940                 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n",
941                                         name, name_type));
942                 return NT_STATUS_INVALID_PARAMETER;
943         }
944
945         *return_iplist = NULL;
946         *return_count = 0;
947
948         /*
949          * "bcast" means do a broadcast lookup on all the local interfaces.
950          */
951
952         DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup "
953                 "for name %s<0x%x>\n", name, name_type));
954
955         if (!interpret_string_addr(&ss, lp_socket_address(),
956                                 AI_NUMERICHOST|AI_PASSIVE)) {
957                 zero_addr(&ss);
958         }
959
960         sock = open_socket_in( SOCK_DGRAM, 0, 3, &ss, true );
961         if (sock == -1) {
962                 return NT_STATUS_UNSUCCESSFUL;
963         }
964
965         set_socket_options(sock,"SO_BROADCAST");
966         /*
967          * Lookup the name on all the interfaces, return on
968          * the first successful match.
969          */
970         for( i = num_interfaces-1; i >= 0; i--) {
971                 const struct sockaddr_storage *pss = iface_n_bcast(i);
972                 int flags;
973
974                 /* Done this way to fix compiler error on IRIX 5.x */
975                 if (!pss) {
976                         continue;
977                 }
978                 ss_list = name_query(sock, name, name_type, true,
979                                     true, pss, return_count, &flags, NULL);
980                 if (ss_list) {
981                         goto success;
982                 }
983         }
984
985         /* failed - no response */
986
987         close(sock);
988         return NT_STATUS_UNSUCCESSFUL;
989
990 success:
991
992         status = NT_STATUS_OK;
993         if (!convert_ss2service(return_iplist, ss_list, *return_count) )
994                 status = NT_STATUS_INVALID_PARAMETER;
995
996         SAFE_FREE(ss_list);
997         close(sock);
998         return status;
999 }
1000
1001 /********************************************************
1002  Resolve via "wins" method.
1003 *********************************************************/
1004
1005 NTSTATUS resolve_wins(const char *name,
1006                 int name_type,
1007                 struct ip_service **return_iplist,
1008                 int *return_count)
1009 {
1010         int sock, t, i;
1011         char **wins_tags;
1012         struct sockaddr_storage src_ss, *ss_list = NULL;
1013         struct in_addr src_ip;
1014         NTSTATUS status;
1015
1016         if (lp_disable_netbios()) {
1017                 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n",
1018                                         name, name_type));
1019                 return NT_STATUS_INVALID_PARAMETER;
1020         }
1021
1022         *return_iplist = NULL;
1023         *return_count = 0;
1024
1025         DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n",
1026                                 name, name_type));
1027
1028         if (wins_srv_count() < 1) {
1029                 DEBUG(3,("resolve_wins: WINS server resolution selected "
1030                         "and no WINS servers listed.\n"));
1031                 return NT_STATUS_INVALID_PARAMETER;
1032         }
1033
1034         /* we try a lookup on each of the WINS tags in turn */
1035         wins_tags = wins_srv_tags();
1036
1037         if (!wins_tags) {
1038                 /* huh? no tags?? give up in disgust */
1039                 return NT_STATUS_INVALID_PARAMETER;
1040         }
1041
1042         /* the address we will be sending from */
1043         if (!interpret_string_addr(&src_ss, lp_socket_address(),
1044                                 AI_NUMERICHOST|AI_PASSIVE)) {
1045                 zero_addr(&src_ss);
1046         }
1047
1048         if (src_ss.ss_family != AF_INET) {
1049                 char addr[INET6_ADDRSTRLEN];
1050                 print_sockaddr(addr, sizeof(addr), &src_ss);
1051                 DEBUG(3,("resolve_wins: cannot receive WINS replies "
1052                         "on IPv6 address %s\n",
1053                         addr));
1054                 return NT_STATUS_INVALID_PARAMETER;
1055         }
1056
1057         src_ip = ((struct sockaddr_in *)&src_ss)->sin_addr;
1058
1059         /* in the worst case we will try every wins server with every
1060            tag! */
1061         for (t=0; wins_tags && wins_tags[t]; t++) {
1062                 int srv_count = wins_srv_count_tag(wins_tags[t]);
1063                 for (i=0; i<srv_count; i++) {
1064                         struct sockaddr_storage wins_ss;
1065                         struct in_addr wins_ip;
1066                         int flags;
1067                         bool timed_out;
1068
1069                         wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
1070
1071                         if (global_in_nmbd && ismyip_v4(wins_ip)) {
1072                                 /* yikes! we'll loop forever */
1073                                 continue;
1074                         }
1075
1076                         /* skip any that have been unresponsive lately */
1077                         if (wins_srv_is_dead(wins_ip, src_ip)) {
1078                                 continue;
1079                         }
1080
1081                         DEBUG(3,("resolve_wins: using WINS server %s "
1082                                 "and tag '%s'\n",
1083                                 inet_ntoa(wins_ip), wins_tags[t]));
1084
1085                         sock = open_socket_in(SOCK_DGRAM, 0, 3, &src_ss, true);
1086                         if (sock == -1) {
1087                                 continue;
1088                         }
1089
1090                         in_addr_to_sockaddr_storage(&wins_ss, wins_ip);
1091                         ss_list = name_query(sock,
1092                                                 name,
1093                                                 name_type,
1094                                                 false,
1095                                                 true,
1096                                                 &wins_ss,
1097                                                 return_count,
1098                                                 &flags,
1099                                                 &timed_out);
1100
1101                         /* exit loop if we got a list of addresses */
1102
1103                         if (ss_list)
1104                                 goto success;
1105
1106                         close(sock);
1107
1108                         if (timed_out) {
1109                                 /* Timed out wating for WINS server to respond.
1110                                  * Mark it dead. */
1111                                 wins_srv_died(wins_ip, src_ip);
1112                         } else {
1113                                 /* The name definately isn't in this
1114                                    group of WINS servers.
1115                                    goto the next group  */
1116                                 break;
1117                         }
1118                 }
1119         }
1120
1121         wins_srv_tags_free(wins_tags);
1122         return NT_STATUS_NO_LOGON_SERVERS;
1123
1124 success:
1125
1126         status = NT_STATUS_OK;
1127         if (!convert_ss2service(return_iplist, ss_list, *return_count))
1128                 status = NT_STATUS_INVALID_PARAMETER;
1129
1130         SAFE_FREE(ss_list);
1131         wins_srv_tags_free(wins_tags);
1132         close(sock);
1133
1134         return status;
1135 }
1136
1137 /********************************************************
1138  Resolve via "lmhosts" method.
1139 *********************************************************/
1140
1141 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
1142                                 struct ip_service **return_iplist,
1143                                 int *return_count)
1144 {
1145         /*
1146          * "lmhosts" means parse the local lmhosts file.
1147          */
1148
1149         XFILE *fp;
1150         char *lmhost_name = NULL;
1151         int name_type2;
1152         struct sockaddr_storage return_ss;
1153         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1154         TALLOC_CTX *ctx = NULL;
1155
1156         *return_iplist = NULL;
1157         *return_count = 0;
1158
1159         DEBUG(3,("resolve_lmhosts: "
1160                 "Attempting lmhosts lookup for name %s<0x%x>\n",
1161                 name, name_type));
1162
1163         fp = startlmhosts(get_dyn_LMHOSTSFILE());
1164
1165         if ( fp == NULL )
1166                 return NT_STATUS_NO_SUCH_FILE;
1167
1168         ctx = talloc_init("resolve_lmhosts");
1169         if (!ctx) {
1170                 endlmhosts(fp);
1171                 return NT_STATUS_NO_MEMORY;
1172         }
1173
1174         while (getlmhostsent(ctx, fp, &lmhost_name, &name_type2, &return_ss)) {
1175
1176                 if (!strequal(name, lmhost_name)) {
1177                         TALLOC_FREE(lmhost_name);
1178                         continue;
1179                 }
1180
1181                 if ((name_type2 != -1) && (name_type != name_type2)) {
1182                         TALLOC_FREE(lmhost_name);
1183                         continue;
1184                 }
1185
1186                 *return_iplist = SMB_REALLOC_ARRAY((*return_iplist),
1187                                         struct ip_service,
1188                                         (*return_count)+1);
1189
1190                 if ((*return_iplist) == NULL) {
1191                         TALLOC_FREE(ctx);
1192                         endlmhosts(fp);
1193                         DEBUG(3,("resolve_lmhosts: malloc fail !\n"));
1194                         return NT_STATUS_NO_MEMORY;
1195                 }
1196
1197                 (*return_iplist)[*return_count].ss = return_ss;
1198                 (*return_iplist)[*return_count].port = PORT_NONE;
1199                 *return_count += 1;
1200
1201                 /* we found something */
1202                 status = NT_STATUS_OK;
1203
1204                 /* Multiple names only for DC lookup */
1205                 if (name_type != 0x1c)
1206                         break;
1207         }
1208
1209         TALLOC_FREE(ctx);
1210         endlmhosts(fp);
1211         return status;
1212 }
1213
1214
1215 /********************************************************
1216  Resolve via "hosts" method.
1217 *********************************************************/
1218
1219 static NTSTATUS resolve_hosts(const char *name, int name_type,
1220                               struct ip_service **return_iplist,
1221                               int *return_count)
1222 {
1223         /*
1224          * "host" means do a localhost, or dns lookup.
1225          */
1226         struct addrinfo hints;
1227         struct addrinfo *ailist = NULL;
1228         struct addrinfo *res = NULL;
1229         int ret = -1;
1230         int i = 0;
1231
1232         if ( name_type != 0x20 && name_type != 0x0) {
1233                 DEBUG(5, ("resolve_hosts: not appropriate "
1234                         "for name type <0x%x>\n",
1235                         name_type));
1236                 return NT_STATUS_INVALID_PARAMETER;
1237         }
1238
1239         *return_iplist = NULL;
1240         *return_count = 0;
1241
1242         DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
1243                                 name, name_type));
1244
1245         ZERO_STRUCT(hints);
1246         /* By default make sure it supports TCP. */
1247         hints.ai_socktype = SOCK_STREAM;
1248         hints.ai_flags = AI_ADDRCONFIG;
1249
1250 #if !defined(HAVE_IPV6)
1251         /* Unless we have IPv6, we really only want IPv4 addresses back. */
1252         hints.ai_family = AF_INET;
1253 #endif
1254
1255         ret = getaddrinfo(name,
1256                         NULL,
1257                         &hints,
1258                         &ailist);
1259         if (ret) {
1260                 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1261                         name,
1262                         gai_strerror(ret) ));
1263         }
1264
1265         for (res = ailist; res; res = res->ai_next) {
1266                 struct sockaddr_storage ss;
1267
1268                 if (!res->ai_addr || res->ai_addrlen == 0) {
1269                         continue;
1270                 }
1271
1272                 memset(&ss, '\0', sizeof(ss));
1273                 memcpy(&ss, res->ai_addr, res->ai_addrlen);
1274
1275                 *return_count += 1;
1276
1277                 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1278                                                 struct ip_service,
1279                                                 *return_count);
1280                 if (!*return_iplist) {
1281                         DEBUG(3,("resolve_hosts: malloc fail !\n"));
1282                         freeaddrinfo(ailist);
1283                         return NT_STATUS_NO_MEMORY;
1284                 }
1285                 (*return_iplist)[i].ss = ss;
1286                 (*return_iplist)[i].port = PORT_NONE;
1287                 i++;
1288         }
1289         if (ailist) {
1290                 freeaddrinfo(ailist);
1291         }
1292         if (*return_count) {
1293                 return NT_STATUS_OK;
1294         }
1295         return NT_STATUS_UNSUCCESSFUL;
1296 }
1297
1298 /********************************************************
1299  Resolve via "ADS" method.
1300 *********************************************************/
1301
1302 static NTSTATUS resolve_ads(const char *name,
1303                             int name_type,
1304                             const char *sitename,
1305                             struct ip_service **return_iplist,
1306                             int *return_count)
1307 {
1308         int                     i, j;
1309         NTSTATUS                status;
1310         TALLOC_CTX              *ctx;
1311         struct dns_rr_srv       *dcs = NULL;
1312         int                     numdcs = 0;
1313         int                     numaddrs = 0;
1314
1315         if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1316             (name_type != 0x1b)) {
1317                 return NT_STATUS_INVALID_PARAMETER;
1318         }
1319
1320         if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1321                 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1322                 return NT_STATUS_NO_MEMORY;
1323         }
1324
1325         /* The DNS code needs fixing to find IPv6 addresses... JRA. */
1326
1327         switch (name_type) {
1328                 case 0x1b:
1329                         DEBUG(5,("resolve_ads: Attempting to resolve "
1330                                  "PDC for %s using DNS\n", name));
1331                         status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1332                         break;
1333
1334                 case 0x1c:
1335                         DEBUG(5,("resolve_ads: Attempting to resolve "
1336                                  "DCs for %s using DNS\n", name));
1337                         status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1338                                                    &numdcs);
1339                         break;
1340                 case KDC_NAME_TYPE:
1341                         DEBUG(5,("resolve_ads: Attempting to resolve "
1342                                  "KDCs for %s using DNS\n", name));
1343                         status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1344                                                     &numdcs);
1345                         break;
1346                 default:
1347                         status = NT_STATUS_INVALID_PARAMETER;
1348                         break;
1349         }
1350
1351         if ( !NT_STATUS_IS_OK( status ) ) {
1352                 talloc_destroy(ctx);
1353                 return status;
1354         }
1355
1356         for (i=0;i<numdcs;i++) {
1357                 numaddrs += MAX(dcs[i].num_ips,1);
1358         }
1359
1360         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
1361                         NULL ) {
1362                 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
1363                                         numaddrs ));
1364                 talloc_destroy(ctx);
1365                 return NT_STATUS_NO_MEMORY;
1366         }
1367
1368         /* now unroll the list of IP addresses */
1369
1370         *return_count = 0;
1371         i = 0;
1372         j = 0;
1373         while ( i < numdcs && (*return_count<numaddrs) ) {
1374                 struct ip_service *r = &(*return_iplist)[*return_count];
1375
1376                 r->port = dcs[i].port;
1377
1378                 /* If we don't have an IP list for a name, lookup it up */
1379
1380                 if (!dcs[i].ss_s) {
1381                         interpret_string_addr(&r->ss, dcs[i].hostname, 0);
1382                         i++;
1383                         j = 0;
1384                 } else {
1385                         /* use the IP addresses from the SRV sresponse */
1386
1387                         if ( j >= dcs[i].num_ips ) {
1388                                 i++;
1389                                 j = 0;
1390                                 continue;
1391                         }
1392
1393                         r->ss = dcs[i].ss_s[j];
1394                         j++;
1395                 }
1396
1397                 /* make sure it is a valid IP.  I considered checking the
1398                  * negative connection cache, but this is the wrong place
1399                  * for it. Maybe only as a hack. After think about it, if
1400                  * all of the IP addresses returned from DNS are dead, what
1401                  * hope does a netbios name lookup have ? The standard reason
1402                  * for falling back to netbios lookups is that our DNS server
1403                  * doesn't know anything about the DC's   -- jerry */
1404
1405                 if (!is_zero_addr(&r->ss)) {
1406                         (*return_count)++;
1407                 }
1408         }
1409
1410         talloc_destroy(ctx);
1411         return NT_STATUS_OK;
1412 }
1413
1414 /*******************************************************************
1415  Internal interface to resolve a name into an IP address.
1416  Use this function if the string is either an IP address, DNS
1417  or host name or NetBIOS name. This uses the name switch in the
1418  smb.conf to determine the order of name resolution.
1419
1420  Added support for ip addr/port to support ADS ldap servers.
1421  the only place we currently care about the port is in the
1422  resolve_hosts() when looking up DC's via SRV RR entries in DNS
1423 **********************************************************************/
1424
1425 static NTSTATUS internal_resolve_name(const char *name,
1426                                 int name_type,
1427                                 const char *sitename,
1428                                 struct ip_service **return_iplist,
1429                                 int *return_count,
1430                                 const char *resolve_order)
1431 {
1432         char *tok;
1433         const char *ptr;
1434         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1435         int i;
1436         TALLOC_CTX *frame = NULL;
1437
1438         *return_iplist = NULL;
1439         *return_count = 0;
1440
1441         DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1442                         name, name_type, sitename ? sitename : NULL));
1443
1444         if (is_ipaddress(name)) {
1445                 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
1446                                 NULL) {
1447                         DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1448                         return NT_STATUS_NO_MEMORY;
1449                 }
1450
1451                 /* ignore the port here */
1452                 (*return_iplist)->port = PORT_NONE;
1453
1454                 /* if it's in the form of an IP address then get the lib to interpret it */
1455                 if (!interpret_string_addr(&(*return_iplist)->ss,
1456                                         name, AI_NUMERICHOST)) {
1457                         DEBUG(1,("internal_resolve_name: interpret_string_addr "
1458                                 "failed on %s\n",
1459                                 name));
1460                         SAFE_FREE(*return_iplist);
1461                         return NT_STATUS_INVALID_PARAMETER;
1462                 }
1463                 *return_count = 1;
1464                 return NT_STATUS_OK;
1465         }
1466
1467         /* Check name cache */
1468
1469         if (namecache_fetch(name, name_type, return_iplist, return_count)) {
1470                 /* This could be a negative response */
1471                 if (*return_count > 0) {
1472                         return NT_STATUS_OK;
1473                 } else {
1474                         return NT_STATUS_UNSUCCESSFUL;
1475                 }
1476         }
1477
1478         /* set the name resolution order */
1479
1480         if (strcmp( resolve_order, "NULL") == 0) {
1481                 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
1482                 return NT_STATUS_INVALID_PARAMETER;
1483         }
1484
1485         if (!resolve_order[0]) {
1486                 ptr = "host";
1487         } else {
1488                 ptr = resolve_order;
1489         }
1490
1491         /* iterate through the name resolution backends */
1492
1493         frame = talloc_stackframe();
1494         while (next_token_talloc(frame, &ptr, &tok, LIST_SEP)) {
1495                 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
1496                         status = resolve_hosts(name, name_type, return_iplist,
1497                                                return_count);
1498                         if (NT_STATUS_IS_OK(status)) {
1499                                 goto done;
1500                         }
1501                 } else if(strequal( tok, "kdc")) {
1502                         /* deal with KDC_NAME_TYPE names here.
1503                          * This will result in a SRV record lookup */
1504                         status = resolve_ads(name, KDC_NAME_TYPE, sitename,
1505                                              return_iplist, return_count);
1506                         if (NT_STATUS_IS_OK(status)) {
1507                                 /* Ensure we don't namecache
1508                                  * this with the KDC port. */
1509                                 name_type = KDC_NAME_TYPE;
1510                                 goto done;
1511                         }
1512                 } else if(strequal( tok, "ads")) {
1513                         /* deal with 0x1c and 0x1b names here.
1514                          * This will result in a SRV record lookup */
1515                         status = resolve_ads(name, name_type, sitename,
1516                                              return_iplist, return_count);
1517                         if (NT_STATUS_IS_OK(status)) {
1518                                 goto done;
1519                         }
1520                 } else if(strequal( tok, "lmhosts")) {
1521                         status = resolve_lmhosts(name, name_type,
1522                                                  return_iplist, return_count);
1523                         if (NT_STATUS_IS_OK(status)) {
1524                                 goto done;
1525                         }
1526                 } else if(strequal( tok, "wins")) {
1527                         /* don't resolve 1D via WINS */
1528                         if (name_type != 0x1D) {
1529                                 status = resolve_wins(name, name_type,
1530                                                       return_iplist,
1531                                                       return_count);
1532                                 if (NT_STATUS_IS_OK(status)) {
1533                                         goto done;
1534                                 }
1535                         }
1536                 } else if(strequal( tok, "bcast")) {
1537                         status = name_resolve_bcast(name, name_type,
1538                                                     return_iplist,
1539                                                     return_count);
1540                         if (NT_STATUS_IS_OK(status)) {
1541                                 goto done;
1542                         }
1543                 } else {
1544                         DEBUG(0,("resolve_name: unknown name switch type %s\n",
1545                                 tok));
1546                 }
1547         }
1548
1549         /* All of the resolve_* functions above have returned false. */
1550
1551         TALLOC_FREE(frame);
1552         SAFE_FREE(*return_iplist);
1553         *return_count = 0;
1554
1555         return NT_STATUS_UNSUCCESSFUL;
1556
1557   done:
1558
1559         /* Remove duplicate entries.  Some queries, notably #1c (domain
1560         controllers) return the PDC in iplist[0] and then all domain
1561         controllers including the PDC in iplist[1..n].  Iterating over
1562         the iplist when the PDC is down will cause two sets of timeouts. */
1563
1564         if ( *return_count ) {
1565                 *return_count = remove_duplicate_addrs2(*return_iplist,
1566                                         *return_count );
1567         }
1568
1569         /* Save in name cache */
1570         if ( DEBUGLEVEL >= 100 ) {
1571                 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
1572                         char addr[INET6_ADDRSTRLEN];
1573                         print_sockaddr(addr, sizeof(addr),
1574                                         &(*return_iplist)[i].ss);
1575                         DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
1576                                         name,
1577                                         name_type,
1578                                         addr,
1579                                         (*return_iplist)[i].port));
1580                 }
1581         }
1582
1583         namecache_store(name, name_type, *return_count, *return_iplist);
1584
1585         /* Display some debugging info */
1586
1587         if ( DEBUGLEVEL >= 10 ) {
1588                 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
1589                                         *return_count));
1590
1591                 for (i = 0; i < *return_count; i++) {
1592                         char addr[INET6_ADDRSTRLEN];
1593                         print_sockaddr(addr, sizeof(addr),
1594                                         &(*return_iplist)[i].ss);
1595                         DEBUGADD(10, ("%s:%d ",
1596                                         addr,
1597                                         (*return_iplist)[i].port));
1598                 }
1599                 DEBUG(10, ("\n"));
1600         }
1601
1602         TALLOC_FREE(frame);
1603         return status;
1604 }
1605
1606 /********************************************************
1607  Internal interface to resolve a name into one IP address.
1608  Use this function if the string is either an IP address, DNS
1609  or host name or NetBIOS name. This uses the name switch in the
1610  smb.conf to determine the order of name resolution.
1611 *********************************************************/
1612
1613 bool resolve_name(const char *name,
1614                 struct sockaddr_storage *return_ss,
1615                 int name_type)
1616 {
1617         struct ip_service *ss_list = NULL;
1618         char *sitename = NULL;
1619         int count = 0;
1620
1621         if (is_ipaddress(name)) {
1622                 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
1623         }
1624
1625         sitename = sitename_fetch(lp_realm()); /* wild guess */
1626
1627         if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
1628                                                   &ss_list, &count,
1629                                                   lp_name_resolve_order()))) {
1630                 int i;
1631
1632                 /* only return valid addresses for TCP connections */
1633                 for (i=0; i<count; i++) {
1634                         if (!is_zero_addr(&ss_list[i].ss) &&
1635                                         !is_broadcast_addr(&ss_list[i].ss)) {
1636                                 *return_ss = ss_list[i].ss;
1637                                 SAFE_FREE(ss_list);
1638                                 SAFE_FREE(sitename);
1639                                 return True;
1640                         }
1641                 }
1642         }
1643
1644         SAFE_FREE(ss_list);
1645         SAFE_FREE(sitename);
1646         return False;
1647 }
1648
1649 /********************************************************
1650  Internal interface to resolve a name into a list of IP addresses.
1651  Use this function if the string is either an IP address, DNS
1652  or host name or NetBIOS name. This uses the name switch in the
1653  smb.conf to determine the order of name resolution.
1654 *********************************************************/
1655
1656 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
1657                 const char *name,
1658                 int name_type,
1659                 struct sockaddr_storage **return_ss_arr,
1660                 unsigned int *p_num_entries)
1661 {
1662         struct ip_service *ss_list = NULL;
1663         char *sitename = NULL;
1664         int count = 0;
1665         int i;
1666         unsigned int num_entries;
1667         NTSTATUS status;
1668
1669         *p_num_entries = 0;
1670         *return_ss_arr = NULL;
1671
1672         if (is_ipaddress(name)) {
1673                 *return_ss_arr = TALLOC_P(ctx, struct sockaddr_storage);
1674                 if (!*return_ss_arr) {
1675                         return NT_STATUS_NO_MEMORY;
1676                 }
1677                 if (!interpret_string_addr(*return_ss_arr, name, AI_NUMERICHOST)) {
1678                         TALLOC_FREE(*return_ss_arr);
1679                         return NT_STATUS_BAD_NETWORK_NAME;
1680                 }
1681                 *p_num_entries = 1;
1682                 return NT_STATUS_OK;
1683         }
1684
1685         sitename = sitename_fetch(lp_realm()); /* wild guess */
1686
1687         status = internal_resolve_name(name, name_type, sitename,
1688                                                   &ss_list, &count,
1689                                                   lp_name_resolve_order());
1690         SAFE_FREE(sitename);
1691
1692         if (!NT_STATUS_IS_OK(status)) {
1693                 return status;
1694         }
1695
1696         /* only return valid addresses for TCP connections */
1697         for (i=0, num_entries = 0; i<count; i++) {
1698                 if (!is_zero_addr(&ss_list[i].ss) &&
1699                                 !is_broadcast_addr(&ss_list[i].ss)) {
1700                         num_entries++;
1701                 }
1702         }
1703         if (num_entries == 0) {
1704                 SAFE_FREE(ss_list);
1705                 return NT_STATUS_BAD_NETWORK_NAME;
1706         }
1707
1708         *return_ss_arr = TALLOC_ARRAY(ctx,
1709                                 struct sockaddr_storage,
1710                                 num_entries);
1711         if (!(*return_ss_arr)) {
1712                 SAFE_FREE(ss_list);
1713                 return NT_STATUS_NO_MEMORY;
1714         }
1715
1716         for (i=0, num_entries = 0; i<count; i++) {
1717                 if (!is_zero_addr(&ss_list[i].ss) &&
1718                                 !is_broadcast_addr(&ss_list[i].ss)) {
1719                         (*return_ss_arr)[num_entries++] = ss_list[i].ss;
1720                 }
1721         }
1722
1723         status = NT_STATUS_OK;
1724         *p_num_entries = num_entries;
1725
1726         SAFE_FREE(ss_list);
1727         return NT_STATUS_OK;
1728 }
1729
1730 /********************************************************
1731  Find the IP address of the master browser or DMB for a workgroup.
1732 *********************************************************/
1733
1734 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
1735 {
1736         struct ip_service *ip_list = NULL;
1737         int count = 0;
1738         NTSTATUS status;
1739
1740         if (lp_disable_netbios()) {
1741                 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
1742                 return false;
1743         }
1744
1745         status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
1746                                        lp_name_resolve_order());
1747         if (NT_STATUS_IS_OK(status)) {
1748                 *master_ss = ip_list[0].ss;
1749                 SAFE_FREE(ip_list);
1750                 return true;
1751         }
1752
1753         status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
1754                                        lp_name_resolve_order());
1755         if (NT_STATUS_IS_OK(status)) {
1756                 *master_ss = ip_list[0].ss;
1757                 SAFE_FREE(ip_list);
1758                 return true;
1759         }
1760
1761         SAFE_FREE(ip_list);
1762         return false;
1763 }
1764
1765 /********************************************************
1766  Get the IP address list of the primary domain controller
1767  for a domain.
1768 *********************************************************/
1769
1770 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
1771 {
1772         struct ip_service *ip_list = NULL;
1773         int count = 0;
1774         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1775
1776         /* Look up #1B name */
1777
1778         if (lp_security() == SEC_ADS) {
1779                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1780                                                &count, "ads");
1781         }
1782
1783         if (!NT_STATUS_IS_OK(status) || count == 0) {
1784                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1785                                                &count,
1786                                                lp_name_resolve_order());
1787                 if (!NT_STATUS_IS_OK(status)) {
1788                         return false;
1789                 }
1790         }
1791
1792         /* if we get more than 1 IP back we have to assume it is a
1793            multi-homed PDC and not a mess up */
1794
1795         if ( count > 1 ) {
1796                 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
1797                 sort_service_list(ip_list, count);
1798         }
1799
1800         *pss = ip_list[0].ss;
1801         SAFE_FREE(ip_list);
1802         return true;
1803 }
1804
1805 /* Private enum type for lookups. */
1806
1807 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
1808
1809 /********************************************************
1810  Get the IP address list of the domain controllers for
1811  a domain.
1812 *********************************************************/
1813
1814 static NTSTATUS get_dc_list(const char *domain,
1815                         const char *sitename,
1816                         struct ip_service **ip_list,
1817                         int *count,
1818                         enum dc_lookup_type lookup_type,
1819                         bool *ordered)
1820 {
1821         char *resolve_order = NULL;
1822         char *saf_servername = NULL;
1823         char *pserver = NULL;
1824         const char *p;
1825         char *port_str = NULL;
1826         int port;
1827         char *name;
1828         int num_addresses = 0;
1829         int  local_count, i, j;
1830         struct ip_service *return_iplist = NULL;
1831         struct ip_service *auto_ip_list = NULL;
1832         bool done_auto_lookup = false;
1833         int auto_count = 0;
1834         NTSTATUS status;
1835         TALLOC_CTX *ctx = talloc_init("get_dc_list");
1836
1837         if (!ctx) {
1838                 return NT_STATUS_NO_MEMORY;
1839         }
1840
1841         *ordered = False;
1842
1843         /* if we are restricted to solely using DNS for looking
1844            up a domain controller, make sure that host lookups
1845            are enabled for the 'name resolve order'.  If host lookups
1846            are disabled and ads_only is True, then set the string to
1847            NULL. */
1848
1849         resolve_order = talloc_strdup(ctx, lp_name_resolve_order());
1850         if (!resolve_order) {
1851                 status = NT_STATUS_NO_MEMORY;
1852                 goto out;
1853         }
1854         strlower_m(resolve_order);
1855         if (lookup_type == DC_ADS_ONLY)  {
1856                 if (strstr( resolve_order, "host")) {
1857                         resolve_order = talloc_strdup(ctx, "ads");
1858
1859                         /* DNS SRV lookups used by the ads resolver
1860                            are already sorted by priority and weight */
1861                         *ordered = true;
1862                 } else {
1863                         resolve_order = talloc_strdup(ctx, "NULL");
1864                 }
1865         } else if (lookup_type == DC_KDC_ONLY) {
1866                 /* DNS SRV lookups used by the ads/kdc resolver
1867                    are already sorted by priority and weight */
1868                 *ordered = true;
1869                 resolve_order = talloc_strdup(ctx, "kdc");
1870         }
1871         if (!resolve_order) {
1872                 status = NT_STATUS_NO_MEMORY;
1873                 goto out;
1874         }
1875
1876         /* fetch the server we have affinity for.  Add the
1877            'password server' list to a search for our domain controllers */
1878
1879         saf_servername = saf_fetch( domain);
1880
1881         if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
1882                 pserver = talloc_asprintf(NULL, "%s, %s",
1883                         saf_servername ? saf_servername : "",
1884                         lp_passwordserver());
1885         } else {
1886                 pserver = talloc_asprintf(NULL, "%s, *",
1887                         saf_servername ? saf_servername : "");
1888         }
1889
1890         SAFE_FREE(saf_servername);
1891         if (!pserver) {
1892                 status = NT_STATUS_NO_MEMORY;
1893                 goto out;
1894         }
1895
1896         /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
1897
1898         if (!*pserver ) {
1899                 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
1900                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
1901                                              count, resolve_order);
1902                 goto out;
1903         }
1904
1905         DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
1906
1907         /*
1908          * if '*' appears in the "password server" list then add
1909          * an auto lookup to the list of manually configured
1910          * DC's.  If any DC is listed by name, then the list should be
1911          * considered to be ordered
1912          */
1913
1914         p = pserver;
1915         while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
1916                 if (strequal(name, "*")) {
1917                         status = internal_resolve_name(domain, 0x1C, sitename,
1918                                                        &auto_ip_list,
1919                                                        &auto_count,
1920                                                        resolve_order);
1921                         if (NT_STATUS_IS_OK(status)) {
1922                                 num_addresses += auto_count;
1923                         }
1924                         done_auto_lookup = true;
1925                         DEBUG(8,("Adding %d DC's from auto lookup\n",
1926                                                 auto_count));
1927                 } else  {
1928                         num_addresses++;
1929                 }
1930         }
1931
1932         /* if we have no addresses and haven't done the auto lookup, then
1933            just return the list of DC's.  Or maybe we just failed. */
1934
1935         if ((num_addresses == 0)) {
1936                 if (done_auto_lookup) {
1937                         DEBUG(4,("get_dc_list: no servers found\n"));
1938                         status = NT_STATUS_NO_LOGON_SERVERS;
1939                         goto out;
1940                 }
1941                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
1942                                              count, resolve_order);
1943                 goto out;
1944         }
1945
1946         if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
1947                                         num_addresses)) == NULL) {
1948                 DEBUG(3,("get_dc_list: malloc fail !\n"));
1949                 status = NT_STATUS_NO_MEMORY;
1950                 goto out;
1951         }
1952
1953         p = pserver;
1954         local_count = 0;
1955
1956         /* fill in the return list now with real IP's */
1957
1958         while ((local_count<num_addresses) &&
1959                         next_token_talloc(ctx, &p, &name, LIST_SEP)) {
1960                 struct sockaddr_storage name_ss;
1961
1962                 /* copy any addersses from the auto lookup */
1963
1964                 if (strequal(name, "*")) {
1965                         for (j=0; j<auto_count; j++) {
1966                                 char addr[INET6_ADDRSTRLEN];
1967                                 print_sockaddr(addr,
1968                                                 sizeof(addr),
1969                                                 &auto_ip_list[j].ss);
1970                                 /* Check for and don't copy any
1971                                  * known bad DC IP's. */
1972                                 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
1973                                                 domain,
1974                                                 addr))) {
1975                                         DEBUG(5,("get_dc_list: "
1976                                                 "negative entry %s removed "
1977                                                 "from DC list\n",
1978                                                 addr));
1979                                         continue;
1980                                 }
1981                                 return_iplist[local_count].ss =
1982                                         auto_ip_list[j].ss;
1983                                 return_iplist[local_count].port =
1984                                         auto_ip_list[j].port;
1985                                 local_count++;
1986                         }
1987                         continue;
1988                 }
1989
1990                 /* added support for address:port syntax for ads
1991                  * (not that I think anyone will ever run the LDAP
1992                  * server in an AD domain on something other than
1993                  * port 389 */
1994
1995                 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
1996                 if ((port_str=strchr(name, ':')) != NULL) {
1997                         *port_str = '\0';
1998                         port_str++;
1999                         port = atoi(port_str);
2000                 }
2001
2002                 /* explicit lookup; resolve_name() will
2003                  * handle names & IP addresses */
2004                 if (resolve_name( name, &name_ss, 0x20 )) {
2005                         char addr[INET6_ADDRSTRLEN];
2006                         print_sockaddr(addr,
2007                                         sizeof(addr),
2008                                         &name_ss);
2009
2010                         /* Check for and don't copy any known bad DC IP's. */
2011                         if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
2012                                                         addr)) ) {
2013                                 DEBUG(5,("get_dc_list: negative entry %s "
2014                                         "removed from DC list\n",
2015                                         name ));
2016                                 continue;
2017                         }
2018
2019                         return_iplist[local_count].ss = name_ss;
2020                         return_iplist[local_count].port = port;
2021                         local_count++;
2022                         *ordered = true;
2023                 }
2024         }
2025
2026         /* need to remove duplicates in the list if we have any
2027            explicit password servers */
2028
2029         if (local_count) {
2030                 local_count = remove_duplicate_addrs2(return_iplist,
2031                                 local_count );
2032         }
2033
2034         if ( DEBUGLEVEL >= 4 ) {
2035                 DEBUG(4,("get_dc_list: returning %d ip addresses "
2036                                 "in an %sordered list\n",
2037                                 local_count,
2038                                 *ordered ? "":"un"));
2039                 DEBUG(4,("get_dc_list: "));
2040                 for ( i=0; i<local_count; i++ ) {
2041                         char addr[INET6_ADDRSTRLEN];
2042                         print_sockaddr(addr,
2043                                         sizeof(addr),
2044                                         &return_iplist[i].ss);
2045                         DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
2046                 }
2047                 DEBUGADD(4,("\n"));
2048         }
2049
2050         *ip_list = return_iplist;
2051         *count = local_count;
2052
2053         status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
2054
2055   out:
2056
2057         SAFE_FREE(auto_ip_list);
2058         TALLOC_FREE(ctx);
2059         return status;
2060 }
2061
2062 /*********************************************************************
2063  Small wrapper function to get the DC list and sort it if neccessary.
2064 *********************************************************************/
2065
2066 NTSTATUS get_sorted_dc_list( const char *domain,
2067                         const char *sitename,
2068                         struct ip_service **ip_list,
2069                         int *count,
2070                         bool ads_only )
2071 {
2072         bool ordered;
2073         NTSTATUS status;
2074         enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
2075
2076         DEBUG(8,("get_sorted_dc_list: attempting lookup "
2077                 "for name %s (sitename %s) using [%s]\n",
2078                 domain,
2079                 sitename ? sitename : "NULL",
2080                 (ads_only ? "ads" : lp_name_resolve_order())));
2081
2082         if (ads_only) {
2083                 lookup_type = DC_ADS_ONLY;
2084         }
2085
2086         status = get_dc_list(domain, sitename, ip_list,
2087                         count, lookup_type, &ordered);
2088         if (!NT_STATUS_IS_OK(status)) {
2089                 return status;
2090         }
2091
2092         /* only sort if we don't already have an ordered list */
2093         if (!ordered) {
2094                 sort_service_list(*ip_list, *count);
2095         }
2096
2097         return NT_STATUS_OK;
2098 }
2099
2100 /*********************************************************************
2101  Get the KDC list - re-use all the logic in get_dc_list.
2102 *********************************************************************/
2103
2104 NTSTATUS get_kdc_list( const char *realm,
2105                         const char *sitename,
2106                         struct ip_service **ip_list,
2107                         int *count)
2108 {
2109         bool ordered;
2110         NTSTATUS status;
2111
2112         *count = 0;
2113         *ip_list = NULL;
2114
2115         status = get_dc_list(realm, sitename, ip_list,
2116                         count, DC_KDC_ONLY, &ordered);
2117
2118         if (!NT_STATUS_IS_OK(status)) {
2119                 return status;
2120         }
2121
2122         /* only sort if we don't already have an ordered list */
2123         if ( !ordered ) {
2124                 sort_service_list(*ip_list, *count);
2125         }
2126
2127         return NT_STATUS_OK;
2128 }