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