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