s3-libsmb Use 'resolv:hosts file' as a DNS emulation when specified.
[kai/samba-autobuild/.git] / source3 / libsmb / namequery.c
1 /*
2    Unix SMB/CIFS implementation.
3    name query routines
4    Copyright (C) Andrew Tridgell 1994-1998
5    Copyright (C) Jeremy Allison 2007.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "libads/sitename_cache.h"
23 #include "libads/dns.h"
24 #include "../libcli/netlogon/netlogon.h"
25 #include "lib/async_req/async_sock.h"
26 #include "libsmb/nmblib.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  Do a NBT node status query on an open socket and return an array of
662  structures holding the returned names or NULL if the query failed.
663 **************************************************************************/
664
665 struct node_status_query_state {
666         struct sockaddr_storage my_addr;
667         struct sockaddr_storage addr;
668         uint8_t buf[1024];
669         ssize_t buflen;
670         struct packet_struct *packet;
671 };
672
673 static int node_status_query_state_destructor(
674         struct node_status_query_state *s);
675 static bool node_status_query_validator(struct packet_struct *p,
676                                         void *private_data);
677 static void node_status_query_done(struct tevent_req *subreq);
678
679 struct tevent_req *node_status_query_send(TALLOC_CTX *mem_ctx,
680                                           struct tevent_context *ev,
681                                           struct nmb_name *name,
682                                           const struct sockaddr_storage *addr)
683 {
684         struct tevent_req *req, *subreq;
685         struct node_status_query_state *state;
686         struct packet_struct p;
687         struct nmb_packet *nmb = &p.packet.nmb;
688         struct sockaddr_in *in_addr;
689
690         req = tevent_req_create(mem_ctx, &state,
691                                 struct node_status_query_state);
692         if (req == NULL) {
693                 return NULL;
694         }
695         talloc_set_destructor(state, node_status_query_state_destructor);
696
697         if (addr->ss_family != AF_INET) {
698                 /* Can't do node status to IPv6 */
699                 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
700                 return tevent_req_post(req, ev);
701         }
702
703         state->addr = *addr;
704         in_addr = (struct sockaddr_in *)(void *)&state->addr;
705         in_addr->sin_port = htons(NMB_PORT);
706
707         if (!interpret_string_addr(&state->my_addr, lp_socket_address(),
708                                    AI_NUMERICHOST|AI_PASSIVE)) {
709                 zero_sockaddr(&state->my_addr);
710         }
711
712         ZERO_STRUCT(p);
713         nmb->header.name_trn_id = generate_trn_id();
714         nmb->header.opcode = 0;
715         nmb->header.response = false;
716         nmb->header.nm_flags.bcast = false;
717         nmb->header.nm_flags.recursion_available = false;
718         nmb->header.nm_flags.recursion_desired = false;
719         nmb->header.nm_flags.trunc = false;
720         nmb->header.nm_flags.authoritative = false;
721         nmb->header.rcode = 0;
722         nmb->header.qdcount = 1;
723         nmb->header.ancount = 0;
724         nmb->header.nscount = 0;
725         nmb->header.arcount = 0;
726         nmb->question.question_name = *name;
727         nmb->question.question_type = 0x21;
728         nmb->question.question_class = 0x1;
729
730         state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
731                                      &p);
732         if (state->buflen == 0) {
733                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
734                 DEBUG(10, ("build_packet failed\n"));
735                 return tevent_req_post(req, ev);
736         }
737
738         subreq = nb_trans_send(state, ev, &state->my_addr, &state->addr, false,
739                                state->buf, state->buflen,
740                                NMB_PACKET, nmb->header.name_trn_id,
741                                node_status_query_validator, NULL);
742         if (tevent_req_nomem(subreq, req)) {
743                 DEBUG(10, ("nb_trans_send failed\n"));
744                 return tevent_req_post(req, ev);
745         }
746         if (!tevent_req_set_endtime(req, ev, timeval_current_ofs(10, 0))) {
747                 return tevent_req_post(req, ev);
748         }
749         tevent_req_set_callback(subreq, node_status_query_done, req);
750         return req;
751 }
752
753 static bool node_status_query_validator(struct packet_struct *p,
754                                         void *private_data)
755 {
756         struct nmb_packet *nmb = &p->packet.nmb;
757         debug_nmb_packet(p);
758
759         if (nmb->header.opcode != 0 ||
760             nmb->header.nm_flags.bcast ||
761             nmb->header.rcode ||
762             !nmb->header.ancount ||
763             nmb->answers->rr_type != 0x21) {
764                 /*
765                  * XXXX what do we do with this? could be a redirect,
766                  * but we'll discard it for the moment
767                  */
768                 return false;
769         }
770         return true;
771 }
772
773 static int node_status_query_state_destructor(
774         struct node_status_query_state *s)
775 {
776         if (s->packet != NULL) {
777                 free_packet(s->packet);
778                 s->packet = NULL;
779         }
780         return 0;
781 }
782
783 static void node_status_query_done(struct tevent_req *subreq)
784 {
785         struct tevent_req *req = tevent_req_callback_data(
786                 subreq, struct tevent_req);
787         struct node_status_query_state *state = tevent_req_data(
788                 req, struct node_status_query_state);
789         NTSTATUS status;
790
791         status = nb_trans_recv(subreq, &state->packet);
792         TALLOC_FREE(subreq);
793         if (tevent_req_nterror(req, status)) {
794                 return;
795         }
796         tevent_req_done(req);
797 }
798
799 NTSTATUS node_status_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
800                                 struct node_status **pnode_status,
801                                 int *pnum_names,
802                                 struct node_status_extra *extra)
803 {
804         struct node_status_query_state *state = tevent_req_data(
805                 req, struct node_status_query_state);
806         struct node_status *node_status;
807         int num_names;
808         NTSTATUS status;
809
810         if (tevent_req_is_nterror(req, &status)) {
811                 return status;
812         }
813         node_status = parse_node_status(
814                 mem_ctx, &state->packet->packet.nmb.answers->rdata[0],
815                 &num_names, extra);
816         if (node_status == NULL) {
817                 return NT_STATUS_NO_MEMORY;
818         }
819         *pnode_status = node_status;
820         *pnum_names = num_names;
821         return NT_STATUS_OK;
822 }
823
824 NTSTATUS node_status_query(TALLOC_CTX *mem_ctx, struct nmb_name *name,
825                            const struct sockaddr_storage *addr,
826                            struct node_status **pnode_status,
827                            int *pnum_names,
828                            struct node_status_extra *extra)
829 {
830         TALLOC_CTX *frame = talloc_stackframe();
831         struct tevent_context *ev;
832         struct tevent_req *req;
833         NTSTATUS status = NT_STATUS_NO_MEMORY;
834
835         ev = tevent_context_init(frame);
836         if (ev == NULL) {
837                 goto fail;
838         }
839         req = node_status_query_send(ev, ev, name, addr);
840         if (req == NULL) {
841                 goto fail;
842         }
843         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
844                 goto fail;
845         }
846         status = node_status_query_recv(req, mem_ctx, pnode_status,
847                                         pnum_names, extra);
848  fail:
849         TALLOC_FREE(frame);
850         return status;
851 }
852
853 /****************************************************************************
854  Find the first type XX name in a node status reply - used for finding
855  a servers name given its IP. Return the matched name in *name.
856 **************************************************************************/
857
858 bool name_status_find(const char *q_name,
859                         int q_type,
860                         int type,
861                         const struct sockaddr_storage *to_ss,
862                         fstring name)
863 {
864         char addr[INET6_ADDRSTRLEN];
865         struct sockaddr_storage ss;
866         struct node_status *addrs = NULL;
867         struct nmb_name nname;
868         int count, i;
869         bool result = false;
870         NTSTATUS status;
871
872         if (lp_disable_netbios()) {
873                 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n",
874                                         q_name, q_type));
875                 return False;
876         }
877
878         print_sockaddr(addr, sizeof(addr), to_ss);
879
880         DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
881                    q_type, addr));
882
883         /* Check the cache first. */
884
885         if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
886                 return True;
887         }
888
889         if (to_ss->ss_family != AF_INET) {
890                 /* Can't do node status to IPv6 */
891                 return false;
892         }
893
894         if (!interpret_string_addr(&ss, lp_socket_address(),
895                                 AI_NUMERICHOST|AI_PASSIVE)) {
896                 zero_sockaddr(&ss);
897         }
898
899         /* W2K PDC's seem not to respond to '*'#0. JRA */
900         make_nmb_name(&nname, q_name, q_type);
901         status = node_status_query(talloc_tos(), &nname, to_ss,
902                                    &addrs, &count, NULL);
903         if (!NT_STATUS_IS_OK(status)) {
904                 goto done;
905         }
906
907         for (i=0;i<count;i++) {
908                 /* Find first one of the requested type that's not a GROUP. */
909                 if (addrs[i].type == type && ! (addrs[i].flags & 0x80))
910                         break;
911         }
912         if (i == count)
913                 goto done;
914
915         pull_ascii_nstring(name, sizeof(fstring), addrs[i].name);
916
917         /* Store the result in the cache. */
918         /* but don't store an entry for 0x1c names here.  Here we have
919            a single host and DOMAIN<0x1c> names should be a list of hosts */
920
921         if ( q_type != 0x1c ) {
922                 namecache_status_store(q_name, q_type, type, to_ss, name);
923         }
924
925         result = true;
926
927  done:
928         TALLOC_FREE(addrs);
929
930         DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
931
932         if (result)
933                 DEBUGADD(10, (", name %s ip address is %s", name, addr));
934
935         DEBUG(10, ("\n"));
936
937         return result;
938 }
939
940 /*
941   comparison function used by sort_addr_list
942 */
943
944 static int addr_compare(const struct sockaddr_storage *ss1,
945                         const struct sockaddr_storage *ss2)
946 {
947         int max_bits1=0, max_bits2=0;
948         int num_interfaces = iface_count();
949         int i;
950
951         /* Sort IPv4 addresses first. */
952         if (ss1->ss_family != ss2->ss_family) {
953                 if (ss2->ss_family == AF_INET) {
954                         return 1;
955                 } else {
956                         return -1;
957                 }
958         }
959
960         /* Here we know both addresses are of the same
961          * family. */
962
963         for (i=0;i<num_interfaces;i++) {
964                 const struct sockaddr_storage *pss = iface_n_bcast(i);
965                 unsigned char *p_ss1 = NULL;
966                 unsigned char *p_ss2 = NULL;
967                 unsigned char *p_if = NULL;
968                 size_t len = 0;
969                 int bits1, bits2;
970
971                 if (pss->ss_family != ss1->ss_family) {
972                         /* Ignore interfaces of the wrong type. */
973                         continue;
974                 }
975                 if (pss->ss_family == AF_INET) {
976                         p_if = (unsigned char *)
977                                 &((const struct sockaddr_in *)pss)->sin_addr;
978                         p_ss1 = (unsigned char *)
979                                 &((const struct sockaddr_in *)ss1)->sin_addr;
980                         p_ss2 = (unsigned char *)
981                                 &((const struct sockaddr_in *)ss2)->sin_addr;
982                         len = 4;
983                 }
984 #if defined(HAVE_IPV6)
985                 if (pss->ss_family == AF_INET6) {
986                         p_if = (unsigned char *)
987                                 &((const struct sockaddr_in6 *)pss)->sin6_addr;
988                         p_ss1 = (unsigned char *)
989                                 &((const struct sockaddr_in6 *)ss1)->sin6_addr;
990                         p_ss2 = (unsigned char *)
991                                 &((const struct sockaddr_in6 *)ss2)->sin6_addr;
992                         len = 16;
993                 }
994 #endif
995                 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
996                         continue;
997                 }
998                 bits1 = matching_len_bits(p_ss1, p_if, len);
999                 bits2 = matching_len_bits(p_ss2, p_if, len);
1000                 max_bits1 = MAX(bits1, max_bits1);
1001                 max_bits2 = MAX(bits2, max_bits2);
1002         }
1003
1004         /* Bias towards directly reachable IPs */
1005         if (iface_local((struct sockaddr *)ss1)) {
1006                 if (ss1->ss_family == AF_INET) {
1007                         max_bits1 += 32;
1008                 } else {
1009                         max_bits1 += 128;
1010                 }
1011         }
1012         if (iface_local((struct sockaddr *)ss2)) {
1013                 if (ss2->ss_family == AF_INET) {
1014                         max_bits2 += 32;
1015                 } else {
1016                         max_bits2 += 128;
1017                 }
1018         }
1019         return max_bits2 - max_bits1;
1020 }
1021
1022 /*******************************************************************
1023  compare 2 ldap IPs by nearness to our interfaces - used in qsort
1024 *******************************************************************/
1025
1026 int ip_service_compare(struct ip_service *ss1, struct ip_service *ss2)
1027 {
1028         int result;
1029
1030         if ((result = addr_compare(&ss1->ss, &ss2->ss)) != 0) {
1031                 return result;
1032         }
1033
1034         if (ss1->port > ss2->port) {
1035                 return 1;
1036         }
1037
1038         if (ss1->port < ss2->port) {
1039                 return -1;
1040         }
1041
1042         return 0;
1043 }
1044
1045 /*
1046   sort an IP list so that names that are close to one of our interfaces
1047   are at the top. This prevents the problem where a WINS server returns an IP
1048   that is not reachable from our subnet as the first match
1049 */
1050
1051 static void sort_addr_list(struct sockaddr_storage *sslist, int count)
1052 {
1053         if (count <= 1) {
1054                 return;
1055         }
1056
1057         TYPESAFE_QSORT(sslist, count, addr_compare);
1058 }
1059
1060 static void sort_service_list(struct ip_service *servlist, int count)
1061 {
1062         if (count <= 1) {
1063                 return;
1064         }
1065
1066         TYPESAFE_QSORT(servlist, count, ip_service_compare);
1067 }
1068
1069 /**********************************************************************
1070  Remove any duplicate address/port pairs in the list
1071  *********************************************************************/
1072
1073 static int remove_duplicate_addrs2(struct ip_service *iplist, int count )
1074 {
1075         int i, j;
1076
1077         DEBUG(10,("remove_duplicate_addrs2: "
1078                         "looking for duplicate address/port pairs\n"));
1079
1080         /* one loop to remove duplicates */
1081         for ( i=0; i<count; i++ ) {
1082                 if ( is_zero_addr(&iplist[i].ss)) {
1083                         continue;
1084                 }
1085
1086                 for ( j=i+1; j<count; j++ ) {
1087                         if (sockaddr_equal((struct sockaddr *)&iplist[i].ss, (struct sockaddr *)&iplist[j].ss) &&
1088                                         iplist[i].port == iplist[j].port) {
1089                                 zero_sockaddr(&iplist[j].ss);
1090                         }
1091                 }
1092         }
1093
1094         /* one loop to clean up any holes we left */
1095         /* first ip should never be a zero_ip() */
1096         for (i = 0; i<count; ) {
1097                 if (is_zero_addr(&iplist[i].ss) ) {
1098                         if (i != count-1) {
1099                                 memmove(&iplist[i], &iplist[i+1],
1100                                         (count - i - 1)*sizeof(iplist[i]));
1101                         }
1102                         count--;
1103                         continue;
1104                 }
1105                 i++;
1106         }
1107
1108         return count;
1109 }
1110
1111 static bool prioritize_ipv4_list(struct ip_service *iplist, int count)
1112 {
1113         TALLOC_CTX *frame = talloc_stackframe();
1114         struct ip_service *iplist_new = TALLOC_ARRAY(frame, struct ip_service, count);
1115         int i, j;
1116
1117         if (iplist_new == NULL) {
1118                 TALLOC_FREE(frame);
1119                 return false;
1120         }
1121
1122         j = 0;
1123
1124         /* Copy IPv4 first. */
1125         for (i = 0; i < count; i++) {
1126                 if (iplist[i].ss.ss_family == AF_INET) {
1127                         iplist_new[j++] = iplist[i];
1128                 }
1129         }
1130
1131         /* Copy IPv6. */
1132         for (i = 0; i < count; i++) {
1133                 if (iplist[i].ss.ss_family != AF_INET) {
1134                         iplist_new[j++] = iplist[i];
1135                 }
1136         }
1137
1138         memcpy(iplist, iplist_new, sizeof(struct ip_service)*count);
1139         TALLOC_FREE(frame);
1140         return true;
1141 }
1142
1143 /****************************************************************************
1144  Do a netbios name query to find someones IP.
1145  Returns an array of IP addresses or NULL if none.
1146  *count will be set to the number of addresses returned.
1147  *timed_out is set if we failed by timing out
1148 ****************************************************************************/
1149
1150 struct name_query_state {
1151         struct sockaddr_storage my_addr;
1152         struct sockaddr_storage addr;
1153         bool bcast;
1154
1155
1156         uint8_t buf[1024];
1157         ssize_t buflen;
1158
1159         NTSTATUS validate_error;
1160         uint8_t flags;
1161
1162         struct sockaddr_storage *addrs;
1163         int num_addrs;
1164 };
1165
1166 static bool name_query_validator(struct packet_struct *p, void *private_data);
1167 static void name_query_done(struct tevent_req *subreq);
1168
1169 struct tevent_req *name_query_send(TALLOC_CTX *mem_ctx,
1170                                    struct tevent_context *ev,
1171                                    const char *name, int name_type,
1172                                    bool bcast, bool recurse,
1173                                    const struct sockaddr_storage *addr)
1174 {
1175         struct tevent_req *req, *subreq;
1176         struct name_query_state *state;
1177         struct packet_struct p;
1178         struct nmb_packet *nmb = &p.packet.nmb;
1179         struct sockaddr_in *in_addr;
1180
1181         req = tevent_req_create(mem_ctx, &state, struct name_query_state);
1182         if (req == NULL) {
1183                 return NULL;
1184         }
1185         state->bcast = bcast;
1186
1187         if (addr->ss_family != AF_INET) {
1188                 /* Can't do node status to IPv6 */
1189                 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
1190                 return tevent_req_post(req, ev);
1191         }
1192
1193         if (lp_disable_netbios()) {
1194                 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
1195                                         name, name_type));
1196                 tevent_req_nterror(req, NT_STATUS_NOT_SUPPORTED);
1197                 return tevent_req_post(req, ev);
1198         }
1199
1200         state->addr = *addr;
1201         in_addr = (struct sockaddr_in *)(void *)&state->addr;
1202         in_addr->sin_port = htons(NMB_PORT);
1203
1204         if (!interpret_string_addr(&state->my_addr, lp_socket_address(),
1205                                    AI_NUMERICHOST|AI_PASSIVE)) {
1206                 zero_sockaddr(&state->my_addr);
1207         }
1208
1209         ZERO_STRUCT(p);
1210         nmb->header.name_trn_id = generate_trn_id();
1211         nmb->header.opcode = 0;
1212         nmb->header.response = false;
1213         nmb->header.nm_flags.bcast = bcast;
1214         nmb->header.nm_flags.recursion_available = false;
1215         nmb->header.nm_flags.recursion_desired = recurse;
1216         nmb->header.nm_flags.trunc = false;
1217         nmb->header.nm_flags.authoritative = false;
1218         nmb->header.rcode = 0;
1219         nmb->header.qdcount = 1;
1220         nmb->header.ancount = 0;
1221         nmb->header.nscount = 0;
1222         nmb->header.arcount = 0;
1223
1224         make_nmb_name(&nmb->question.question_name,name,name_type);
1225
1226         nmb->question.question_type = 0x20;
1227         nmb->question.question_class = 0x1;
1228
1229         state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
1230                                      &p);
1231         if (state->buflen == 0) {
1232                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1233                 DEBUG(10, ("build_packet failed\n"));
1234                 return tevent_req_post(req, ev);
1235         }
1236
1237         subreq = nb_trans_send(state, ev, &state->my_addr, &state->addr, bcast,
1238                                state->buf, state->buflen,
1239                                NMB_PACKET, nmb->header.name_trn_id,
1240                                name_query_validator, state);
1241         if (tevent_req_nomem(subreq, req)) {
1242                 DEBUG(10, ("nb_trans_send failed\n"));
1243                 return tevent_req_post(req, ev);
1244         }
1245         tevent_req_set_callback(subreq, name_query_done, req);
1246         return req;
1247 }
1248
1249 static bool name_query_validator(struct packet_struct *p, void *private_data)
1250 {
1251         struct name_query_state *state = talloc_get_type_abort(
1252                 private_data, struct name_query_state);
1253         struct nmb_packet *nmb = &p->packet.nmb;
1254         struct sockaddr_storage *tmp_addrs;
1255         int i;
1256
1257         debug_nmb_packet(p);
1258
1259         /*
1260          * If we get a Negative Name Query Response from a WINS
1261          * server, we should report it and give up.
1262          */
1263         if( 0 == nmb->header.opcode     /* A query response   */
1264             && !state->bcast            /* from a WINS server */
1265             && nmb->header.rcode        /* Error returned     */
1266                 ) {
1267
1268                 if( DEBUGLVL( 3 ) ) {
1269                         /* Only executed if DEBUGLEVEL >= 3 */
1270                         dbgtext( "Negative name query "
1271                                  "response, rcode 0x%02x: ",
1272                                  nmb->header.rcode );
1273                         switch( nmb->header.rcode ) {
1274                         case 0x01:
1275                                 dbgtext("Request was invalidly formatted.\n");
1276                                 break;
1277                         case 0x02:
1278                                 dbgtext("Problem with NBNS, cannot process "
1279                                         "name.\n");
1280                                 break;
1281                         case 0x03:
1282                                 dbgtext("The name requested does not "
1283                                         "exist.\n");
1284                                 break;
1285                         case 0x04:
1286                                 dbgtext("Unsupported request error.\n");
1287                                 break;
1288                         case 0x05:
1289                                 dbgtext("Query refused error.\n");
1290                                 break;
1291                         default:
1292                                 dbgtext("Unrecognized error code.\n" );
1293                                 break;
1294                         }
1295                 }
1296
1297                 /*
1298                  * We accept this packet as valid, but tell the upper
1299                  * layers that it's a negative response.
1300                  */
1301                 state->validate_error = NT_STATUS_NOT_FOUND;
1302                 return true;
1303         }
1304
1305         if (nmb->header.opcode != 0 ||
1306             nmb->header.nm_flags.bcast ||
1307             nmb->header.rcode ||
1308             !nmb->header.ancount) {
1309                 /*
1310                  * XXXX what do we do with this? Could be a redirect,
1311                  * but we'll discard it for the moment.
1312                  */
1313                 return false;
1314         }
1315
1316         tmp_addrs = TALLOC_REALLOC_ARRAY(
1317                 state, state->addrs, struct sockaddr_storage,
1318                 state->num_addrs + nmb->answers->rdlength/6);
1319         if (tmp_addrs == NULL) {
1320                 state->validate_error = NT_STATUS_NO_MEMORY;
1321                 return true;
1322         }
1323         state->addrs = tmp_addrs;
1324
1325         DEBUG(2,("Got a positive name query response "
1326                  "from %s ( ", inet_ntoa(p->ip)));
1327
1328         for (i=0; i<nmb->answers->rdlength/6; i++) {
1329                 struct in_addr ip;
1330                 putip((char *)&ip,&nmb->answers->rdata[2+i*6]);
1331                 in_addr_to_sockaddr_storage(
1332                         &state->addrs[state->num_addrs], ip);
1333                 DEBUGADD(2,("%s ",inet_ntoa(ip)));
1334                 state->num_addrs += 1;
1335         }
1336         DEBUGADD(2,(")\n"));
1337
1338         /* We add the flags back ... */
1339         if (nmb->header.response)
1340                 state->flags |= NM_FLAGS_RS;
1341         if (nmb->header.nm_flags.authoritative)
1342                 state->flags |= NM_FLAGS_AA;
1343         if (nmb->header.nm_flags.trunc)
1344                 state->flags |= NM_FLAGS_TC;
1345         if (nmb->header.nm_flags.recursion_desired)
1346                 state->flags |= NM_FLAGS_RD;
1347         if (nmb->header.nm_flags.recursion_available)
1348                 state->flags |= NM_FLAGS_RA;
1349         if (nmb->header.nm_flags.bcast)
1350                 state->flags |= NM_FLAGS_B;
1351
1352         if (state->bcast) {
1353                 /*
1354                  * We have to collect all entries coming in from
1355                  * broadcast queries
1356                  */
1357                 return false;
1358         }
1359         /*
1360          * WINS responses are accepted when they are received
1361          */
1362         return true;
1363 }
1364
1365 static void name_query_done(struct tevent_req *subreq)
1366 {
1367         struct tevent_req *req = tevent_req_callback_data(
1368                 subreq, struct tevent_req);
1369         struct name_query_state *state = tevent_req_data(
1370                 req, struct name_query_state);
1371         NTSTATUS status;
1372         struct packet_struct *p = NULL;
1373
1374         status = nb_trans_recv(subreq, &p);
1375         TALLOC_FREE(subreq);
1376         if (tevent_req_nterror(req, status)) {
1377                 return;
1378         }
1379         if (!NT_STATUS_IS_OK(state->validate_error)) {
1380                 tevent_req_nterror(req, state->validate_error);
1381                 return;
1382         }
1383         if (p != NULL) {
1384                 /*
1385                  * Free the packet here, we've collected the response in the
1386                  * validator
1387                  */
1388                 free_packet(p);
1389         }
1390         tevent_req_done(req);
1391 }
1392
1393 NTSTATUS name_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1394                          struct sockaddr_storage **addrs, int *num_addrs,
1395                          uint8_t *flags)
1396 {
1397         struct name_query_state *state = tevent_req_data(
1398                 req, struct name_query_state);
1399         NTSTATUS status;
1400
1401         if (tevent_req_is_nterror(req, &status)
1402             && !NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
1403                 return status;
1404         }
1405         if (state->num_addrs == 0) {
1406                 return NT_STATUS_NOT_FOUND;
1407         }
1408         *addrs = talloc_move(mem_ctx, &state->addrs);
1409         sort_addr_list(*addrs, state->num_addrs);
1410         *num_addrs = state->num_addrs;
1411         if (flags != NULL) {
1412                 *flags = state->flags;
1413         }
1414         return NT_STATUS_OK;
1415 }
1416
1417 NTSTATUS name_query(const char *name, int name_type,
1418                     bool bcast, bool recurse,
1419                     const struct sockaddr_storage *to_ss,
1420                     TALLOC_CTX *mem_ctx,
1421                     struct sockaddr_storage **addrs,
1422                     int *num_addrs, uint8_t *flags)
1423 {
1424         TALLOC_CTX *frame = talloc_stackframe();
1425         struct tevent_context *ev;
1426         struct tevent_req *req;
1427         struct timeval timeout;
1428         NTSTATUS status = NT_STATUS_NO_MEMORY;
1429
1430         ev = tevent_context_init(frame);
1431         if (ev == NULL) {
1432                 goto fail;
1433         }
1434         req = name_query_send(ev, ev, name, name_type, bcast, recurse, to_ss);
1435         if (req == NULL) {
1436                 goto fail;
1437         }
1438         if (bcast) {
1439                 timeout = timeval_current_ofs(0, 250000);
1440         } else {
1441                 timeout = timeval_current_ofs(2, 0);
1442         }
1443         if (!tevent_req_set_endtime(req, ev, timeout)) {
1444                 goto fail;
1445         }
1446         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
1447                 goto fail;
1448         }
1449         status = name_query_recv(req, mem_ctx, addrs, num_addrs, flags);
1450  fail:
1451         TALLOC_FREE(frame);
1452         return status;
1453 }
1454
1455 /********************************************************
1456  convert an array if struct sockaddr_storage to struct ip_service
1457  return false on failure.  Port is set to PORT_NONE;
1458 *********************************************************/
1459
1460 static bool convert_ss2service(struct ip_service **return_iplist,
1461                 const struct sockaddr_storage *ss_list,
1462                 int count)
1463 {
1464         int i;
1465
1466         if ( count==0 || !ss_list )
1467                 return False;
1468
1469         /* copy the ip address; port will be PORT_NONE */
1470         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) ==
1471                         NULL) {
1472                 DEBUG(0,("convert_ip2service: malloc failed "
1473                         "for %d enetries!\n", count ));
1474                 return False;
1475         }
1476
1477         for ( i=0; i<count; i++ ) {
1478                 (*return_iplist)[i].ss   = ss_list[i];
1479                 (*return_iplist)[i].port = PORT_NONE;
1480         }
1481
1482         return true;
1483 }
1484
1485 /********************************************************
1486  Resolve via "bcast" method.
1487 *********************************************************/
1488
1489 NTSTATUS name_resolve_bcast(const char *name,
1490                         int name_type,
1491                         struct ip_service **return_iplist,
1492                         int *return_count)
1493 {
1494         int i;
1495         int num_interfaces = iface_count();
1496         struct sockaddr_storage *ss_list;
1497         NTSTATUS status = NT_STATUS_NOT_FOUND;
1498
1499         if (lp_disable_netbios()) {
1500                 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n",
1501                                         name, name_type));
1502                 return NT_STATUS_INVALID_PARAMETER;
1503         }
1504
1505         *return_iplist = NULL;
1506         *return_count = 0;
1507
1508         /*
1509          * "bcast" means do a broadcast lookup on all the local interfaces.
1510          */
1511
1512         DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup "
1513                 "for name %s<0x%x>\n", name, name_type));
1514
1515         /*
1516          * Lookup the name on all the interfaces, return on
1517          * the first successful match.
1518          */
1519         for( i = num_interfaces-1; i >= 0; i--) {
1520                 const struct sockaddr_storage *pss = iface_n_bcast(i);
1521
1522                 /* Done this way to fix compiler error on IRIX 5.x */
1523                 if (!pss) {
1524                         continue;
1525                 }
1526                 status = name_query(name, name_type, true, true, pss,
1527                                     talloc_tos(), &ss_list, return_count,
1528                                     NULL);
1529                 if (NT_STATUS_IS_OK(status)) {
1530                         goto success;
1531                 }
1532         }
1533
1534         /* failed - no response */
1535
1536         return status;
1537
1538 success:
1539
1540         if (!convert_ss2service(return_iplist, ss_list, *return_count) )
1541                 status = NT_STATUS_NO_MEMORY;
1542
1543         TALLOC_FREE(ss_list);
1544         return status;
1545 }
1546
1547 /********************************************************
1548  Resolve via "wins" method.
1549 *********************************************************/
1550
1551 NTSTATUS resolve_wins(const char *name,
1552                 int name_type,
1553                 struct ip_service **return_iplist,
1554                 int *return_count)
1555 {
1556         int t, i;
1557         char **wins_tags;
1558         struct sockaddr_storage src_ss, *ss_list = NULL;
1559         struct in_addr src_ip;
1560         NTSTATUS status;
1561
1562         if (lp_disable_netbios()) {
1563                 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n",
1564                                         name, name_type));
1565                 return NT_STATUS_INVALID_PARAMETER;
1566         }
1567
1568         *return_iplist = NULL;
1569         *return_count = 0;
1570
1571         DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n",
1572                                 name, name_type));
1573
1574         if (wins_srv_count() < 1) {
1575                 DEBUG(3,("resolve_wins: WINS server resolution selected "
1576                         "and no WINS servers listed.\n"));
1577                 return NT_STATUS_INVALID_PARAMETER;
1578         }
1579
1580         /* we try a lookup on each of the WINS tags in turn */
1581         wins_tags = wins_srv_tags();
1582
1583         if (!wins_tags) {
1584                 /* huh? no tags?? give up in disgust */
1585                 return NT_STATUS_INVALID_PARAMETER;
1586         }
1587
1588         /* the address we will be sending from */
1589         if (!interpret_string_addr(&src_ss, lp_socket_address(),
1590                                 AI_NUMERICHOST|AI_PASSIVE)) {
1591                 zero_sockaddr(&src_ss);
1592         }
1593
1594         if (src_ss.ss_family != AF_INET) {
1595                 char addr[INET6_ADDRSTRLEN];
1596                 print_sockaddr(addr, sizeof(addr), &src_ss);
1597                 DEBUG(3,("resolve_wins: cannot receive WINS replies "
1598                         "on IPv6 address %s\n",
1599                         addr));
1600                 wins_srv_tags_free(wins_tags);
1601                 return NT_STATUS_INVALID_PARAMETER;
1602         }
1603
1604         src_ip = ((struct sockaddr_in *)&src_ss)->sin_addr;
1605
1606         /* in the worst case we will try every wins server with every
1607            tag! */
1608         for (t=0; wins_tags && wins_tags[t]; t++) {
1609                 int srv_count = wins_srv_count_tag(wins_tags[t]);
1610                 for (i=0; i<srv_count; i++) {
1611                         struct sockaddr_storage wins_ss;
1612                         struct in_addr wins_ip;
1613
1614                         wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
1615
1616                         if (global_in_nmbd && ismyip_v4(wins_ip)) {
1617                                 /* yikes! we'll loop forever */
1618                                 continue;
1619                         }
1620
1621                         /* skip any that have been unresponsive lately */
1622                         if (wins_srv_is_dead(wins_ip, src_ip)) {
1623                                 continue;
1624                         }
1625
1626                         DEBUG(3,("resolve_wins: using WINS server %s "
1627                                 "and tag '%s'\n",
1628                                 inet_ntoa(wins_ip), wins_tags[t]));
1629
1630                         in_addr_to_sockaddr_storage(&wins_ss, wins_ip);
1631                         status = name_query(name,
1632                                                 name_type,
1633                                                 false,
1634                                                 true,
1635                                                 &wins_ss,
1636                                                 talloc_tos(),
1637                                                 &ss_list,
1638                                                 return_count,
1639                                                 NULL);
1640
1641                         /* exit loop if we got a list of addresses */
1642
1643                         if (NT_STATUS_IS_OK(status)) {
1644                                 goto success;
1645                         }
1646
1647                         if (NT_STATUS_EQUAL(status,
1648                                             NT_STATUS_IO_TIMEOUT)) {
1649                                 /* Timed out waiting for WINS server to
1650                                  * respond.
1651                                  * Mark it dead. */
1652                                 wins_srv_died(wins_ip, src_ip);
1653                         } else {
1654                                 /* The name definitely isn't in this
1655                                    group of WINS servers.
1656                                    goto the next group  */
1657                                 break;
1658                         }
1659                 }
1660         }
1661
1662         wins_srv_tags_free(wins_tags);
1663         return NT_STATUS_NO_LOGON_SERVERS;
1664
1665 success:
1666
1667         status = NT_STATUS_OK;
1668         if (!convert_ss2service(return_iplist, ss_list, *return_count))
1669                 status = NT_STATUS_INVALID_PARAMETER;
1670
1671         TALLOC_FREE(ss_list);
1672         wins_srv_tags_free(wins_tags);
1673
1674         return status;
1675 }
1676
1677 /********************************************************
1678  Resolve via "lmhosts" method.
1679 *********************************************************/
1680
1681 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
1682                                 struct ip_service **return_iplist,
1683                                 int *return_count)
1684 {
1685         /*
1686          * "lmhosts" means parse the local lmhosts file.
1687          */
1688         struct sockaddr_storage *ss_list;
1689         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1690         TALLOC_CTX *ctx = NULL;
1691
1692         *return_iplist = NULL;
1693         *return_count = 0;
1694
1695         DEBUG(3,("resolve_lmhosts: "
1696                 "Attempting lmhosts lookup for name %s<0x%x>\n",
1697                 name, name_type));
1698
1699         ctx = talloc_init("resolve_lmhosts");
1700         if (!ctx) {
1701                 return NT_STATUS_NO_MEMORY;
1702         }
1703
1704         status = resolve_lmhosts_file_as_sockaddr(get_dyn_LMHOSTSFILE(), 
1705                                                   name, name_type, 
1706                                                   ctx, 
1707                                                   &ss_list, 
1708                                                   return_count);
1709         if (NT_STATUS_IS_OK(status)) {
1710                 if (convert_ss2service(return_iplist, 
1711                                        ss_list,
1712                                        *return_count)) {
1713                         talloc_free(ctx);
1714                         return NT_STATUS_OK;
1715                 } else {
1716                         talloc_free(ctx);
1717                         return NT_STATUS_NO_MEMORY;
1718                 }
1719         }
1720         talloc_free(ctx);
1721         return status;
1722 }
1723
1724
1725 /********************************************************
1726  Resolve via "hosts" method.
1727 *********************************************************/
1728
1729 static NTSTATUS resolve_hosts(const char *name, int name_type,
1730                               struct ip_service **return_iplist,
1731                               int *return_count)
1732 {
1733         /*
1734          * "host" means do a localhost, or dns lookup.
1735          */
1736         struct addrinfo hints;
1737         struct addrinfo *ailist = NULL;
1738         struct addrinfo *res = NULL;
1739         int ret = -1;
1740         int i = 0;
1741         const char *dns_hosts_file;
1742
1743         if ( name_type != 0x20 && name_type != 0x0) {
1744                 DEBUG(5, ("resolve_hosts: not appropriate "
1745                         "for name type <0x%x>\n",
1746                         name_type));
1747                 return NT_STATUS_INVALID_PARAMETER;
1748         }
1749
1750         *return_iplist = NULL;
1751         *return_count = 0;
1752
1753         DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
1754                                 name, name_type));
1755
1756         ZERO_STRUCT(hints);
1757         /* By default make sure it supports TCP. */
1758         hints.ai_socktype = SOCK_STREAM;
1759         hints.ai_flags = AI_ADDRCONFIG;
1760
1761 #if !defined(HAVE_IPV6)
1762         /* Unless we have IPv6, we really only want IPv4 addresses back. */
1763         hints.ai_family = AF_INET;
1764 #endif
1765
1766         dns_hosts_file = lp_parm_const_string(-1, "resolv", "host file", NULL);
1767         if (dns_hosts_file) {
1768                 struct sockaddr_storage *ss_list;
1769                 NTSTATUS status;
1770                 TALLOC_CTX *ctx = talloc_stackframe();
1771                 if (!ctx) {
1772                         return NT_STATUS_NO_MEMORY;
1773                 }
1774
1775                 status = resolve_dns_hosts_file_as_sockaddr(dns_hosts_file, name, false,
1776                                                             ctx, &ss_list, return_count);
1777                 if (NT_STATUS_IS_OK(status)) {
1778                         if (convert_ss2service(return_iplist,
1779                                                ss_list,
1780                                                *return_count)) {
1781                                 talloc_free(ctx);
1782                                 return NT_STATUS_OK;
1783                         } else {
1784                                 talloc_free(ctx);
1785                                 return NT_STATUS_NO_MEMORY;
1786                         }
1787                 }
1788                 talloc_free(ctx);
1789                 return NT_STATUS_UNSUCCESSFUL;
1790         }
1791
1792         ret = getaddrinfo(name,
1793                         NULL,
1794                         &hints,
1795                         &ailist);
1796         if (ret) {
1797                 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1798                         name,
1799                         gai_strerror(ret) ));
1800         }
1801
1802         for (res = ailist; res; res = res->ai_next) {
1803                 struct sockaddr_storage ss;
1804
1805                 if (!res->ai_addr || res->ai_addrlen == 0) {
1806                         continue;
1807                 }
1808
1809                 ZERO_STRUCT(ss);
1810                 memcpy(&ss, res->ai_addr, res->ai_addrlen);
1811
1812                 *return_count += 1;
1813
1814                 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1815                                                 struct ip_service,
1816                                                 *return_count);
1817                 if (!*return_iplist) {
1818                         DEBUG(3,("resolve_hosts: malloc fail !\n"));
1819                         freeaddrinfo(ailist);
1820                         return NT_STATUS_NO_MEMORY;
1821                 }
1822                 (*return_iplist)[i].ss = ss;
1823                 (*return_iplist)[i].port = PORT_NONE;
1824                 i++;
1825         }
1826         if (ailist) {
1827                 freeaddrinfo(ailist);
1828         }
1829         if (*return_count) {
1830                 return NT_STATUS_OK;
1831         }
1832         return NT_STATUS_UNSUCCESSFUL;
1833 }
1834
1835 /********************************************************
1836  Resolve via "ADS" method.
1837 *********************************************************/
1838
1839 /* Special name type used to cause a _kerberos DNS lookup. */
1840 #define KDC_NAME_TYPE 0xDCDC
1841
1842 static NTSTATUS resolve_ads(const char *name,
1843                             int name_type,
1844                             const char *sitename,
1845                             struct ip_service **return_iplist,
1846                             int *return_count)
1847 {
1848         int                     i, j;
1849         NTSTATUS                status;
1850         TALLOC_CTX              *ctx;
1851         struct dns_rr_srv       *dcs = NULL;
1852         int                     numdcs = 0;
1853         int                     numaddrs = 0;
1854
1855         if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1856             (name_type != 0x1b)) {
1857                 return NT_STATUS_INVALID_PARAMETER;
1858         }
1859
1860         if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1861                 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1862                 return NT_STATUS_NO_MEMORY;
1863         }
1864
1865         /* The DNS code needs fixing to find IPv6 addresses... JRA. */
1866
1867         switch (name_type) {
1868                 case 0x1b:
1869                         DEBUG(5,("resolve_ads: Attempting to resolve "
1870                                  "PDC for %s using DNS\n", name));
1871                         status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1872                         break;
1873
1874                 case 0x1c:
1875                         DEBUG(5,("resolve_ads: Attempting to resolve "
1876                                  "DCs for %s using DNS\n", name));
1877                         status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1878                                                    &numdcs);
1879                         break;
1880                 case KDC_NAME_TYPE:
1881                         DEBUG(5,("resolve_ads: Attempting to resolve "
1882                                  "KDCs for %s using DNS\n", name));
1883                         status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1884                                                     &numdcs);
1885                         break;
1886                 default:
1887                         status = NT_STATUS_INVALID_PARAMETER;
1888                         break;
1889         }
1890
1891         if ( !NT_STATUS_IS_OK( status ) ) {
1892                 talloc_destroy(ctx);
1893                 return status;
1894         }
1895
1896         for (i=0;i<numdcs;i++) {
1897                 numaddrs += MAX(dcs[i].num_ips,1);
1898         }
1899
1900         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
1901                         NULL ) {
1902                 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
1903                                         numaddrs ));
1904                 talloc_destroy(ctx);
1905                 return NT_STATUS_NO_MEMORY;
1906         }
1907
1908         /* now unroll the list of IP addresses */
1909
1910         *return_count = 0;
1911         i = 0;
1912         j = 0;
1913         while ( i < numdcs && (*return_count<numaddrs) ) {
1914                 struct ip_service *r = &(*return_iplist)[*return_count];
1915
1916                 r->port = dcs[i].port;
1917
1918                 /* If we don't have an IP list for a name, lookup it up */
1919
1920                 if (!dcs[i].ss_s) {
1921                         interpret_string_addr(&r->ss, dcs[i].hostname, 0);
1922                         i++;
1923                         j = 0;
1924                 } else {
1925                         /* use the IP addresses from the SRV sresponse */
1926
1927                         if ( j >= dcs[i].num_ips ) {
1928                                 i++;
1929                                 j = 0;
1930                                 continue;
1931                         }
1932
1933                         r->ss = dcs[i].ss_s[j];
1934                         j++;
1935                 }
1936
1937                 /* make sure it is a valid IP.  I considered checking the
1938                  * negative connection cache, but this is the wrong place
1939                  * for it. Maybe only as a hack. After think about it, if
1940                  * all of the IP addresses returned from DNS are dead, what
1941                  * hope does a netbios name lookup have ? The standard reason
1942                  * for falling back to netbios lookups is that our DNS server
1943                  * doesn't know anything about the DC's   -- jerry */
1944
1945                 if (!is_zero_addr(&r->ss)) {
1946                         (*return_count)++;
1947                 }
1948         }
1949
1950         talloc_destroy(ctx);
1951         return NT_STATUS_OK;
1952 }
1953
1954 /*******************************************************************
1955  Internal interface to resolve a name into an IP address.
1956  Use this function if the string is either an IP address, DNS
1957  or host name or NetBIOS name. This uses the name switch in the
1958  smb.conf to determine the order of name resolution.
1959
1960  Added support for ip addr/port to support ADS ldap servers.
1961  the only place we currently care about the port is in the
1962  resolve_hosts() when looking up DC's via SRV RR entries in DNS
1963 **********************************************************************/
1964
1965 NTSTATUS internal_resolve_name(const char *name,
1966                                 int name_type,
1967                                 const char *sitename,
1968                                 struct ip_service **return_iplist,
1969                                 int *return_count,
1970                                 const char *resolve_order)
1971 {
1972         char *tok;
1973         const char *ptr;
1974         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1975         int i;
1976         TALLOC_CTX *frame = NULL;
1977
1978         *return_iplist = NULL;
1979         *return_count = 0;
1980
1981         DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1982                         name, name_type, sitename ? sitename : "(null)"));
1983
1984         if (is_ipaddress(name)) {
1985                 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
1986                                 NULL) {
1987                         DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1988                         return NT_STATUS_NO_MEMORY;
1989                 }
1990
1991                 /* ignore the port here */
1992                 (*return_iplist)->port = PORT_NONE;
1993
1994                 /* if it's in the form of an IP address then get the lib to interpret it */
1995                 if (!interpret_string_addr(&(*return_iplist)->ss,
1996                                         name, AI_NUMERICHOST)) {
1997                         DEBUG(1,("internal_resolve_name: interpret_string_addr "
1998                                 "failed on %s\n",
1999                                 name));
2000                         SAFE_FREE(*return_iplist);
2001                         return NT_STATUS_INVALID_PARAMETER;
2002                 }
2003                 *return_count = 1;
2004                 return NT_STATUS_OK;
2005         }
2006
2007         /* Check name cache */
2008
2009         if (namecache_fetch(name, name_type, return_iplist, return_count)) {
2010                 /* This could be a negative response */
2011                 if (*return_count > 0) {
2012                         return NT_STATUS_OK;
2013                 } else {
2014                         return NT_STATUS_UNSUCCESSFUL;
2015                 }
2016         }
2017
2018         /* set the name resolution order */
2019
2020         if (strcmp( resolve_order, "NULL") == 0) {
2021                 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
2022                 return NT_STATUS_INVALID_PARAMETER;
2023         }
2024
2025         if (!resolve_order[0]) {
2026                 ptr = "host";
2027         } else {
2028                 ptr = resolve_order;
2029         }
2030
2031         /* iterate through the name resolution backends */
2032
2033         frame = talloc_stackframe();
2034         while (next_token_talloc(frame, &ptr, &tok, LIST_SEP)) {
2035                 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
2036                         status = resolve_hosts(name, name_type, return_iplist,
2037                                                return_count);
2038                         if (NT_STATUS_IS_OK(status)) {
2039                                 goto done;
2040                         }
2041                 } else if(strequal( tok, "kdc")) {
2042                         /* deal with KDC_NAME_TYPE names here.
2043                          * This will result in a SRV record lookup */
2044                         status = resolve_ads(name, KDC_NAME_TYPE, sitename,
2045                                              return_iplist, return_count);
2046                         if (NT_STATUS_IS_OK(status)) {
2047                                 /* Ensure we don't namecache
2048                                  * this with the KDC port. */
2049                                 name_type = KDC_NAME_TYPE;
2050                                 goto done;
2051                         }
2052                 } else if(strequal( tok, "ads")) {
2053                         /* deal with 0x1c and 0x1b names here.
2054                          * This will result in a SRV record lookup */
2055                         status = resolve_ads(name, name_type, sitename,
2056                                              return_iplist, return_count);
2057                         if (NT_STATUS_IS_OK(status)) {
2058                                 goto done;
2059                         }
2060                 } else if(strequal( tok, "lmhosts")) {
2061                         status = resolve_lmhosts(name, name_type,
2062                                                  return_iplist, return_count);
2063                         if (NT_STATUS_IS_OK(status)) {
2064                                 goto done;
2065                         }
2066                 } else if(strequal( tok, "wins")) {
2067                         /* don't resolve 1D via WINS */
2068                         if (name_type != 0x1D) {
2069                                 status = resolve_wins(name, name_type,
2070                                                       return_iplist,
2071                                                       return_count);
2072                                 if (NT_STATUS_IS_OK(status)) {
2073                                         goto done;
2074                                 }
2075                         }
2076                 } else if(strequal( tok, "bcast")) {
2077                         status = name_resolve_bcast(name, name_type,
2078                                                     return_iplist,
2079                                                     return_count);
2080                         if (NT_STATUS_IS_OK(status)) {
2081                                 goto done;
2082                         }
2083                 } else {
2084                         DEBUG(0,("resolve_name: unknown name switch type %s\n",
2085                                 tok));
2086                 }
2087         }
2088
2089         /* All of the resolve_* functions above have returned false. */
2090
2091         TALLOC_FREE(frame);
2092         SAFE_FREE(*return_iplist);
2093         *return_count = 0;
2094
2095         return NT_STATUS_UNSUCCESSFUL;
2096
2097   done:
2098
2099         /* Remove duplicate entries.  Some queries, notably #1c (domain
2100         controllers) return the PDC in iplist[0] and then all domain
2101         controllers including the PDC in iplist[1..n].  Iterating over
2102         the iplist when the PDC is down will cause two sets of timeouts. */
2103
2104         if ( *return_count ) {
2105                 *return_count = remove_duplicate_addrs2(*return_iplist,
2106                                         *return_count );
2107         }
2108
2109         /* Save in name cache */
2110         if ( DEBUGLEVEL >= 100 ) {
2111                 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
2112                         char addr[INET6_ADDRSTRLEN];
2113                         print_sockaddr(addr, sizeof(addr),
2114                                         &(*return_iplist)[i].ss);
2115                         DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
2116                                         name,
2117                                         name_type,
2118                                         addr,
2119                                         (*return_iplist)[i].port));
2120                 }
2121         }
2122
2123         namecache_store(name, name_type, *return_count, *return_iplist);
2124
2125         /* Display some debugging info */
2126
2127         if ( DEBUGLEVEL >= 10 ) {
2128                 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
2129                                         *return_count));
2130
2131                 for (i = 0; i < *return_count; i++) {
2132                         char addr[INET6_ADDRSTRLEN];
2133                         print_sockaddr(addr, sizeof(addr),
2134                                         &(*return_iplist)[i].ss);
2135                         DEBUGADD(10, ("%s:%d ",
2136                                         addr,
2137                                         (*return_iplist)[i].port));
2138                 }
2139                 DEBUG(10, ("\n"));
2140         }
2141
2142         TALLOC_FREE(frame);
2143         return status;
2144 }
2145
2146 /********************************************************
2147  Internal interface to resolve a name into one IP address.
2148  Use this function if the string is either an IP address, DNS
2149  or host name or NetBIOS name. This uses the name switch in the
2150  smb.conf to determine the order of name resolution.
2151 *********************************************************/
2152
2153 bool resolve_name(const char *name,
2154                 struct sockaddr_storage *return_ss,
2155                 int name_type,
2156                 bool prefer_ipv4)
2157 {
2158         struct ip_service *ss_list = NULL;
2159         char *sitename = NULL;
2160         int count = 0;
2161
2162         if (is_ipaddress(name)) {
2163                 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
2164         }
2165
2166         sitename = sitename_fetch(lp_realm()); /* wild guess */
2167
2168         if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
2169                                                   &ss_list, &count,
2170                                                   lp_name_resolve_order()))) {
2171                 int i;
2172
2173                 if (prefer_ipv4) {
2174                         for (i=0; i<count; i++) {
2175                                 if (!is_zero_addr(&ss_list[i].ss) &&
2176                                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss) &&
2177                                                 (ss_list[i].ss.ss_family == AF_INET)) {
2178                                         *return_ss = ss_list[i].ss;
2179                                         SAFE_FREE(ss_list);
2180                                         SAFE_FREE(sitename);
2181                                         return True;
2182                                 }
2183                         }
2184                 }
2185
2186                 /* only return valid addresses for TCP connections */
2187                 for (i=0; i<count; i++) {
2188                         if (!is_zero_addr(&ss_list[i].ss) &&
2189                                         !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2190                                 *return_ss = ss_list[i].ss;
2191                                 SAFE_FREE(ss_list);
2192                                 SAFE_FREE(sitename);
2193                                 return True;
2194                         }
2195                 }
2196         }
2197
2198         SAFE_FREE(ss_list);
2199         SAFE_FREE(sitename);
2200         return False;
2201 }
2202
2203 /********************************************************
2204  Internal interface to resolve a name into a list of IP addresses.
2205  Use this function if the string is either an IP address, DNS
2206  or host name or NetBIOS name. This uses the name switch in the
2207  smb.conf to determine the order of name resolution.
2208 *********************************************************/
2209
2210 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
2211                 const char *name,
2212                 int name_type,
2213                 struct sockaddr_storage **return_ss_arr,
2214                 unsigned int *p_num_entries)
2215 {
2216         struct ip_service *ss_list = NULL;
2217         char *sitename = NULL;
2218         int count = 0;
2219         int i;
2220         unsigned int num_entries;
2221         NTSTATUS status;
2222
2223         *p_num_entries = 0;
2224         *return_ss_arr = NULL;
2225
2226         if (is_ipaddress(name)) {
2227                 *return_ss_arr = TALLOC_P(ctx, struct sockaddr_storage);
2228                 if (!*return_ss_arr) {
2229                         return NT_STATUS_NO_MEMORY;
2230                 }
2231                 if (!interpret_string_addr(*return_ss_arr, name, AI_NUMERICHOST)) {
2232                         TALLOC_FREE(*return_ss_arr);
2233                         return NT_STATUS_BAD_NETWORK_NAME;
2234                 }
2235                 *p_num_entries = 1;
2236                 return NT_STATUS_OK;
2237         }
2238
2239         sitename = sitename_fetch(lp_realm()); /* wild guess */
2240
2241         status = internal_resolve_name(name, name_type, sitename,
2242                                                   &ss_list, &count,
2243                                                   lp_name_resolve_order());
2244         SAFE_FREE(sitename);
2245
2246         if (!NT_STATUS_IS_OK(status)) {
2247                 return status;
2248         }
2249
2250         /* only return valid addresses for TCP connections */
2251         for (i=0, num_entries = 0; i<count; i++) {
2252                 if (!is_zero_addr(&ss_list[i].ss) &&
2253                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2254                         num_entries++;
2255                 }
2256         }
2257         if (num_entries == 0) {
2258                 SAFE_FREE(ss_list);
2259                 return NT_STATUS_BAD_NETWORK_NAME;
2260         }
2261
2262         *return_ss_arr = TALLOC_ARRAY(ctx,
2263                                 struct sockaddr_storage,
2264                                 num_entries);
2265         if (!(*return_ss_arr)) {
2266                 SAFE_FREE(ss_list);
2267                 return NT_STATUS_NO_MEMORY;
2268         }
2269
2270         for (i=0, num_entries = 0; i<count; i++) {
2271                 if (!is_zero_addr(&ss_list[i].ss) &&
2272                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2273                         (*return_ss_arr)[num_entries++] = ss_list[i].ss;
2274                 }
2275         }
2276
2277         status = NT_STATUS_OK;
2278         *p_num_entries = num_entries;
2279
2280         SAFE_FREE(ss_list);
2281         return NT_STATUS_OK;
2282 }
2283
2284 /********************************************************
2285  Find the IP address of the master browser or DMB for a workgroup.
2286 *********************************************************/
2287
2288 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
2289 {
2290         struct ip_service *ip_list = NULL;
2291         int count = 0;
2292         NTSTATUS status;
2293
2294         if (lp_disable_netbios()) {
2295                 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
2296                 return false;
2297         }
2298
2299         status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
2300                                        lp_name_resolve_order());
2301         if (NT_STATUS_IS_OK(status)) {
2302                 *master_ss = ip_list[0].ss;
2303                 SAFE_FREE(ip_list);
2304                 return true;
2305         }
2306
2307         status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
2308                                        lp_name_resolve_order());
2309         if (NT_STATUS_IS_OK(status)) {
2310                 *master_ss = ip_list[0].ss;
2311                 SAFE_FREE(ip_list);
2312                 return true;
2313         }
2314
2315         SAFE_FREE(ip_list);
2316         return false;
2317 }
2318
2319 /********************************************************
2320  Get the IP address list of the primary domain controller
2321  for a domain.
2322 *********************************************************/
2323
2324 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
2325 {
2326         struct ip_service *ip_list = NULL;
2327         int count = 0;
2328         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2329
2330         /* Look up #1B name */
2331
2332         if (lp_security() == SEC_ADS) {
2333                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2334                                                &count, "ads");
2335         }
2336
2337         if (!NT_STATUS_IS_OK(status) || count == 0) {
2338                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2339                                                &count,
2340                                                lp_name_resolve_order());
2341                 if (!NT_STATUS_IS_OK(status)) {
2342                         return false;
2343                 }
2344         }
2345
2346         /* if we get more than 1 IP back we have to assume it is a
2347            multi-homed PDC and not a mess up */
2348
2349         if ( count > 1 ) {
2350                 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
2351                 sort_service_list(ip_list, count);
2352         }
2353
2354         *pss = ip_list[0].ss;
2355         SAFE_FREE(ip_list);
2356         return true;
2357 }
2358
2359 /* Private enum type for lookups. */
2360
2361 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
2362
2363 /********************************************************
2364  Get the IP address list of the domain controllers for
2365  a domain.
2366 *********************************************************/
2367
2368 static NTSTATUS get_dc_list(const char *domain,
2369                         const char *sitename,
2370                         struct ip_service **ip_list,
2371                         int *count,
2372                         enum dc_lookup_type lookup_type,
2373                         bool *ordered)
2374 {
2375         char *resolve_order = NULL;
2376         char *saf_servername = NULL;
2377         char *pserver = NULL;
2378         const char *p;
2379         char *port_str = NULL;
2380         int port;
2381         char *name;
2382         int num_addresses = 0;
2383         int  local_count, i, j;
2384         struct ip_service *return_iplist = NULL;
2385         struct ip_service *auto_ip_list = NULL;
2386         bool done_auto_lookup = false;
2387         int auto_count = 0;
2388         NTSTATUS status;
2389         TALLOC_CTX *ctx = talloc_init("get_dc_list");
2390
2391         *ip_list = NULL;
2392         *count = 0;
2393
2394         if (!ctx) {
2395                 return NT_STATUS_NO_MEMORY;
2396         }
2397
2398         *ordered = False;
2399
2400         /* if we are restricted to solely using DNS for looking
2401            up a domain controller, make sure that host lookups
2402            are enabled for the 'name resolve order'.  If host lookups
2403            are disabled and ads_only is True, then set the string to
2404            NULL. */
2405
2406         resolve_order = talloc_strdup(ctx, lp_name_resolve_order());
2407         if (!resolve_order) {
2408                 status = NT_STATUS_NO_MEMORY;
2409                 goto out;
2410         }
2411         strlower_m(resolve_order);
2412         if (lookup_type == DC_ADS_ONLY)  {
2413                 if (strstr( resolve_order, "host")) {
2414                         resolve_order = talloc_strdup(ctx, "ads");
2415
2416                         /* DNS SRV lookups used by the ads resolver
2417                            are already sorted by priority and weight */
2418                         *ordered = true;
2419                 } else {
2420                         resolve_order = talloc_strdup(ctx, "NULL");
2421                 }
2422         } else if (lookup_type == DC_KDC_ONLY) {
2423                 /* DNS SRV lookups used by the ads/kdc resolver
2424                    are already sorted by priority and weight */
2425                 *ordered = true;
2426                 resolve_order = talloc_strdup(ctx, "kdc");
2427         }
2428         if (!resolve_order) {
2429                 status = NT_STATUS_NO_MEMORY;
2430                 goto out;
2431         }
2432
2433         /* fetch the server we have affinity for.  Add the
2434            'password server' list to a search for our domain controllers */
2435
2436         saf_servername = saf_fetch( domain);
2437
2438         if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
2439                 pserver = talloc_asprintf(ctx, "%s, %s",
2440                         saf_servername ? saf_servername : "",
2441                         lp_passwordserver());
2442         } else {
2443                 pserver = talloc_asprintf(ctx, "%s, *",
2444                         saf_servername ? saf_servername : "");
2445         }
2446
2447         SAFE_FREE(saf_servername);
2448         if (!pserver) {
2449                 status = NT_STATUS_NO_MEMORY;
2450                 goto out;
2451         }
2452
2453         /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
2454
2455         if (!*pserver ) {
2456                 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
2457                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2458                                              count, resolve_order);
2459                 goto out;
2460         }
2461
2462         DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
2463
2464         /*
2465          * if '*' appears in the "password server" list then add
2466          * an auto lookup to the list of manually configured
2467          * DC's.  If any DC is listed by name, then the list should be
2468          * considered to be ordered
2469          */
2470
2471         p = pserver;
2472         while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2473                 if (!done_auto_lookup && strequal(name, "*")) {
2474                         status = internal_resolve_name(domain, 0x1C, sitename,
2475                                                        &auto_ip_list,
2476                                                        &auto_count,
2477                                                        resolve_order);
2478                         if (NT_STATUS_IS_OK(status)) {
2479                                 num_addresses += auto_count;
2480                         }
2481                         done_auto_lookup = true;
2482                         DEBUG(8,("Adding %d DC's from auto lookup\n",
2483                                                 auto_count));
2484                 } else  {
2485                         num_addresses++;
2486                 }
2487         }
2488
2489         /* if we have no addresses and haven't done the auto lookup, then
2490            just return the list of DC's.  Or maybe we just failed. */
2491
2492         if ((num_addresses == 0)) {
2493                 if (done_auto_lookup) {
2494                         DEBUG(4,("get_dc_list: no servers found\n"));
2495                         status = NT_STATUS_NO_LOGON_SERVERS;
2496                         goto out;
2497                 }
2498                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2499                                              count, resolve_order);
2500                 goto out;
2501         }
2502
2503         if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
2504                                         num_addresses)) == NULL) {
2505                 DEBUG(3,("get_dc_list: malloc fail !\n"));
2506                 status = NT_STATUS_NO_MEMORY;
2507                 goto out;
2508         }
2509
2510         p = pserver;
2511         local_count = 0;
2512
2513         /* fill in the return list now with real IP's */
2514
2515         while ((local_count<num_addresses) &&
2516                         next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2517                 struct sockaddr_storage name_ss;
2518
2519                 /* copy any addersses from the auto lookup */
2520
2521                 if (strequal(name, "*")) {
2522                         for (j=0; j<auto_count; j++) {
2523                                 char addr[INET6_ADDRSTRLEN];
2524                                 print_sockaddr(addr,
2525                                                 sizeof(addr),
2526                                                 &auto_ip_list[j].ss);
2527                                 /* Check for and don't copy any
2528                                  * known bad DC IP's. */
2529                                 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
2530                                                 domain,
2531                                                 addr))) {
2532                                         DEBUG(5,("get_dc_list: "
2533                                                 "negative entry %s removed "
2534                                                 "from DC list\n",
2535                                                 addr));
2536                                         continue;
2537                                 }
2538                                 return_iplist[local_count].ss =
2539                                         auto_ip_list[j].ss;
2540                                 return_iplist[local_count].port =
2541                                         auto_ip_list[j].port;
2542                                 local_count++;
2543                         }
2544                         continue;
2545                 }
2546
2547                 /* added support for address:port syntax for ads
2548                  * (not that I think anyone will ever run the LDAP
2549                  * server in an AD domain on something other than
2550                  * port 389 */
2551
2552                 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
2553                 if ((port_str=strchr(name, ':')) != NULL) {
2554                         *port_str = '\0';
2555                         port_str++;
2556                         port = atoi(port_str);
2557                 }
2558
2559                 /* explicit lookup; resolve_name() will
2560                  * handle names & IP addresses */
2561                 if (resolve_name( name, &name_ss, 0x20, true )) {
2562                         char addr[INET6_ADDRSTRLEN];
2563                         print_sockaddr(addr,
2564                                         sizeof(addr),
2565                                         &name_ss);
2566
2567                         /* Check for and don't copy any known bad DC IP's. */
2568                         if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
2569                                                         addr)) ) {
2570                                 DEBUG(5,("get_dc_list: negative entry %s "
2571                                         "removed from DC list\n",
2572                                         name ));
2573                                 continue;
2574                         }
2575
2576                         return_iplist[local_count].ss = name_ss;
2577                         return_iplist[local_count].port = port;
2578                         local_count++;
2579                         *ordered = true;
2580                 }
2581         }
2582
2583         /* need to remove duplicates in the list if we have any
2584            explicit password servers */
2585
2586         if (local_count) {
2587                 local_count = remove_duplicate_addrs2(return_iplist,
2588                                 local_count );
2589         }
2590
2591         /* For DC's we always prioritize IPv4 due to W2K3 not
2592          * supporting LDAP, KRB5 or CLDAP over IPv6. */
2593
2594         if (local_count && return_iplist) {
2595                 prioritize_ipv4_list(return_iplist, local_count);
2596         }
2597
2598         if ( DEBUGLEVEL >= 4 ) {
2599                 DEBUG(4,("get_dc_list: returning %d ip addresses "
2600                                 "in an %sordered list\n",
2601                                 local_count,
2602                                 *ordered ? "":"un"));
2603                 DEBUG(4,("get_dc_list: "));
2604                 for ( i=0; i<local_count; i++ ) {
2605                         char addr[INET6_ADDRSTRLEN];
2606                         print_sockaddr(addr,
2607                                         sizeof(addr),
2608                                         &return_iplist[i].ss);
2609                         DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
2610                 }
2611                 DEBUGADD(4,("\n"));
2612         }
2613
2614         *ip_list = return_iplist;
2615         *count = local_count;
2616
2617         status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
2618
2619   out:
2620
2621         if (!NT_STATUS_IS_OK(status)) {
2622                 SAFE_FREE(return_iplist);
2623                 *ip_list = NULL;
2624                 *count = 0;
2625         }
2626
2627         SAFE_FREE(auto_ip_list);
2628         TALLOC_FREE(ctx);
2629         return status;
2630 }
2631
2632 /*********************************************************************
2633  Small wrapper function to get the DC list and sort it if neccessary.
2634 *********************************************************************/
2635
2636 NTSTATUS get_sorted_dc_list( const char *domain,
2637                         const char *sitename,
2638                         struct ip_service **ip_list,
2639                         int *count,
2640                         bool ads_only )
2641 {
2642         bool ordered = false;
2643         NTSTATUS status;
2644         enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
2645
2646         *ip_list = NULL;
2647         *count = 0;
2648
2649         DEBUG(8,("get_sorted_dc_list: attempting lookup "
2650                 "for name %s (sitename %s) using [%s]\n",
2651                 domain,
2652                 sitename ? sitename : "NULL",
2653                 (ads_only ? "ads" : lp_name_resolve_order())));
2654
2655         if (ads_only) {
2656                 lookup_type = DC_ADS_ONLY;
2657         }
2658
2659         status = get_dc_list(domain, sitename, ip_list,
2660                         count, lookup_type, &ordered);
2661         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS)
2662             && sitename) {
2663                 DEBUG(3,("get_sorted_dc_list: no server for name %s available"
2664                          " in site %s, fallback to all servers\n",
2665                          domain, sitename));
2666                 status = get_dc_list(domain, NULL, ip_list,
2667                                      count, lookup_type, &ordered);
2668         }
2669
2670         if (!NT_STATUS_IS_OK(status)) {
2671                 SAFE_FREE(*ip_list);
2672                 *count = 0;
2673                 return status;
2674         }
2675
2676         /* only sort if we don't already have an ordered list */
2677         if (!ordered) {
2678                 sort_service_list(*ip_list, *count);
2679         }
2680
2681         return NT_STATUS_OK;
2682 }
2683
2684 /*********************************************************************
2685  Get the KDC list - re-use all the logic in get_dc_list.
2686 *********************************************************************/
2687
2688 NTSTATUS get_kdc_list( const char *realm,
2689                         const char *sitename,
2690                         struct ip_service **ip_list,
2691                         int *count)
2692 {
2693         bool ordered;
2694         NTSTATUS status;
2695
2696         *count = 0;
2697         *ip_list = NULL;
2698
2699         status = get_dc_list(realm, sitename, ip_list,
2700                         count, DC_KDC_ONLY, &ordered);
2701
2702         if (!NT_STATUS_IS_OK(status)) {
2703                 SAFE_FREE(*ip_list);
2704                 *count = 0;
2705                 return status;
2706         }
2707
2708         /* only sort if we don't already have an ordered list */
2709         if ( !ordered ) {
2710                 sort_service_list(*ip_list, *count);
2711         }
2712
2713         return NT_STATUS_OK;
2714 }