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