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