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