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