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