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