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