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