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