Specifically ask for IP4 addresses if we don't have IP6 support.
[metze/samba/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;
795                 char *flags;
796                 char *extra;
797                 char *name;
798                 const char *ptr;
799                 char *ptr1;
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                 ip[0] = '\0';
813                 name[0] = '\0';
814                 flags[0] = '\0';
815
816                 ptr = line;
817
818                 if (next_token_talloc(ctx, &ptr, &ip, NULL))
819                         ++count;
820                 if (next_token_talloc(ctx, &ptr, &name, NULL))
821                         ++count;
822                 if (next_token_talloc(ctx, &ptr, &flags, NULL))
823                         ++count;
824                 if (next_token_talloc(ctx, &ptr, &extra, NULL))
825                         ++count;
826
827                 if (count <= 0)
828                         continue;
829
830                 if (count > 0 && count < 2) {
831                         DEBUG(0,("getlmhostsent: Ill formed hosts line [%s]\n",
832                                                 line));
833                         continue;
834                 }
835
836                 if (count >= 4) {
837                         DEBUG(0,("getlmhostsent: too many columns "
838                                 "in lmhosts file (obsolete syntax)\n"));
839                         continue;
840                 }
841
842                 DEBUG(4, ("getlmhostsent: lmhost entry: %s %s %s\n",
843                                         ip, name, flags));
844
845                 if (strchr_m(flags,'G') || strchr_m(flags,'S')) {
846                         DEBUG(0,("getlmhostsent: group flag "
847                                 "in lmhosts ignored (obsolete)\n"));
848                         continue;
849                 }
850
851                 if (!interpret_string_addr(pss, ip, AI_NUMERICHOST)) {
852                         DEBUG(0,("getlmhostsent: invalid address "
853                                 "%s.\n", ip));
854                 }
855
856                 /* Extra feature. If the name ends in '#XX',
857                  * where XX is a hex number, then only add that name type. */
858                 if((ptr1 = strchr_m(name, '#')) != NULL) {
859                         char *endptr;
860                         ptr1++;
861
862                         *name_type = (int)strtol(ptr1, &endptr, 16);
863                         if(!*ptr1 || (endptr == ptr1)) {
864                                 DEBUG(0,("getlmhostsent: invalid name "
865                                         "%s containing '#'.\n", name));
866                                 continue;
867                         }
868
869                         *(--ptr1) = '\0'; /* Truncate at the '#' */
870                 }
871
872                 *pp_name = talloc_strdup(ctx, name);
873                 if (!*pp_name) {
874                         return false;
875                 }
876                 return true;
877         }
878
879         return false;
880 }
881
882 /********************************************************
883  Finish parsing the lmhosts file.
884 *********************************************************/
885
886 void endlmhosts(XFILE *fp)
887 {
888         x_fclose(fp);
889 }
890
891 /********************************************************
892  convert an array if struct sockaddr_storage to struct ip_service
893  return false on failure.  Port is set to PORT_NONE;
894 *********************************************************/
895
896 static bool convert_ss2service(struct ip_service **return_iplist,
897                 const struct sockaddr_storage *ss_list,
898                 int count)
899 {
900         int i;
901
902         if ( count==0 || !ss_list )
903                 return False;
904
905         /* copy the ip address; port will be PORT_NONE */
906         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) ==
907                         NULL) {
908                 DEBUG(0,("convert_ip2service: malloc failed "
909                         "for %d enetries!\n", count ));
910                 return False;
911         }
912
913         for ( i=0; i<count; i++ ) {
914                 (*return_iplist)[i].ss   = ss_list[i];
915                 (*return_iplist)[i].port = PORT_NONE;
916         }
917
918         return true;
919 }
920
921 /********************************************************
922  Resolve via "bcast" method.
923 *********************************************************/
924
925 NTSTATUS name_resolve_bcast(const char *name,
926                         int name_type,
927                         struct ip_service **return_iplist,
928                         int *return_count)
929 {
930         int sock, i;
931         int num_interfaces = iface_count();
932         struct sockaddr_storage *ss_list;
933         struct sockaddr_storage ss;
934         NTSTATUS status;
935
936         if (lp_disable_netbios()) {
937                 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n",
938                                         name, name_type));
939                 return NT_STATUS_INVALID_PARAMETER;
940         }
941
942         *return_iplist = NULL;
943         *return_count = 0;
944
945         /*
946          * "bcast" means do a broadcast lookup on all the local interfaces.
947          */
948
949         DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup "
950                 "for name %s<0x%x>\n", name, name_type));
951
952         if (!interpret_string_addr(&ss, lp_socket_address(),
953                                 AI_NUMERICHOST|AI_PASSIVE)) {
954                 zero_addr(&ss);
955         }
956
957         sock = open_socket_in( SOCK_DGRAM, 0, 3, &ss, true );
958         if (sock == -1) {
959                 return NT_STATUS_UNSUCCESSFUL;
960         }
961
962         set_socket_options(sock,"SO_BROADCAST");
963         /*
964          * Lookup the name on all the interfaces, return on
965          * the first successful match.
966          */
967         for( i = num_interfaces-1; i >= 0; i--) {
968                 const struct sockaddr_storage *pss = iface_n_bcast(i);
969                 int flags;
970
971                 /* Done this way to fix compiler error on IRIX 5.x */
972                 if (!pss) {
973                         continue;
974                 }
975                 ss_list = name_query(sock, name, name_type, true,
976                                     true, pss, return_count, &flags, NULL);
977                 if (ss_list) {
978                         goto success;
979                 }
980         }
981
982         /* failed - no response */
983
984         close(sock);
985         return NT_STATUS_UNSUCCESSFUL;
986
987 success:
988
989         status = NT_STATUS_OK;
990         if (!convert_ss2service(return_iplist, ss_list, *return_count) )
991                 status = NT_STATUS_INVALID_PARAMETER;
992
993         SAFE_FREE(ss_list);
994         close(sock);
995         return status;
996 }
997
998 /********************************************************
999  Resolve via "wins" method.
1000 *********************************************************/
1001
1002 NTSTATUS resolve_wins(const char *name,
1003                 int name_type,
1004                 struct ip_service **return_iplist,
1005                 int *return_count)
1006 {
1007         int sock, t, i;
1008         char **wins_tags;
1009         struct sockaddr_storage src_ss, *ss_list = NULL;
1010         struct in_addr src_ip;
1011         NTSTATUS status;
1012
1013         if (lp_disable_netbios()) {
1014                 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n",
1015                                         name, name_type));
1016                 return NT_STATUS_INVALID_PARAMETER;
1017         }
1018
1019         *return_iplist = NULL;
1020         *return_count = 0;
1021
1022         DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n",
1023                                 name, name_type));
1024
1025         if (wins_srv_count() < 1) {
1026                 DEBUG(3,("resolve_wins: WINS server resolution selected "
1027                         "and no WINS servers listed.\n"));
1028                 return NT_STATUS_INVALID_PARAMETER;
1029         }
1030
1031         /* we try a lookup on each of the WINS tags in turn */
1032         wins_tags = wins_srv_tags();
1033
1034         if (!wins_tags) {
1035                 /* huh? no tags?? give up in disgust */
1036                 return NT_STATUS_INVALID_PARAMETER;
1037         }
1038
1039         /* the address we will be sending from */
1040         if (!interpret_string_addr(&src_ss, lp_socket_address(),
1041                                 AI_NUMERICHOST|AI_PASSIVE)) {
1042                 zero_addr(&src_ss);
1043         }
1044
1045         if (src_ss.ss_family != AF_INET) {
1046                 char addr[INET6_ADDRSTRLEN];
1047                 print_sockaddr(addr, sizeof(addr), &src_ss);
1048                 DEBUG(3,("resolve_wins: cannot receive WINS replies "
1049                         "on IPv6 address %s\n",
1050                         addr));
1051                 return NT_STATUS_INVALID_PARAMETER;
1052         }
1053
1054         src_ip = ((struct sockaddr_in *)&src_ss)->sin_addr;
1055
1056         /* in the worst case we will try every wins server with every
1057            tag! */
1058         for (t=0; wins_tags && wins_tags[t]; t++) {
1059                 int srv_count = wins_srv_count_tag(wins_tags[t]);
1060                 for (i=0; i<srv_count; i++) {
1061                         struct sockaddr_storage wins_ss;
1062                         struct in_addr wins_ip;
1063                         int flags;
1064                         bool timed_out;
1065
1066                         wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
1067
1068                         if (global_in_nmbd && ismyip_v4(wins_ip)) {
1069                                 /* yikes! we'll loop forever */
1070                                 continue;
1071                         }
1072
1073                         /* skip any that have been unresponsive lately */
1074                         if (wins_srv_is_dead(wins_ip, src_ip)) {
1075                                 continue;
1076                         }
1077
1078                         DEBUG(3,("resolve_wins: using WINS server %s "
1079                                 "and tag '%s'\n",
1080                                 inet_ntoa(wins_ip), wins_tags[t]));
1081
1082                         sock = open_socket_in(SOCK_DGRAM, 0, 3, &src_ss, true);
1083                         if (sock == -1) {
1084                                 continue;
1085                         }
1086
1087                         in_addr_to_sockaddr_storage(&wins_ss, wins_ip);
1088                         ss_list = name_query(sock,
1089                                                 name,
1090                                                 name_type,
1091                                                 false,
1092                                                 true,
1093                                                 &wins_ss,
1094                                                 return_count,
1095                                                 &flags,
1096                                                 &timed_out);
1097
1098                         /* exit loop if we got a list of addresses */
1099
1100                         if (ss_list)
1101                                 goto success;
1102
1103                         close(sock);
1104
1105                         if (timed_out) {
1106                                 /* Timed out wating for WINS server to respond.
1107                                  * Mark it dead. */
1108                                 wins_srv_died(wins_ip, src_ip);
1109                         } else {
1110                                 /* The name definately isn't in this
1111                                    group of WINS servers.
1112                                    goto the next group  */
1113                                 break;
1114                         }
1115                 }
1116         }
1117
1118         wins_srv_tags_free(wins_tags);
1119         return NT_STATUS_NO_LOGON_SERVERS;
1120
1121 success:
1122
1123         status = NT_STATUS_OK;
1124         if (!convert_ss2service(return_iplist, ss_list, *return_count))
1125                 status = NT_STATUS_INVALID_PARAMETER;
1126
1127         SAFE_FREE(ss_list);
1128         wins_srv_tags_free(wins_tags);
1129         close(sock);
1130
1131         return status;
1132 }
1133
1134 /********************************************************
1135  Resolve via "lmhosts" method.
1136 *********************************************************/
1137
1138 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
1139                                 struct ip_service **return_iplist,
1140                                 int *return_count)
1141 {
1142         /*
1143          * "lmhosts" means parse the local lmhosts file.
1144          */
1145
1146         XFILE *fp;
1147         char *lmhost_name = NULL;
1148         int name_type2;
1149         struct sockaddr_storage return_ss;
1150         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1151         TALLOC_CTX *ctx = NULL;
1152
1153         *return_iplist = NULL;
1154         *return_count = 0;
1155
1156         DEBUG(3,("resolve_lmhosts: "
1157                 "Attempting lmhosts lookup for name %s<0x%x>\n",
1158                 name, name_type));
1159
1160         fp = startlmhosts(dyn_LMHOSTSFILE);
1161
1162         if ( fp == NULL )
1163                 return NT_STATUS_NO_SUCH_FILE;
1164
1165         ctx = talloc_init("resolve_lmhosts");
1166         if (!ctx) {
1167                 endlmhosts(fp);
1168                 return NT_STATUS_NO_MEMORY;
1169         }
1170
1171         while (getlmhostsent(ctx, fp, &lmhost_name, &name_type2, &return_ss)) {
1172
1173                 if (!strequal(name, lmhost_name)) {
1174                         TALLOC_FREE(lmhost_name);
1175                         continue;
1176                 }
1177
1178                 if ((name_type2 != -1) && (name_type != name_type2)) {
1179                         TALLOC_FREE(lmhost_name);
1180                         continue;
1181                 }
1182
1183                 *return_iplist = SMB_REALLOC_ARRAY((*return_iplist),
1184                                         struct ip_service,
1185                                         (*return_count)+1);
1186
1187                 if ((*return_iplist) == NULL) {
1188                         TALLOC_FREE(ctx);
1189                         endlmhosts(fp);
1190                         DEBUG(3,("resolve_lmhosts: malloc fail !\n"));
1191                         return NT_STATUS_NO_MEMORY;
1192                 }
1193
1194                 (*return_iplist)[*return_count].ss = return_ss;
1195                 (*return_iplist)[*return_count].port = PORT_NONE;
1196                 *return_count += 1;
1197
1198                 /* we found something */
1199                 status = NT_STATUS_OK;
1200
1201                 /* Multiple names only for DC lookup */
1202                 if (name_type != 0x1c)
1203                         break;
1204         }
1205
1206         TALLOC_FREE(ctx);
1207         endlmhosts(fp);
1208         return status;
1209 }
1210
1211
1212 /********************************************************
1213  Resolve via "hosts" method.
1214 *********************************************************/
1215
1216 static NTSTATUS resolve_hosts(const char *name, int name_type,
1217                               struct ip_service **return_iplist,
1218                               int *return_count)
1219 {
1220         /*
1221          * "host" means do a localhost, or dns lookup.
1222          */
1223         struct addrinfo hints;
1224         struct addrinfo *ailist = NULL;
1225         struct addrinfo *res = NULL;
1226         int ret = -1;
1227         int i = 0;
1228
1229         if ( name_type != 0x20 && name_type != 0x0) {
1230                 DEBUG(5, ("resolve_hosts: not appropriate "
1231                         "for name type <0x%x>\n",
1232                         name_type));
1233                 return NT_STATUS_INVALID_PARAMETER;
1234         }
1235
1236         *return_iplist = NULL;
1237         *return_count = 0;
1238
1239         DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
1240                                 name, name_type));
1241
1242         ZERO_STRUCT(hints);
1243         /* By default make sure it supports TCP. */
1244         hints.ai_socktype = SOCK_STREAM;
1245         hints.ai_flags = AI_ADDRCONFIG;
1246
1247 #if !defined(HAVE_IPV6)
1248         /* Unless we have IPv6, we really only want IPv4 addresses back. */
1249         hints.ai_family = AF_INET;
1250 #endif
1251
1252         ret = getaddrinfo(name,
1253                         NULL,
1254                         &hints,
1255                         &ailist);
1256         if (ret) {
1257                 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1258                         name,
1259                         gai_strerror(ret) ));
1260         }
1261
1262         for (res = ailist; res; res = res->ai_next) {
1263                 struct sockaddr_storage ss;
1264
1265                 if (!res->ai_addr || res->ai_addrlen == 0) {
1266                         continue;
1267                 }
1268
1269                 memset(&ss, '\0', sizeof(ss));
1270                 memcpy(&ss, res->ai_addr, res->ai_addrlen);
1271
1272                 *return_count += 1;
1273
1274                 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1275                                                 struct ip_service,
1276                                                 *return_count);
1277                 if (!*return_iplist) {
1278                         DEBUG(3,("resolve_hosts: malloc fail !\n"));
1279                         freeaddrinfo(ailist);
1280                         return NT_STATUS_NO_MEMORY;
1281                 }
1282                 (*return_iplist)[i].ss = ss;
1283                 (*return_iplist)[i].port = PORT_NONE;
1284                 i++;
1285         }
1286         if (ailist) {
1287                 freeaddrinfo(ailist);
1288         }
1289         if (*return_count) {
1290                 return NT_STATUS_OK;
1291         }
1292         return NT_STATUS_UNSUCCESSFUL;
1293 }
1294
1295 /********************************************************
1296  Resolve via "ADS" method.
1297 *********************************************************/
1298
1299 NTSTATUS resolve_ads(const char *name,
1300                         int name_type,
1301                         const char *sitename,
1302                         struct ip_service **return_iplist,
1303                         int *return_count)
1304 {
1305         int                     i, j;
1306         NTSTATUS                status;
1307         TALLOC_CTX              *ctx;
1308         struct dns_rr_srv       *dcs = NULL;
1309         int                     numdcs = 0;
1310         int                     numaddrs = 0;
1311
1312         if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1313             (name_type != 0x1b)) {
1314                 return NT_STATUS_INVALID_PARAMETER;
1315         }
1316
1317         if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1318                 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1319                 return NT_STATUS_NO_MEMORY;
1320         }
1321
1322         /* The DNS code needs fixing to find IPv6 addresses... JRA. */
1323
1324         switch (name_type) {
1325                 case 0x1b:
1326                         DEBUG(5,("resolve_ads: Attempting to resolve "
1327                                  "PDC for %s using DNS\n", name));
1328                         status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1329                         break;
1330
1331                 case 0x1c:
1332                         DEBUG(5,("resolve_ads: Attempting to resolve "
1333                                  "DCs for %s using DNS\n", name));
1334                         status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1335                                                    &numdcs);
1336                         break;
1337                 case KDC_NAME_TYPE:
1338                         DEBUG(5,("resolve_ads: Attempting to resolve "
1339                                  "KDCs for %s using DNS\n", name));
1340                         status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1341                                                     &numdcs);
1342                         break;
1343                 default:
1344                         status = NT_STATUS_INVALID_PARAMETER;
1345                         break;
1346         }
1347
1348         if ( !NT_STATUS_IS_OK( status ) ) {
1349                 talloc_destroy(ctx);
1350                 return status;
1351         }
1352
1353         for (i=0;i<numdcs;i++) {
1354                 numaddrs += MAX(dcs[i].num_ips,1);
1355         }
1356
1357         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
1358                         NULL ) {
1359                 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
1360                                         numaddrs ));
1361                 talloc_destroy(ctx);
1362                 return NT_STATUS_NO_MEMORY;
1363         }
1364
1365         /* now unroll the list of IP addresses */
1366
1367         *return_count = 0;
1368         i = 0;
1369         j = 0;
1370         while ( i < numdcs && (*return_count<numaddrs) ) {
1371                 struct ip_service *r = &(*return_iplist)[*return_count];
1372
1373                 r->port = dcs[i].port;
1374
1375                 /* If we don't have an IP list for a name, lookup it up */
1376
1377                 if (!dcs[i].ss_s) {
1378                         interpret_string_addr(&r->ss, dcs[i].hostname, 0);
1379                         i++;
1380                         j = 0;
1381                 } else {
1382                         /* use the IP addresses from the SRV sresponse */
1383
1384                         if ( j >= dcs[i].num_ips ) {
1385                                 i++;
1386                                 j = 0;
1387                                 continue;
1388                         }
1389
1390                         r->ss = dcs[i].ss_s[j];
1391                         j++;
1392                 }
1393
1394                 /* make sure it is a valid IP.  I considered checking the
1395                  * negative connection cache, but this is the wrong place
1396                  * for it. Maybe only as a hack. After think about it, if
1397                  * all of the IP addresses returned from DNS are dead, what
1398                  * hope does a netbios name lookup have ? The standard reason
1399                  * for falling back to netbios lookups is that our DNS server
1400                  * doesn't know anything about the DC's   -- jerry */
1401
1402                 if (!is_zero_addr(&r->ss)) {
1403                         (*return_count)++;
1404                 }
1405         }
1406
1407         talloc_destroy(ctx);
1408         return NT_STATUS_OK;
1409 }
1410
1411 /*******************************************************************
1412  Internal interface to resolve a name into an IP address.
1413  Use this function if the string is either an IP address, DNS
1414  or host name or NetBIOS name. This uses the name switch in the
1415  smb.conf to determine the order of name resolution.
1416
1417  Added support for ip addr/port to support ADS ldap servers.
1418  the only place we currently care about the port is in the
1419  resolve_hosts() when looking up DC's via SRV RR entries in DNS
1420 **********************************************************************/
1421
1422 NTSTATUS internal_resolve_name(const char *name,
1423                                 int name_type,
1424                                 const char *sitename,
1425                                 struct ip_service **return_iplist,
1426                                 int *return_count,
1427                                 const char *resolve_order)
1428 {
1429         const char *name_resolve_list;
1430         char *tok;
1431         const char *ptr;
1432         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1433         int i;
1434         TALLOC_CTX *frame = NULL;
1435
1436         *return_iplist = NULL;
1437         *return_count = 0;
1438
1439         DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1440                         name, name_type, sitename ? sitename : NULL));
1441
1442         if (is_ipaddress(name)) {
1443                 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
1444                                 NULL) {
1445                         DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1446                         return NT_STATUS_NO_MEMORY;
1447                 }
1448
1449                 /* ignore the port here */
1450                 (*return_iplist)->port = PORT_NONE;
1451
1452                 /* if it's in the form of an IP address then get the lib to interpret it */
1453                 if (!interpret_string_addr(&(*return_iplist)->ss,
1454                                         name, AI_NUMERICHOST)) {
1455                         DEBUG(1,("internal_resolve_name: interpret_string_addr "
1456                                 "failed on %s\n",
1457                                 name));
1458                         SAFE_FREE(*return_iplist);
1459                         return NT_STATUS_INVALID_PARAMETER;
1460                 }
1461                 *return_count = 1;
1462                 return NT_STATUS_OK;
1463         }
1464
1465         /* Check name cache */
1466
1467         if (namecache_fetch(name, name_type, return_iplist, return_count)) {
1468                 /* This could be a negative response */
1469                 if (*return_count > 0) {
1470                         return NT_STATUS_OK;
1471                 } else {
1472                         return NT_STATUS_UNSUCCESSFUL;
1473                 }
1474         }
1475
1476         /* set the name resolution order */
1477
1478         if (strcmp( resolve_order, "NULL") == 0) {
1479                 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
1480                 return NT_STATUS_INVALID_PARAMETER;
1481         }
1482
1483         if (!resolve_order) {
1484                 name_resolve_list = lp_name_resolve_order();
1485         } else {
1486                 name_resolve_list = resolve_order;
1487         }
1488
1489         if (!name_resolve_list[0]) {
1490                 ptr = "host";
1491         } else {
1492                 ptr = name_resolve_list;
1493         }
1494
1495         /* iterate through the name resolution backends */
1496
1497         frame = talloc_stackframe();
1498         while (next_token_talloc(frame, &ptr, &tok, LIST_SEP)) {
1499                 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
1500                         status = resolve_hosts(name, name_type, return_iplist,
1501                                                return_count);
1502                         if (NT_STATUS_IS_OK(status)) {
1503                                 goto done;
1504                         }
1505                 } else if(strequal( tok, "kdc")) {
1506                         /* deal with KDC_NAME_TYPE names here.
1507                          * This will result in a SRV record lookup */
1508                         status = resolve_ads(name, KDC_NAME_TYPE, sitename,
1509                                              return_iplist, return_count);
1510                         if (NT_STATUS_IS_OK(status)) {
1511                                 /* Ensure we don't namecache
1512                                  * this with the KDC port. */
1513                                 name_type = KDC_NAME_TYPE;
1514                                 goto done;
1515                         }
1516                 } else if(strequal( tok, "ads")) {
1517                         /* deal with 0x1c and 0x1b names here.
1518                          * This will result in a SRV record lookup */
1519                         status = resolve_ads(name, name_type, sitename,
1520                                              return_iplist, return_count);
1521                         if (NT_STATUS_IS_OK(status)) {
1522                                 goto done;
1523                         }
1524                 } else if(strequal( tok, "lmhosts")) {
1525                         status = resolve_lmhosts(name, name_type,
1526                                                  return_iplist, return_count);
1527                         if (NT_STATUS_IS_OK(status)) {
1528                                 goto done;
1529                         }
1530                 } else if(strequal( tok, "wins")) {
1531                         /* don't resolve 1D via WINS */
1532                         if (name_type != 0x1D) {
1533                                 status = resolve_wins(name, name_type,
1534                                                       return_iplist,
1535                                                       return_count);
1536                                 if (NT_STATUS_IS_OK(status)) {
1537                                         goto done;
1538                                 }
1539                         }
1540                 } else if(strequal( tok, "bcast")) {
1541                         status = name_resolve_bcast(name, name_type,
1542                                                     return_iplist,
1543                                                     return_count);
1544                         if (NT_STATUS_IS_OK(status)) {
1545                                 goto done;
1546                         }
1547                 } else {
1548                         DEBUG(0,("resolve_name: unknown name switch type %s\n",
1549                                 tok));
1550                 }
1551         }
1552
1553         /* All of the resolve_* functions above have returned false. */
1554
1555         TALLOC_FREE(frame);
1556         SAFE_FREE(*return_iplist);
1557         *return_count = 0;
1558
1559         return NT_STATUS_UNSUCCESSFUL;
1560
1561   done:
1562
1563         /* Remove duplicate entries.  Some queries, notably #1c (domain
1564         controllers) return the PDC in iplist[0] and then all domain
1565         controllers including the PDC in iplist[1..n].  Iterating over
1566         the iplist when the PDC is down will cause two sets of timeouts. */
1567
1568         if ( *return_count ) {
1569                 *return_count = remove_duplicate_addrs2(*return_iplist,
1570                                         *return_count );
1571         }
1572
1573         /* Save in name cache */
1574         if ( DEBUGLEVEL >= 100 ) {
1575                 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
1576                         char addr[INET6_ADDRSTRLEN];
1577                         print_sockaddr(addr, sizeof(addr),
1578                                         &(*return_iplist)[i].ss);
1579                         DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
1580                                         name,
1581                                         name_type,
1582                                         addr,
1583                                         (*return_iplist)[i].port));
1584                 }
1585         }
1586
1587         namecache_store(name, name_type, *return_count, *return_iplist);
1588
1589         /* Display some debugging info */
1590
1591         if ( DEBUGLEVEL >= 10 ) {
1592                 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
1593                                         *return_count));
1594
1595                 for (i = 0; i < *return_count; i++) {
1596                         char addr[INET6_ADDRSTRLEN];
1597                         print_sockaddr(addr, sizeof(addr),
1598                                         &(*return_iplist)[i].ss);
1599                         DEBUGADD(10, ("%s:%d ",
1600                                         addr,
1601                                         (*return_iplist)[i].port));
1602                 }
1603                 DEBUG(10, ("\n"));
1604         }
1605
1606         TALLOC_FREE(frame);
1607         return status;
1608 }
1609
1610 /********************************************************
1611  Internal interface to resolve a name into one IP address.
1612  Use this function if the string is either an IP address, DNS
1613  or host name or NetBIOS name. This uses the name switch in the
1614  smb.conf to determine the order of name resolution.
1615 *********************************************************/
1616
1617 bool resolve_name(const char *name,
1618                 struct sockaddr_storage *return_ss,
1619                 int name_type)
1620 {
1621         struct ip_service *ss_list = NULL;
1622         char *sitename = NULL;
1623         int count = 0;
1624
1625         if (is_ipaddress(name)) {
1626                 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
1627         }
1628
1629         sitename = sitename_fetch(lp_realm()); /* wild guess */
1630
1631         if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
1632                                                   &ss_list, &count,
1633                                                   lp_name_resolve_order()))) {
1634                 int i;
1635
1636                 /* only return valid addresses for TCP connections */
1637                 for (i=0; i<count; i++) {
1638                         if (!is_zero_addr(&ss_list[i].ss) &&
1639                                         !is_broadcast_addr(&ss_list[i].ss)) {
1640                                 *return_ss = ss_list[i].ss;
1641                                 SAFE_FREE(ss_list);
1642                                 SAFE_FREE(sitename);
1643                                 return True;
1644                         }
1645                 }
1646         }
1647
1648         SAFE_FREE(ss_list);
1649         SAFE_FREE(sitename);
1650         return False;
1651 }
1652
1653 /********************************************************
1654  Find the IP address of the master browser or DMB for a workgroup.
1655 *********************************************************/
1656
1657 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
1658 {
1659         struct ip_service *ip_list = NULL;
1660         int count = 0;
1661         NTSTATUS status;
1662
1663         if (lp_disable_netbios()) {
1664                 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
1665                 return false;
1666         }
1667
1668         status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
1669                                        lp_name_resolve_order());
1670         if (NT_STATUS_IS_OK(status)) {
1671                 *master_ss = ip_list[0].ss;
1672                 SAFE_FREE(ip_list);
1673                 return true;
1674         }
1675
1676         status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
1677                                        lp_name_resolve_order());
1678         if (NT_STATUS_IS_OK(status)) {
1679                 *master_ss = ip_list[0].ss;
1680                 SAFE_FREE(ip_list);
1681                 return true;
1682         }
1683
1684         SAFE_FREE(ip_list);
1685         return false;
1686 }
1687
1688 /********************************************************
1689  Get the IP address list of the primary domain controller
1690  for a domain.
1691 *********************************************************/
1692
1693 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
1694 {
1695         struct ip_service *ip_list = NULL;
1696         int count = 0;
1697         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1698
1699         /* Look up #1B name */
1700
1701         if (lp_security() == SEC_ADS) {
1702                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1703                                                &count, "ads");
1704         }
1705
1706         if (!NT_STATUS_IS_OK(status) || count == 0) {
1707                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1708                                                &count,
1709                                                lp_name_resolve_order());
1710                 if (!NT_STATUS_IS_OK(status)) {
1711                         return false;
1712                 }
1713         }
1714
1715         /* if we get more than 1 IP back we have to assume it is a
1716            multi-homed PDC and not a mess up */
1717
1718         if ( count > 1 ) {
1719                 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
1720                 sort_service_list(ip_list, count);
1721         }
1722
1723         *pss = ip_list[0].ss;
1724         SAFE_FREE(ip_list);
1725         return true;
1726 }
1727
1728 /* Private enum type for lookups. */
1729
1730 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
1731
1732 /********************************************************
1733  Get the IP address list of the domain controllers for
1734  a domain.
1735 *********************************************************/
1736
1737 static NTSTATUS get_dc_list(const char *domain,
1738                         const char *sitename,
1739                         struct ip_service **ip_list,
1740                         int *count,
1741                         enum dc_lookup_type lookup_type,
1742                         bool *ordered)
1743 {
1744         char *resolve_order = NULL;
1745         char *saf_servername = NULL;
1746         char *pserver = NULL;
1747         const char *p;
1748         char *port_str = NULL;
1749         int port;
1750         char *name;
1751         int num_addresses = 0;
1752         int  local_count, i, j;
1753         struct ip_service *return_iplist = NULL;
1754         struct ip_service *auto_ip_list = NULL;
1755         bool done_auto_lookup = false;
1756         int auto_count = 0;
1757         NTSTATUS status;
1758         TALLOC_CTX *ctx = talloc_init("get_dc_list");
1759
1760         if (!ctx) {
1761                 return NT_STATUS_NO_MEMORY;
1762         }
1763
1764         *ordered = False;
1765
1766         /* if we are restricted to solely using DNS for looking
1767            up a domain controller, make sure that host lookups
1768            are enabled for the 'name resolve order'.  If host lookups
1769            are disabled and ads_only is True, then set the string to
1770            NULL. */
1771
1772         resolve_order = talloc_strdup(ctx, lp_name_resolve_order());
1773         if (!resolve_order) {
1774                 status = NT_STATUS_NO_MEMORY;
1775                 goto out;
1776         }
1777         strlower_m(resolve_order);
1778         if (lookup_type == DC_ADS_ONLY)  {
1779                 if (strstr( resolve_order, "host")) {
1780                         resolve_order = talloc_strdup(ctx, "ads");
1781
1782                         /* DNS SRV lookups used by the ads resolver
1783                            are already sorted by priority and weight */
1784                         *ordered = true;
1785                 } else {
1786                         resolve_order = talloc_strdup(ctx, "NULL");
1787                 }
1788         } else if (lookup_type == DC_KDC_ONLY) {
1789                 /* DNS SRV lookups used by the ads/kdc resolver
1790                    are already sorted by priority and weight */
1791                 *ordered = true;
1792                 resolve_order = talloc_strdup(ctx, "kdc");
1793         }
1794         if (!resolve_order) {
1795                 status = NT_STATUS_NO_MEMORY;
1796                 goto out;
1797         }
1798
1799         /* fetch the server we have affinity for.  Add the
1800            'password server' list to a search for our domain controllers */
1801
1802         saf_servername = saf_fetch( domain);
1803
1804         if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
1805                 pserver = talloc_asprintf(NULL, "%s, %s",
1806                         saf_servername ? saf_servername : "",
1807                         lp_passwordserver());
1808         } else {
1809                 pserver = talloc_asprintf(NULL, "%s, *",
1810                         saf_servername ? saf_servername : "");
1811         }
1812
1813         SAFE_FREE(saf_servername);
1814         if (!pserver) {
1815                 status = NT_STATUS_NO_MEMORY;
1816                 goto out;
1817         }
1818
1819         /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
1820
1821         if (!*pserver ) {
1822                 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
1823                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
1824                                              count, resolve_order);
1825                 goto out;
1826         }
1827
1828         DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
1829
1830         /*
1831          * if '*' appears in the "password server" list then add
1832          * an auto lookup to the list of manually configured
1833          * DC's.  If any DC is listed by name, then the list should be
1834          * considered to be ordered
1835          */
1836
1837         p = pserver;
1838         while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
1839                 if (strequal(name, "*")) {
1840                         status = internal_resolve_name(domain, 0x1C, sitename,
1841                                                        &auto_ip_list,
1842                                                        &auto_count,
1843                                                        resolve_order);
1844                         if (NT_STATUS_IS_OK(status)) {
1845                                 num_addresses += auto_count;
1846                         }
1847                         done_auto_lookup = true;
1848                         DEBUG(8,("Adding %d DC's from auto lookup\n",
1849                                                 auto_count));
1850                 } else  {
1851                         num_addresses++;
1852                 }
1853         }
1854
1855         /* if we have no addresses and haven't done the auto lookup, then
1856            just return the list of DC's.  Or maybe we just failed. */
1857
1858         if ((num_addresses == 0)) {
1859                 if (done_auto_lookup) {
1860                         DEBUG(4,("get_dc_list: no servers found\n"));
1861                         status = NT_STATUS_NO_LOGON_SERVERS;
1862                         goto out;
1863                 }
1864                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
1865                                              count, resolve_order);
1866                 goto out;
1867         }
1868
1869         if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
1870                                         num_addresses)) == NULL) {
1871                 DEBUG(3,("get_dc_list: malloc fail !\n"));
1872                 status = NT_STATUS_NO_MEMORY;
1873                 goto out;
1874         }
1875
1876         p = pserver;
1877         local_count = 0;
1878
1879         /* fill in the return list now with real IP's */
1880
1881         while ((local_count<num_addresses) &&
1882                         next_token_talloc(ctx, &p, &name, LIST_SEP)) {
1883                 struct sockaddr_storage name_ss;
1884
1885                 /* copy any addersses from the auto lookup */
1886
1887                 if (strequal(name, "*")) {
1888                         for (j=0; j<auto_count; j++) {
1889                                 char addr[INET6_ADDRSTRLEN];
1890                                 print_sockaddr(addr,
1891                                                 sizeof(addr),
1892                                                 &auto_ip_list[j].ss);
1893                                 /* Check for and don't copy any
1894                                  * known bad DC IP's. */
1895                                 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
1896                                                 domain,
1897                                                 addr))) {
1898                                         DEBUG(5,("get_dc_list: "
1899                                                 "negative entry %s removed "
1900                                                 "from DC list\n",
1901                                                 addr));
1902                                         continue;
1903                                 }
1904                                 return_iplist[local_count].ss =
1905                                         auto_ip_list[j].ss;
1906                                 return_iplist[local_count].port =
1907                                         auto_ip_list[j].port;
1908                                 local_count++;
1909                         }
1910                         continue;
1911                 }
1912
1913                 /* added support for address:port syntax for ads
1914                  * (not that I think anyone will ever run the LDAP
1915                  * server in an AD domain on something other than
1916                  * port 389 */
1917
1918                 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
1919                 if ((port_str=strchr(name, ':')) != NULL) {
1920                         *port_str = '\0';
1921                         port_str++;
1922                         port = atoi(port_str);
1923                 }
1924
1925                 /* explicit lookup; resolve_name() will
1926                  * handle names & IP addresses */
1927                 if (resolve_name( name, &name_ss, 0x20 )) {
1928                         char addr[INET6_ADDRSTRLEN];
1929                         print_sockaddr(addr,
1930                                         sizeof(addr),
1931                                         &name_ss);
1932
1933                         /* Check for and don't copy any known bad DC IP's. */
1934                         if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
1935                                                         addr)) ) {
1936                                 DEBUG(5,("get_dc_list: negative entry %s "
1937                                         "removed from DC list\n",
1938                                         name ));
1939                                 continue;
1940                         }
1941
1942                         return_iplist[local_count].ss = name_ss;
1943                         return_iplist[local_count].port = port;
1944                         local_count++;
1945                         *ordered = true;
1946                 }
1947         }
1948
1949         /* need to remove duplicates in the list if we have any
1950            explicit password servers */
1951
1952         if (local_count) {
1953                 local_count = remove_duplicate_addrs2(return_iplist,
1954                                 local_count );
1955         }
1956
1957         if ( DEBUGLEVEL >= 4 ) {
1958                 DEBUG(4,("get_dc_list: returning %d ip addresses "
1959                                 "in an %sordered list\n",
1960                                 local_count,
1961                                 *ordered ? "":"un"));
1962                 DEBUG(4,("get_dc_list: "));
1963                 for ( i=0; i<local_count; i++ ) {
1964                         char addr[INET6_ADDRSTRLEN];
1965                         print_sockaddr(addr,
1966                                         sizeof(addr),
1967                                         &return_iplist[i].ss);
1968                         DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
1969                 }
1970                 DEBUGADD(4,("\n"));
1971         }
1972
1973         *ip_list = return_iplist;
1974         *count = local_count;
1975
1976         status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
1977
1978   out:
1979
1980         SAFE_FREE(auto_ip_list);
1981         TALLOC_FREE(ctx);
1982         return status;
1983 }
1984
1985 /*********************************************************************
1986  Small wrapper function to get the DC list and sort it if neccessary.
1987 *********************************************************************/
1988
1989 NTSTATUS get_sorted_dc_list( const char *domain,
1990                         const char *sitename,
1991                         struct ip_service **ip_list,
1992                         int *count,
1993                         bool ads_only )
1994 {
1995         bool ordered;
1996         NTSTATUS status;
1997         enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
1998
1999         DEBUG(8,("get_sorted_dc_list: attempting lookup "
2000                 "for name %s (sitename %s) using [%s]\n",
2001                 domain,
2002                 sitename ? sitename : "NULL",
2003                 (ads_only ? "ads" : lp_name_resolve_order())));
2004
2005         if (ads_only) {
2006                 lookup_type = DC_ADS_ONLY;
2007         }
2008
2009         status = get_dc_list(domain, sitename, ip_list,
2010                         count, lookup_type, &ordered);
2011         if (!NT_STATUS_IS_OK(status)) {
2012                 return status;
2013         }
2014
2015         /* only sort if we don't already have an ordered list */
2016         if (!ordered) {
2017                 sort_service_list(*ip_list, *count);
2018         }
2019
2020         return NT_STATUS_OK;
2021 }
2022
2023 /*********************************************************************
2024  Get the KDC list - re-use all the logic in get_dc_list.
2025 *********************************************************************/
2026
2027 NTSTATUS get_kdc_list( const char *realm,
2028                         const char *sitename,
2029                         struct ip_service **ip_list,
2030                         int *count)
2031 {
2032         bool ordered;
2033         NTSTATUS status;
2034
2035         *count = 0;
2036         *ip_list = NULL;
2037
2038         status = get_dc_list(realm, sitename, ip_list,
2039                         count, DC_KDC_ONLY, &ordered);
2040
2041         if (!NT_STATUS_IS_OK(status)) {
2042                 return status;
2043         }
2044
2045         /* only sort if we don't already have an ordered list */
2046         if ( !ordered ) {
2047                 sort_service_list(*ip_list, *count);
2048         }
2049
2050         return NT_STATUS_OK;
2051 }