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