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