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