Fix convert_ss2service() to filter out zero addresses.
[ddiss/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 set duplicates to a zero addr. */
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         /* Now remove any addresses set to zero above. */
1096         for (i = 0; i < count; i++) {
1097                 while (i < count &&
1098                                 is_zero_addr(&iplist[i].ss)) {
1099                         if (count-i-1>0) {
1100                                 memmove(&iplist[i],
1101                                         &iplist[i+1],
1102                                         (count-i-1)*sizeof(struct ip_service));
1103                         }
1104                         count--;
1105                 }
1106         }
1107
1108         return count;
1109 }
1110
1111 static bool prioritize_ipv4_list(struct ip_service *iplist, int count)
1112 {
1113         TALLOC_CTX *frame = talloc_stackframe();
1114         struct ip_service *iplist_new = TALLOC_ARRAY(frame, struct ip_service, count);
1115         int i, j;
1116
1117         if (iplist_new == NULL) {
1118                 TALLOC_FREE(frame);
1119                 return false;
1120         }
1121
1122         j = 0;
1123
1124         /* Copy IPv4 first. */
1125         for (i = 0; i < count; i++) {
1126                 if (iplist[i].ss.ss_family == AF_INET) {
1127                         iplist_new[j++] = iplist[i];
1128                 }
1129         }
1130
1131         /* Copy IPv6. */
1132         for (i = 0; i < count; i++) {
1133                 if (iplist[i].ss.ss_family != AF_INET) {
1134                         iplist_new[j++] = iplist[i];
1135                 }
1136         }
1137
1138         memcpy(iplist, iplist_new, sizeof(struct ip_service)*count);
1139         TALLOC_FREE(frame);
1140         return true;
1141 }
1142
1143 /****************************************************************************
1144  Do a netbios name query to find someones IP.
1145  Returns an array of IP addresses or NULL if none.
1146  *count will be set to the number of addresses returned.
1147  *timed_out is set if we failed by timing out
1148 ****************************************************************************/
1149
1150 struct name_query_state {
1151         struct sockaddr_storage my_addr;
1152         struct sockaddr_storage addr;
1153         bool bcast;
1154
1155
1156         uint8_t buf[1024];
1157         ssize_t buflen;
1158
1159         NTSTATUS validate_error;
1160         uint8_t flags;
1161
1162         struct sockaddr_storage *addrs;
1163         int num_addrs;
1164 };
1165
1166 static bool name_query_validator(struct packet_struct *p, void *private_data);
1167 static void name_query_done(struct tevent_req *subreq);
1168
1169 struct tevent_req *name_query_send(TALLOC_CTX *mem_ctx,
1170                                    struct tevent_context *ev,
1171                                    const char *name, int name_type,
1172                                    bool bcast, bool recurse,
1173                                    const struct sockaddr_storage *addr)
1174 {
1175         struct tevent_req *req, *subreq;
1176         struct name_query_state *state;
1177         struct packet_struct p;
1178         struct nmb_packet *nmb = &p.packet.nmb;
1179         struct sockaddr_in *in_addr;
1180
1181         req = tevent_req_create(mem_ctx, &state, struct name_query_state);
1182         if (req == NULL) {
1183                 return NULL;
1184         }
1185         state->bcast = bcast;
1186
1187         if (addr->ss_family != AF_INET) {
1188                 /* Can't do node status to IPv6 */
1189                 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
1190                 return tevent_req_post(req, ev);
1191         }
1192
1193         if (lp_disable_netbios()) {
1194                 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
1195                                         name, name_type));
1196                 tevent_req_nterror(req, NT_STATUS_NOT_SUPPORTED);
1197                 return tevent_req_post(req, ev);
1198         }
1199
1200         state->addr = *addr;
1201         in_addr = (struct sockaddr_in *)(void *)&state->addr;
1202         in_addr->sin_port = htons(NMB_PORT);
1203
1204         if (!interpret_string_addr(&state->my_addr, lp_socket_address(),
1205                                    AI_NUMERICHOST|AI_PASSIVE)) {
1206                 zero_sockaddr(&state->my_addr);
1207         }
1208
1209         ZERO_STRUCT(p);
1210         nmb->header.name_trn_id = generate_trn_id();
1211         nmb->header.opcode = 0;
1212         nmb->header.response = false;
1213         nmb->header.nm_flags.bcast = bcast;
1214         nmb->header.nm_flags.recursion_available = false;
1215         nmb->header.nm_flags.recursion_desired = recurse;
1216         nmb->header.nm_flags.trunc = false;
1217         nmb->header.nm_flags.authoritative = false;
1218         nmb->header.rcode = 0;
1219         nmb->header.qdcount = 1;
1220         nmb->header.ancount = 0;
1221         nmb->header.nscount = 0;
1222         nmb->header.arcount = 0;
1223
1224         make_nmb_name(&nmb->question.question_name,name,name_type);
1225
1226         nmb->question.question_type = 0x20;
1227         nmb->question.question_class = 0x1;
1228
1229         state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
1230                                      &p);
1231         if (state->buflen == 0) {
1232                 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1233                 DEBUG(10, ("build_packet failed\n"));
1234                 return tevent_req_post(req, ev);
1235         }
1236
1237         subreq = nb_trans_send(state, ev, &state->my_addr, &state->addr, bcast,
1238                                state->buf, state->buflen,
1239                                NMB_PACKET, nmb->header.name_trn_id,
1240                                name_query_validator, state);
1241         if (tevent_req_nomem(subreq, req)) {
1242                 DEBUG(10, ("nb_trans_send failed\n"));
1243                 return tevent_req_post(req, ev);
1244         }
1245         tevent_req_set_callback(subreq, name_query_done, req);
1246         return req;
1247 }
1248
1249 static bool name_query_validator(struct packet_struct *p, void *private_data)
1250 {
1251         struct name_query_state *state = talloc_get_type_abort(
1252                 private_data, struct name_query_state);
1253         struct nmb_packet *nmb = &p->packet.nmb;
1254         struct sockaddr_storage *tmp_addrs;
1255         bool got_unique_netbios_name = false;
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                 uint16_t flags;
1331                 struct in_addr ip;
1332                 struct sockaddr_storage addr;
1333                 int j;
1334
1335                 flags = RSVAL(&nmb->answers->rdata[i*6], 0);
1336                 got_unique_netbios_name |= ((flags & 0x8000) == 0);
1337
1338                 putip((char *)&ip,&nmb->answers->rdata[2+i*6]);
1339                 in_addr_to_sockaddr_storage(&addr, ip);
1340
1341                 for (j=0; j<state->num_addrs; j++) {
1342                         if (sockaddr_equal(
1343                                     (struct sockaddr *)&addr,
1344                                     (struct sockaddr *)&state->addrs[j])) {
1345                                 break;
1346                         }
1347                 }
1348                 if (j < state->num_addrs) {
1349                         /* Already got it */
1350                         continue;
1351                 }
1352
1353                 DEBUGADD(2,("%s ",inet_ntoa(ip)));
1354
1355                 state->addrs[state->num_addrs] = addr;
1356                 state->num_addrs += 1;
1357         }
1358         DEBUGADD(2,(")\n"));
1359
1360         /* We add the flags back ... */
1361         if (nmb->header.response)
1362                 state->flags |= NM_FLAGS_RS;
1363         if (nmb->header.nm_flags.authoritative)
1364                 state->flags |= NM_FLAGS_AA;
1365         if (nmb->header.nm_flags.trunc)
1366                 state->flags |= NM_FLAGS_TC;
1367         if (nmb->header.nm_flags.recursion_desired)
1368                 state->flags |= NM_FLAGS_RD;
1369         if (nmb->header.nm_flags.recursion_available)
1370                 state->flags |= NM_FLAGS_RA;
1371         if (nmb->header.nm_flags.bcast)
1372                 state->flags |= NM_FLAGS_B;
1373
1374         if (state->bcast) {
1375                 /*
1376                  * We have to collect all entries coming in from broadcast
1377                  * queries. If we got a unique name, we're done.
1378                  */
1379                 return got_unique_netbios_name;
1380         }
1381         /*
1382          * WINS responses are accepted when they are received
1383          */
1384         return true;
1385 }
1386
1387 static void name_query_done(struct tevent_req *subreq)
1388 {
1389         struct tevent_req *req = tevent_req_callback_data(
1390                 subreq, struct tevent_req);
1391         struct name_query_state *state = tevent_req_data(
1392                 req, struct name_query_state);
1393         NTSTATUS status;
1394         struct packet_struct *p = NULL;
1395
1396         status = nb_trans_recv(subreq, &p);
1397         TALLOC_FREE(subreq);
1398         if (tevent_req_nterror(req, status)) {
1399                 return;
1400         }
1401         if (!NT_STATUS_IS_OK(state->validate_error)) {
1402                 tevent_req_nterror(req, state->validate_error);
1403                 return;
1404         }
1405         if (p != NULL) {
1406                 /*
1407                  * Free the packet here, we've collected the response in the
1408                  * validator
1409                  */
1410                 free_packet(p);
1411         }
1412         tevent_req_done(req);
1413 }
1414
1415 NTSTATUS name_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1416                          struct sockaddr_storage **addrs, int *num_addrs,
1417                          uint8_t *flags)
1418 {
1419         struct name_query_state *state = tevent_req_data(
1420                 req, struct name_query_state);
1421         NTSTATUS status;
1422
1423         if (tevent_req_is_nterror(req, &status)
1424             && !NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
1425                 return status;
1426         }
1427         if (state->num_addrs == 0) {
1428                 return NT_STATUS_NOT_FOUND;
1429         }
1430         *addrs = talloc_move(mem_ctx, &state->addrs);
1431         sort_addr_list(*addrs, state->num_addrs);
1432         *num_addrs = state->num_addrs;
1433         if (flags != NULL) {
1434                 *flags = state->flags;
1435         }
1436         return NT_STATUS_OK;
1437 }
1438
1439 NTSTATUS name_query(const char *name, int name_type,
1440                     bool bcast, bool recurse,
1441                     const struct sockaddr_storage *to_ss,
1442                     TALLOC_CTX *mem_ctx,
1443                     struct sockaddr_storage **addrs,
1444                     int *num_addrs, uint8_t *flags)
1445 {
1446         TALLOC_CTX *frame = talloc_stackframe();
1447         struct tevent_context *ev;
1448         struct tevent_req *req;
1449         struct timeval timeout;
1450         NTSTATUS status = NT_STATUS_NO_MEMORY;
1451
1452         ev = tevent_context_init(frame);
1453         if (ev == NULL) {
1454                 goto fail;
1455         }
1456         req = name_query_send(ev, ev, name, name_type, bcast, recurse, to_ss);
1457         if (req == NULL) {
1458                 goto fail;
1459         }
1460         if (bcast) {
1461                 timeout = timeval_current_ofs(0, 250000);
1462         } else {
1463                 timeout = timeval_current_ofs(2, 0);
1464         }
1465         if (!tevent_req_set_endtime(req, ev, timeout)) {
1466                 goto fail;
1467         }
1468         if (!tevent_req_poll_ntstatus(req, ev, &status)) {
1469                 goto fail;
1470         }
1471         status = name_query_recv(req, mem_ctx, addrs, num_addrs, flags);
1472  fail:
1473         TALLOC_FREE(frame);
1474         return status;
1475 }
1476
1477 /********************************************************
1478  Convert an array if struct sockaddr_storage to struct ip_service
1479  return false on failure.  Port is set to PORT_NONE;
1480  pcount is [in/out] - it is the length of ss_list on input,
1481  and the length of return_iplist on output as we remove any
1482  zero addresses from ss_list.
1483 *********************************************************/
1484
1485 static bool convert_ss2service(struct ip_service **return_iplist,
1486                 const struct sockaddr_storage *ss_list,
1487                 int *pcount)
1488 {
1489         int i;
1490         int orig_count = *pcount;
1491         int real_count = 0;
1492
1493         if (orig_count==0 || !ss_list )
1494                 return False;
1495
1496         /* Filter out zero addrs. */
1497         for ( i=0; i<orig_count; i++ ) {
1498                 if (is_zero_addr(&ss_list[i])) {
1499                         continue;
1500                 }
1501                 real_count++;
1502         }
1503         if (real_count==0) {
1504                 return false;
1505         }
1506
1507         /* copy the ip address; port will be PORT_NONE */
1508         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, real_count)) ==
1509                         NULL) {
1510                 DEBUG(0,("convert_ip2service: malloc failed "
1511                         "for %d enetries!\n", real_count ));
1512                 return False;
1513         }
1514
1515         for ( i=0, real_count = 0; i<orig_count; i++ ) {
1516                 if (is_zero_addr(&ss_list[i])) {
1517                         continue;
1518                 }
1519                 (*return_iplist)[real_count].ss   = ss_list[i];
1520                 (*return_iplist)[real_count].port = PORT_NONE;
1521                 real_count++;
1522         }
1523
1524         *pcount = real_count;
1525         return true;
1526 }
1527
1528 /********************************************************
1529  Resolve via "bcast" method.
1530 *********************************************************/
1531
1532 NTSTATUS name_resolve_bcast(const char *name,
1533                         int name_type,
1534                         TALLOC_CTX *mem_ctx,
1535                         struct sockaddr_storage **return_iplist,
1536                         int *return_count)
1537 {
1538         int i;
1539         int num_interfaces = iface_count();
1540         struct sockaddr_storage *ss_list;
1541         NTSTATUS status = NT_STATUS_NOT_FOUND;
1542
1543         if (lp_disable_netbios()) {
1544                 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n",
1545                                         name, name_type));
1546                 return NT_STATUS_INVALID_PARAMETER;
1547         }
1548
1549         *return_iplist = NULL;
1550         *return_count = 0;
1551
1552         /*
1553          * "bcast" means do a broadcast lookup on all the local interfaces.
1554          */
1555
1556         DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup "
1557                 "for name %s<0x%x>\n", name, name_type));
1558
1559         /*
1560          * Lookup the name on all the interfaces, return on
1561          * the first successful match.
1562          */
1563         for( i = num_interfaces-1; i >= 0; i--) {
1564                 const struct sockaddr_storage *pss = iface_n_bcast(i);
1565
1566                 /* Done this way to fix compiler error on IRIX 5.x */
1567                 if (!pss) {
1568                         continue;
1569                 }
1570                 status = name_query(name, name_type, true, true, pss,
1571                                     talloc_tos(), &ss_list, return_count,
1572                                     NULL);
1573                 if (NT_STATUS_IS_OK(status)) {
1574                         goto success;
1575                 }
1576         }
1577
1578         /* failed - no response */
1579
1580         return status;
1581
1582 success:
1583         *return_iplist = ss_list;
1584         return status;
1585 }
1586
1587 /********************************************************
1588  Resolve via "wins" method.
1589 *********************************************************/
1590
1591 NTSTATUS resolve_wins(const char *name,
1592                 int name_type,
1593                 struct ip_service **return_iplist,
1594                 int *return_count)
1595 {
1596         int t, i;
1597         char **wins_tags;
1598         struct sockaddr_storage src_ss, *ss_list = NULL;
1599         struct in_addr src_ip;
1600         NTSTATUS status;
1601
1602         if (lp_disable_netbios()) {
1603                 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n",
1604                                         name, name_type));
1605                 return NT_STATUS_INVALID_PARAMETER;
1606         }
1607
1608         *return_iplist = NULL;
1609         *return_count = 0;
1610
1611         DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n",
1612                                 name, name_type));
1613
1614         if (wins_srv_count() < 1) {
1615                 DEBUG(3,("resolve_wins: WINS server resolution selected "
1616                         "and no WINS servers listed.\n"));
1617                 return NT_STATUS_INVALID_PARAMETER;
1618         }
1619
1620         /* we try a lookup on each of the WINS tags in turn */
1621         wins_tags = wins_srv_tags();
1622
1623         if (!wins_tags) {
1624                 /* huh? no tags?? give up in disgust */
1625                 return NT_STATUS_INVALID_PARAMETER;
1626         }
1627
1628         /* the address we will be sending from */
1629         if (!interpret_string_addr(&src_ss, lp_socket_address(),
1630                                 AI_NUMERICHOST|AI_PASSIVE)) {
1631                 zero_sockaddr(&src_ss);
1632         }
1633
1634         if (src_ss.ss_family != AF_INET) {
1635                 char addr[INET6_ADDRSTRLEN];
1636                 print_sockaddr(addr, sizeof(addr), &src_ss);
1637                 DEBUG(3,("resolve_wins: cannot receive WINS replies "
1638                         "on IPv6 address %s\n",
1639                         addr));
1640                 wins_srv_tags_free(wins_tags);
1641                 return NT_STATUS_INVALID_PARAMETER;
1642         }
1643
1644         src_ip = ((struct sockaddr_in *)&src_ss)->sin_addr;
1645
1646         /* in the worst case we will try every wins server with every
1647            tag! */
1648         for (t=0; wins_tags && wins_tags[t]; t++) {
1649                 int srv_count = wins_srv_count_tag(wins_tags[t]);
1650                 for (i=0; i<srv_count; i++) {
1651                         struct sockaddr_storage wins_ss;
1652                         struct in_addr wins_ip;
1653
1654                         wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
1655
1656                         if (global_in_nmbd && ismyip_v4(wins_ip)) {
1657                                 /* yikes! we'll loop forever */
1658                                 continue;
1659                         }
1660
1661                         /* skip any that have been unresponsive lately */
1662                         if (wins_srv_is_dead(wins_ip, src_ip)) {
1663                                 continue;
1664                         }
1665
1666                         DEBUG(3,("resolve_wins: using WINS server %s "
1667                                 "and tag '%s'\n",
1668                                 inet_ntoa(wins_ip), wins_tags[t]));
1669
1670                         in_addr_to_sockaddr_storage(&wins_ss, wins_ip);
1671                         status = name_query(name,
1672                                                 name_type,
1673                                                 false,
1674                                                 true,
1675                                                 &wins_ss,
1676                                                 talloc_tos(),
1677                                                 &ss_list,
1678                                                 return_count,
1679                                                 NULL);
1680
1681                         /* exit loop if we got a list of addresses */
1682
1683                         if (NT_STATUS_IS_OK(status)) {
1684                                 goto success;
1685                         }
1686
1687                         if (NT_STATUS_EQUAL(status,
1688                                             NT_STATUS_IO_TIMEOUT)) {
1689                                 /* Timed out waiting for WINS server to
1690                                  * respond.
1691                                  * Mark it dead. */
1692                                 wins_srv_died(wins_ip, src_ip);
1693                         } else {
1694                                 /* The name definitely isn't in this
1695                                    group of WINS servers.
1696                                    goto the next group  */
1697                                 break;
1698                         }
1699                 }
1700         }
1701
1702         wins_srv_tags_free(wins_tags);
1703         return NT_STATUS_NO_LOGON_SERVERS;
1704
1705 success:
1706
1707         status = NT_STATUS_OK;
1708         if (!convert_ss2service(return_iplist, ss_list, return_count))
1709                 status = NT_STATUS_INVALID_PARAMETER;
1710
1711         TALLOC_FREE(ss_list);
1712         wins_srv_tags_free(wins_tags);
1713
1714         return status;
1715 }
1716
1717 /********************************************************
1718  Resolve via "lmhosts" method.
1719 *********************************************************/
1720
1721 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
1722                                 struct ip_service **return_iplist,
1723                                 int *return_count)
1724 {
1725         /*
1726          * "lmhosts" means parse the local lmhosts file.
1727          */
1728         struct sockaddr_storage *ss_list;
1729         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1730         TALLOC_CTX *ctx = NULL;
1731
1732         *return_iplist = NULL;
1733         *return_count = 0;
1734
1735         DEBUG(3,("resolve_lmhosts: "
1736                 "Attempting lmhosts lookup for name %s<0x%x>\n",
1737                 name, name_type));
1738
1739         ctx = talloc_init("resolve_lmhosts");
1740         if (!ctx) {
1741                 return NT_STATUS_NO_MEMORY;
1742         }
1743
1744         status = resolve_lmhosts_file_as_sockaddr(get_dyn_LMHOSTSFILE(), 
1745                                                   name, name_type, 
1746                                                   ctx, 
1747                                                   &ss_list, 
1748                                                   return_count);
1749         if (NT_STATUS_IS_OK(status)) {
1750                 if (convert_ss2service(return_iplist, 
1751                                        ss_list,
1752                                        return_count)) {
1753                         talloc_free(ctx);
1754                         return NT_STATUS_OK;
1755                 } else {
1756                         talloc_free(ctx);
1757                         return NT_STATUS_NO_MEMORY;
1758                 }
1759         }
1760         talloc_free(ctx);
1761         return status;
1762 }
1763
1764
1765 /********************************************************
1766  Resolve via "hosts" method.
1767 *********************************************************/
1768
1769 static NTSTATUS resolve_hosts(const char *name, int name_type,
1770                               struct ip_service **return_iplist,
1771                               int *return_count)
1772 {
1773         /*
1774          * "host" means do a localhost, or dns lookup.
1775          */
1776         struct addrinfo hints;
1777         struct addrinfo *ailist = NULL;
1778         struct addrinfo *res = NULL;
1779         int ret = -1;
1780         int i = 0;
1781
1782         if ( name_type != 0x20 && name_type != 0x0) {
1783                 DEBUG(5, ("resolve_hosts: not appropriate "
1784                         "for name type <0x%x>\n",
1785                         name_type));
1786                 return NT_STATUS_INVALID_PARAMETER;
1787         }
1788
1789         *return_iplist = NULL;
1790         *return_count = 0;
1791
1792         DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
1793                                 name, name_type));
1794
1795         ZERO_STRUCT(hints);
1796         /* By default make sure it supports TCP. */
1797         hints.ai_socktype = SOCK_STREAM;
1798         hints.ai_flags = AI_ADDRCONFIG;
1799
1800 #if !defined(HAVE_IPV6)
1801         /* Unless we have IPv6, we really only want IPv4 addresses back. */
1802         hints.ai_family = AF_INET;
1803 #endif
1804
1805         ret = getaddrinfo(name,
1806                         NULL,
1807                         &hints,
1808                         &ailist);
1809         if (ret) {
1810                 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1811                         name,
1812                         gai_strerror(ret) ));
1813         }
1814
1815         for (res = ailist; res; res = res->ai_next) {
1816                 struct sockaddr_storage ss;
1817
1818                 if (!res->ai_addr || res->ai_addrlen == 0) {
1819                         continue;
1820                 }
1821
1822                 ZERO_STRUCT(ss);
1823                 memcpy(&ss, res->ai_addr, res->ai_addrlen);
1824
1825                 *return_count += 1;
1826
1827                 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1828                                                 struct ip_service,
1829                                                 *return_count);
1830                 if (!*return_iplist) {
1831                         DEBUG(3,("resolve_hosts: malloc fail !\n"));
1832                         freeaddrinfo(ailist);
1833                         return NT_STATUS_NO_MEMORY;
1834                 }
1835                 (*return_iplist)[i].ss = ss;
1836                 (*return_iplist)[i].port = PORT_NONE;
1837                 i++;
1838         }
1839         if (ailist) {
1840                 freeaddrinfo(ailist);
1841         }
1842         if (*return_count) {
1843                 return NT_STATUS_OK;
1844         }
1845         return NT_STATUS_UNSUCCESSFUL;
1846 }
1847
1848 /********************************************************
1849  Resolve via "ADS" method.
1850 *********************************************************/
1851
1852 /* Special name type used to cause a _kerberos DNS lookup. */
1853 #define KDC_NAME_TYPE 0xDCDC
1854
1855 static NTSTATUS resolve_ads(const char *name,
1856                             int name_type,
1857                             const char *sitename,
1858                             struct ip_service **return_iplist,
1859                             int *return_count)
1860 {
1861         int                     i, j;
1862         NTSTATUS                status;
1863         TALLOC_CTX              *ctx;
1864         struct dns_rr_srv       *dcs = NULL;
1865         int                     numdcs = 0;
1866         int                     numaddrs = 0;
1867
1868         if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1869             (name_type != 0x1b)) {
1870                 return NT_STATUS_INVALID_PARAMETER;
1871         }
1872
1873         if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1874                 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1875                 return NT_STATUS_NO_MEMORY;
1876         }
1877
1878         /* The DNS code needs fixing to find IPv6 addresses... JRA. */
1879
1880         switch (name_type) {
1881                 case 0x1b:
1882                         DEBUG(5,("resolve_ads: Attempting to resolve "
1883                                  "PDC for %s using DNS\n", name));
1884                         status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1885                         break;
1886
1887                 case 0x1c:
1888                         DEBUG(5,("resolve_ads: Attempting to resolve "
1889                                  "DCs for %s using DNS\n", name));
1890                         status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1891                                                    &numdcs);
1892                         break;
1893                 case KDC_NAME_TYPE:
1894                         DEBUG(5,("resolve_ads: Attempting to resolve "
1895                                  "KDCs for %s using DNS\n", name));
1896                         status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1897                                                     &numdcs);
1898                         break;
1899                 default:
1900                         status = NT_STATUS_INVALID_PARAMETER;
1901                         break;
1902         }
1903
1904         if ( !NT_STATUS_IS_OK( status ) ) {
1905                 talloc_destroy(ctx);
1906                 return status;
1907         }
1908
1909         for (i=0;i<numdcs;i++) {
1910                 numaddrs += MAX(dcs[i].num_ips,1);
1911         }
1912
1913         if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
1914                         NULL ) {
1915                 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
1916                                         numaddrs ));
1917                 talloc_destroy(ctx);
1918                 return NT_STATUS_NO_MEMORY;
1919         }
1920
1921         /* now unroll the list of IP addresses */
1922
1923         *return_count = 0;
1924         i = 0;
1925         j = 0;
1926         while ( i < numdcs && (*return_count<numaddrs) ) {
1927                 struct ip_service *r = &(*return_iplist)[*return_count];
1928
1929                 r->port = dcs[i].port;
1930
1931                 /* If we don't have an IP list for a name, lookup it up */
1932
1933                 if (!dcs[i].ss_s) {
1934                         interpret_string_addr(&r->ss, dcs[i].hostname, 0);
1935                         i++;
1936                         j = 0;
1937                 } else {
1938                         /* use the IP addresses from the SRV sresponse */
1939
1940                         if ( j >= dcs[i].num_ips ) {
1941                                 i++;
1942                                 j = 0;
1943                                 continue;
1944                         }
1945
1946                         r->ss = dcs[i].ss_s[j];
1947                         j++;
1948                 }
1949
1950                 /* make sure it is a valid IP.  I considered checking the
1951                  * negative connection cache, but this is the wrong place
1952                  * for it. Maybe only as a hack. After think about it, if
1953                  * all of the IP addresses returned from DNS are dead, what
1954                  * hope does a netbios name lookup have ? The standard reason
1955                  * for falling back to netbios lookups is that our DNS server
1956                  * doesn't know anything about the DC's   -- jerry */
1957
1958                 if (!is_zero_addr(&r->ss)) {
1959                         (*return_count)++;
1960                 }
1961         }
1962
1963         talloc_destroy(ctx);
1964         return NT_STATUS_OK;
1965 }
1966
1967 /*******************************************************************
1968  Internal interface to resolve a name into an IP address.
1969  Use this function if the string is either an IP address, DNS
1970  or host name or NetBIOS name. This uses the name switch in the
1971  smb.conf to determine the order of name resolution.
1972
1973  Added support for ip addr/port to support ADS ldap servers.
1974  the only place we currently care about the port is in the
1975  resolve_hosts() when looking up DC's via SRV RR entries in DNS
1976 **********************************************************************/
1977
1978 NTSTATUS internal_resolve_name(const char *name,
1979                                 int name_type,
1980                                 const char *sitename,
1981                                 struct ip_service **return_iplist,
1982                                 int *return_count,
1983                                 const char *resolve_order)
1984 {
1985         char *tok;
1986         const char *ptr;
1987         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1988         int i;
1989         TALLOC_CTX *frame = NULL;
1990
1991         *return_iplist = NULL;
1992         *return_count = 0;
1993
1994         DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1995                         name, name_type, sitename ? sitename : "(null)"));
1996
1997         if (is_ipaddress(name)) {
1998                 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
1999                                 NULL) {
2000                         DEBUG(0,("internal_resolve_name: malloc fail !\n"));
2001                         return NT_STATUS_NO_MEMORY;
2002                 }
2003
2004                 /* ignore the port here */
2005                 (*return_iplist)->port = PORT_NONE;
2006
2007                 /* if it's in the form of an IP address then get the lib to interpret it */
2008                 if (!interpret_string_addr(&(*return_iplist)->ss,
2009                                         name, AI_NUMERICHOST)) {
2010                         DEBUG(1,("internal_resolve_name: interpret_string_addr "
2011                                 "failed on %s\n",
2012                                 name));
2013                         SAFE_FREE(*return_iplist);
2014                         return NT_STATUS_INVALID_PARAMETER;
2015                 }
2016                 *return_count = 1;
2017                 return NT_STATUS_OK;
2018         }
2019
2020         /* Check name cache */
2021
2022         if (namecache_fetch(name, name_type, return_iplist, return_count)) {
2023                 /* This could be a negative response */
2024                 if (*return_count > 0) {
2025                         return NT_STATUS_OK;
2026                 } else {
2027                         return NT_STATUS_UNSUCCESSFUL;
2028                 }
2029         }
2030
2031         /* set the name resolution order */
2032
2033         if (strcmp( resolve_order, "NULL") == 0) {
2034                 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
2035                 return NT_STATUS_INVALID_PARAMETER;
2036         }
2037
2038         if (!resolve_order[0]) {
2039                 ptr = "host";
2040         } else {
2041                 ptr = resolve_order;
2042         }
2043
2044         /* iterate through the name resolution backends */
2045
2046         frame = talloc_stackframe();
2047         while (next_token_talloc(frame, &ptr, &tok, LIST_SEP)) {
2048                 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
2049                         status = resolve_hosts(name, name_type, return_iplist,
2050                                                return_count);
2051                         if (NT_STATUS_IS_OK(status)) {
2052                                 goto done;
2053                         }
2054                 } else if(strequal( tok, "kdc")) {
2055                         /* deal with KDC_NAME_TYPE names here.
2056                          * This will result in a SRV record lookup */
2057                         status = resolve_ads(name, KDC_NAME_TYPE, sitename,
2058                                              return_iplist, return_count);
2059                         if (NT_STATUS_IS_OK(status)) {
2060                                 /* Ensure we don't namecache
2061                                  * this with the KDC port. */
2062                                 name_type = KDC_NAME_TYPE;
2063                                 goto done;
2064                         }
2065                 } else if(strequal( tok, "ads")) {
2066                         /* deal with 0x1c and 0x1b names here.
2067                          * This will result in a SRV record lookup */
2068                         status = resolve_ads(name, name_type, sitename,
2069                                              return_iplist, return_count);
2070                         if (NT_STATUS_IS_OK(status)) {
2071                                 goto done;
2072                         }
2073                 } else if(strequal( tok, "lmhosts")) {
2074                         status = resolve_lmhosts(name, name_type,
2075                                                  return_iplist, return_count);
2076                         if (NT_STATUS_IS_OK(status)) {
2077                                 goto done;
2078                         }
2079                 } else if(strequal( tok, "wins")) {
2080                         /* don't resolve 1D via WINS */
2081                         if (name_type != 0x1D) {
2082                                 status = resolve_wins(name, name_type,
2083                                                       return_iplist,
2084                                                       return_count);
2085                                 if (NT_STATUS_IS_OK(status)) {
2086                                         goto done;
2087                                 }
2088                         }
2089                 } else if(strequal( tok, "bcast")) {
2090                         struct sockaddr_storage *ss_list;
2091                         status = name_resolve_bcast(
2092                                 name, name_type, talloc_tos(),
2093                                 &ss_list, return_count);
2094                         if (NT_STATUS_IS_OK(status)) {
2095                                 if (!convert_ss2service(return_iplist,
2096                                                         ss_list,
2097                                                         return_count)) {
2098                                         status = NT_STATUS_NO_MEMORY;
2099                                 }
2100                                 goto done;
2101                         }
2102                 } else {
2103                         DEBUG(0,("resolve_name: unknown name switch type %s\n",
2104                                 tok));
2105                 }
2106         }
2107
2108         /* All of the resolve_* functions above have returned false. */
2109
2110         TALLOC_FREE(frame);
2111         SAFE_FREE(*return_iplist);
2112         *return_count = 0;
2113
2114         return NT_STATUS_UNSUCCESSFUL;
2115
2116   done:
2117
2118         /* Remove duplicate entries.  Some queries, notably #1c (domain
2119         controllers) return the PDC in iplist[0] and then all domain
2120         controllers including the PDC in iplist[1..n].  Iterating over
2121         the iplist when the PDC is down will cause two sets of timeouts. */
2122
2123         if ( *return_count ) {
2124                 *return_count = remove_duplicate_addrs2(*return_iplist,
2125                                         *return_count );
2126         }
2127
2128         /* Save in name cache */
2129         if ( DEBUGLEVEL >= 100 ) {
2130                 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
2131                         char addr[INET6_ADDRSTRLEN];
2132                         print_sockaddr(addr, sizeof(addr),
2133                                         &(*return_iplist)[i].ss);
2134                         DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
2135                                         name,
2136                                         name_type,
2137                                         addr,
2138                                         (*return_iplist)[i].port));
2139                 }
2140         }
2141
2142         namecache_store(name, name_type, *return_count, *return_iplist);
2143
2144         /* Display some debugging info */
2145
2146         if ( DEBUGLEVEL >= 10 ) {
2147                 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
2148                                         *return_count));
2149
2150                 for (i = 0; i < *return_count; i++) {
2151                         char addr[INET6_ADDRSTRLEN];
2152                         print_sockaddr(addr, sizeof(addr),
2153                                         &(*return_iplist)[i].ss);
2154                         DEBUGADD(10, ("%s:%d ",
2155                                         addr,
2156                                         (*return_iplist)[i].port));
2157                 }
2158                 DEBUG(10, ("\n"));
2159         }
2160
2161         TALLOC_FREE(frame);
2162         return status;
2163 }
2164
2165 /********************************************************
2166  Internal interface to resolve a name into one IP address.
2167  Use this function if the string is either an IP address, DNS
2168  or host name or NetBIOS name. This uses the name switch in the
2169  smb.conf to determine the order of name resolution.
2170 *********************************************************/
2171
2172 bool resolve_name(const char *name,
2173                 struct sockaddr_storage *return_ss,
2174                 int name_type,
2175                 bool prefer_ipv4)
2176 {
2177         struct ip_service *ss_list = NULL;
2178         char *sitename = NULL;
2179         int count = 0;
2180
2181         if (is_ipaddress(name)) {
2182                 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
2183         }
2184
2185         sitename = sitename_fetch(lp_realm()); /* wild guess */
2186
2187         if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
2188                                                   &ss_list, &count,
2189                                                   lp_name_resolve_order()))) {
2190                 int i;
2191
2192                 if (prefer_ipv4) {
2193                         for (i=0; i<count; i++) {
2194                                 if (!is_zero_addr(&ss_list[i].ss) &&
2195                                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss) &&
2196                                                 (ss_list[i].ss.ss_family == AF_INET)) {
2197                                         *return_ss = ss_list[i].ss;
2198                                         SAFE_FREE(ss_list);
2199                                         SAFE_FREE(sitename);
2200                                         return True;
2201                                 }
2202                         }
2203                 }
2204
2205                 /* only return valid addresses for TCP connections */
2206                 for (i=0; i<count; i++) {
2207                         if (!is_zero_addr(&ss_list[i].ss) &&
2208                                         !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2209                                 *return_ss = ss_list[i].ss;
2210                                 SAFE_FREE(ss_list);
2211                                 SAFE_FREE(sitename);
2212                                 return True;
2213                         }
2214                 }
2215         }
2216
2217         SAFE_FREE(ss_list);
2218         SAFE_FREE(sitename);
2219         return False;
2220 }
2221
2222 /********************************************************
2223  Internal interface to resolve a name into a list of IP addresses.
2224  Use this function if the string is either an IP address, DNS
2225  or host name or NetBIOS name. This uses the name switch in the
2226  smb.conf to determine the order of name resolution.
2227 *********************************************************/
2228
2229 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
2230                 const char *name,
2231                 int name_type,
2232                 struct sockaddr_storage **return_ss_arr,
2233                 unsigned int *p_num_entries)
2234 {
2235         struct ip_service *ss_list = NULL;
2236         char *sitename = NULL;
2237         int count = 0;
2238         int i;
2239         unsigned int num_entries;
2240         NTSTATUS status;
2241
2242         *p_num_entries = 0;
2243         *return_ss_arr = NULL;
2244
2245         if (is_ipaddress(name)) {
2246                 *return_ss_arr = TALLOC_P(ctx, struct sockaddr_storage);
2247                 if (!*return_ss_arr) {
2248                         return NT_STATUS_NO_MEMORY;
2249                 }
2250                 if (!interpret_string_addr(*return_ss_arr, name, AI_NUMERICHOST)) {
2251                         TALLOC_FREE(*return_ss_arr);
2252                         return NT_STATUS_BAD_NETWORK_NAME;
2253                 }
2254                 *p_num_entries = 1;
2255                 return NT_STATUS_OK;
2256         }
2257
2258         sitename = sitename_fetch(lp_realm()); /* wild guess */
2259
2260         status = internal_resolve_name(name, name_type, sitename,
2261                                                   &ss_list, &count,
2262                                                   lp_name_resolve_order());
2263         SAFE_FREE(sitename);
2264
2265         if (!NT_STATUS_IS_OK(status)) {
2266                 return status;
2267         }
2268
2269         /* only return valid addresses for TCP connections */
2270         for (i=0, num_entries = 0; i<count; i++) {
2271                 if (!is_zero_addr(&ss_list[i].ss) &&
2272                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2273                         num_entries++;
2274                 }
2275         }
2276         if (num_entries == 0) {
2277                 SAFE_FREE(ss_list);
2278                 return NT_STATUS_BAD_NETWORK_NAME;
2279         }
2280
2281         *return_ss_arr = TALLOC_ARRAY(ctx,
2282                                 struct sockaddr_storage,
2283                                 num_entries);
2284         if (!(*return_ss_arr)) {
2285                 SAFE_FREE(ss_list);
2286                 return NT_STATUS_NO_MEMORY;
2287         }
2288
2289         for (i=0, num_entries = 0; i<count; i++) {
2290                 if (!is_zero_addr(&ss_list[i].ss) &&
2291                                 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2292                         (*return_ss_arr)[num_entries++] = ss_list[i].ss;
2293                 }
2294         }
2295
2296         status = NT_STATUS_OK;
2297         *p_num_entries = num_entries;
2298
2299         SAFE_FREE(ss_list);
2300         return NT_STATUS_OK;
2301 }
2302
2303 /********************************************************
2304  Find the IP address of the master browser or DMB for a workgroup.
2305 *********************************************************/
2306
2307 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
2308 {
2309         struct ip_service *ip_list = NULL;
2310         int count = 0;
2311         NTSTATUS status;
2312
2313         if (lp_disable_netbios()) {
2314                 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
2315                 return false;
2316         }
2317
2318         status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
2319                                        lp_name_resolve_order());
2320         if (NT_STATUS_IS_OK(status)) {
2321                 *master_ss = ip_list[0].ss;
2322                 SAFE_FREE(ip_list);
2323                 return true;
2324         }
2325
2326         status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
2327                                        lp_name_resolve_order());
2328         if (NT_STATUS_IS_OK(status)) {
2329                 *master_ss = ip_list[0].ss;
2330                 SAFE_FREE(ip_list);
2331                 return true;
2332         }
2333
2334         SAFE_FREE(ip_list);
2335         return false;
2336 }
2337
2338 /********************************************************
2339  Get the IP address list of the primary domain controller
2340  for a domain.
2341 *********************************************************/
2342
2343 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
2344 {
2345         struct ip_service *ip_list = NULL;
2346         int count = 0;
2347         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2348
2349         /* Look up #1B name */
2350
2351         if (lp_security() == SEC_ADS) {
2352                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2353                                                &count, "ads");
2354         }
2355
2356         if (!NT_STATUS_IS_OK(status) || count == 0) {
2357                 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2358                                                &count,
2359                                                lp_name_resolve_order());
2360                 if (!NT_STATUS_IS_OK(status)) {
2361                         return false;
2362                 }
2363         }
2364
2365         /* if we get more than 1 IP back we have to assume it is a
2366            multi-homed PDC and not a mess up */
2367
2368         if ( count > 1 ) {
2369                 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
2370                 sort_service_list(ip_list, count);
2371         }
2372
2373         *pss = ip_list[0].ss;
2374         SAFE_FREE(ip_list);
2375         return true;
2376 }
2377
2378 /* Private enum type for lookups. */
2379
2380 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
2381
2382 /********************************************************
2383  Get the IP address list of the domain controllers for
2384  a domain.
2385 *********************************************************/
2386
2387 static NTSTATUS get_dc_list(const char *domain,
2388                         const char *sitename,
2389                         struct ip_service **ip_list,
2390                         int *count,
2391                         enum dc_lookup_type lookup_type,
2392                         bool *ordered)
2393 {
2394         char *resolve_order = NULL;
2395         char *saf_servername = NULL;
2396         char *pserver = NULL;
2397         const char *p;
2398         char *port_str = NULL;
2399         int port;
2400         char *name;
2401         int num_addresses = 0;
2402         int  local_count, i, j;
2403         struct ip_service *return_iplist = NULL;
2404         struct ip_service *auto_ip_list = NULL;
2405         bool done_auto_lookup = false;
2406         int auto_count = 0;
2407         NTSTATUS status;
2408         TALLOC_CTX *ctx = talloc_init("get_dc_list");
2409
2410         *ip_list = NULL;
2411         *count = 0;
2412
2413         if (!ctx) {
2414                 return NT_STATUS_NO_MEMORY;
2415         }
2416
2417         *ordered = False;
2418
2419         /* if we are restricted to solely using DNS for looking
2420            up a domain controller, make sure that host lookups
2421            are enabled for the 'name resolve order'.  If host lookups
2422            are disabled and ads_only is True, then set the string to
2423            NULL. */
2424
2425         resolve_order = talloc_strdup(ctx, lp_name_resolve_order());
2426         if (!resolve_order) {
2427                 status = NT_STATUS_NO_MEMORY;
2428                 goto out;
2429         }
2430         strlower_m(resolve_order);
2431         if (lookup_type == DC_ADS_ONLY)  {
2432                 if (strstr( resolve_order, "host")) {
2433                         resolve_order = talloc_strdup(ctx, "ads");
2434
2435                         /* DNS SRV lookups used by the ads resolver
2436                            are already sorted by priority and weight */
2437                         *ordered = true;
2438                 } else {
2439                         resolve_order = talloc_strdup(ctx, "NULL");
2440                 }
2441         } else if (lookup_type == DC_KDC_ONLY) {
2442                 /* DNS SRV lookups used by the ads/kdc resolver
2443                    are already sorted by priority and weight */
2444                 *ordered = true;
2445                 resolve_order = talloc_strdup(ctx, "kdc");
2446         }
2447         if (!resolve_order) {
2448                 status = NT_STATUS_NO_MEMORY;
2449                 goto out;
2450         }
2451
2452         /* fetch the server we have affinity for.  Add the
2453            'password server' list to a search for our domain controllers */
2454
2455         saf_servername = saf_fetch( domain);
2456
2457         if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
2458                 pserver = talloc_asprintf(ctx, "%s, %s",
2459                         saf_servername ? saf_servername : "",
2460                         lp_passwordserver());
2461         } else {
2462                 pserver = talloc_asprintf(ctx, "%s, *",
2463                         saf_servername ? saf_servername : "");
2464         }
2465
2466         SAFE_FREE(saf_servername);
2467         if (!pserver) {
2468                 status = NT_STATUS_NO_MEMORY;
2469                 goto out;
2470         }
2471
2472         /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
2473
2474         if (!*pserver ) {
2475                 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
2476                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2477                                              count, resolve_order);
2478                 goto out;
2479         }
2480
2481         DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
2482
2483         /*
2484          * if '*' appears in the "password server" list then add
2485          * an auto lookup to the list of manually configured
2486          * DC's.  If any DC is listed by name, then the list should be
2487          * considered to be ordered
2488          */
2489
2490         p = pserver;
2491         while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2492                 if (!done_auto_lookup && strequal(name, "*")) {
2493                         status = internal_resolve_name(domain, 0x1C, sitename,
2494                                                        &auto_ip_list,
2495                                                        &auto_count,
2496                                                        resolve_order);
2497                         if (NT_STATUS_IS_OK(status)) {
2498                                 num_addresses += auto_count;
2499                         }
2500                         done_auto_lookup = true;
2501                         DEBUG(8,("Adding %d DC's from auto lookup\n",
2502                                                 auto_count));
2503                 } else  {
2504                         num_addresses++;
2505                 }
2506         }
2507
2508         /* if we have no addresses and haven't done the auto lookup, then
2509            just return the list of DC's.  Or maybe we just failed. */
2510
2511         if ((num_addresses == 0)) {
2512                 if (done_auto_lookup) {
2513                         DEBUG(4,("get_dc_list: no servers found\n"));
2514                         status = NT_STATUS_NO_LOGON_SERVERS;
2515                         goto out;
2516                 }
2517                 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2518                                              count, resolve_order);
2519                 goto out;
2520         }
2521
2522         if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
2523                                         num_addresses)) == NULL) {
2524                 DEBUG(3,("get_dc_list: malloc fail !\n"));
2525                 status = NT_STATUS_NO_MEMORY;
2526                 goto out;
2527         }
2528
2529         p = pserver;
2530         local_count = 0;
2531
2532         /* fill in the return list now with real IP's */
2533
2534         while ((local_count<num_addresses) &&
2535                         next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2536                 struct sockaddr_storage name_ss;
2537
2538                 /* copy any addersses from the auto lookup */
2539
2540                 if (strequal(name, "*")) {
2541                         for (j=0; j<auto_count; j++) {
2542                                 char addr[INET6_ADDRSTRLEN];
2543                                 print_sockaddr(addr,
2544                                                 sizeof(addr),
2545                                                 &auto_ip_list[j].ss);
2546                                 /* Check for and don't copy any
2547                                  * known bad DC IP's. */
2548                                 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
2549                                                 domain,
2550                                                 addr))) {
2551                                         DEBUG(5,("get_dc_list: "
2552                                                 "negative entry %s removed "
2553                                                 "from DC list\n",
2554                                                 addr));
2555                                         continue;
2556                                 }
2557                                 return_iplist[local_count].ss =
2558                                         auto_ip_list[j].ss;
2559                                 return_iplist[local_count].port =
2560                                         auto_ip_list[j].port;
2561                                 local_count++;
2562                         }
2563                         continue;
2564                 }
2565
2566                 /* added support for address:port syntax for ads
2567                  * (not that I think anyone will ever run the LDAP
2568                  * server in an AD domain on something other than
2569                  * port 389 */
2570
2571                 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
2572                 if ((port_str=strchr(name, ':')) != NULL) {
2573                         *port_str = '\0';
2574                         port_str++;
2575                         port = atoi(port_str);
2576                 }
2577
2578                 /* explicit lookup; resolve_name() will
2579                  * handle names & IP addresses */
2580                 if (resolve_name( name, &name_ss, 0x20, true )) {
2581                         char addr[INET6_ADDRSTRLEN];
2582                         print_sockaddr(addr,
2583                                         sizeof(addr),
2584                                         &name_ss);
2585
2586                         /* Check for and don't copy any known bad DC IP's. */
2587                         if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
2588                                                         addr)) ) {
2589                                 DEBUG(5,("get_dc_list: negative entry %s "
2590                                         "removed from DC list\n",
2591                                         name ));
2592                                 continue;
2593                         }
2594
2595                         return_iplist[local_count].ss = name_ss;
2596                         return_iplist[local_count].port = port;
2597                         local_count++;
2598                         *ordered = true;
2599                 }
2600         }
2601
2602         /* need to remove duplicates in the list if we have any
2603            explicit password servers */
2604
2605         if (local_count) {
2606                 local_count = remove_duplicate_addrs2(return_iplist,
2607                                 local_count );
2608         }
2609
2610         /* For DC's we always prioritize IPv4 due to W2K3 not
2611          * supporting LDAP, KRB5 or CLDAP over IPv6. */
2612
2613         if (local_count && return_iplist) {
2614                 prioritize_ipv4_list(return_iplist, local_count);
2615         }
2616
2617         if ( DEBUGLEVEL >= 4 ) {
2618                 DEBUG(4,("get_dc_list: returning %d ip addresses "
2619                                 "in an %sordered list\n",
2620                                 local_count,
2621                                 *ordered ? "":"un"));
2622                 DEBUG(4,("get_dc_list: "));
2623                 for ( i=0; i<local_count; i++ ) {
2624                         char addr[INET6_ADDRSTRLEN];
2625                         print_sockaddr(addr,
2626                                         sizeof(addr),
2627                                         &return_iplist[i].ss);
2628                         DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
2629                 }
2630                 DEBUGADD(4,("\n"));
2631         }
2632
2633         *ip_list = return_iplist;
2634         *count = local_count;
2635
2636         status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
2637
2638   out:
2639
2640         if (!NT_STATUS_IS_OK(status)) {
2641                 SAFE_FREE(return_iplist);
2642                 *ip_list = NULL;
2643                 *count = 0;
2644         }
2645
2646         SAFE_FREE(auto_ip_list);
2647         TALLOC_FREE(ctx);
2648         return status;
2649 }
2650
2651 /*********************************************************************
2652  Small wrapper function to get the DC list and sort it if neccessary.
2653 *********************************************************************/
2654
2655 NTSTATUS get_sorted_dc_list( const char *domain,
2656                         const char *sitename,
2657                         struct ip_service **ip_list,
2658                         int *count,
2659                         bool ads_only )
2660 {
2661         bool ordered = false;
2662         NTSTATUS status;
2663         enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
2664
2665         *ip_list = NULL;
2666         *count = 0;
2667
2668         DEBUG(8,("get_sorted_dc_list: attempting lookup "
2669                 "for name %s (sitename %s) using [%s]\n",
2670                 domain,
2671                 sitename ? sitename : "NULL",
2672                 (ads_only ? "ads" : lp_name_resolve_order())));
2673
2674         if (ads_only) {
2675                 lookup_type = DC_ADS_ONLY;
2676         }
2677
2678         status = get_dc_list(domain, sitename, ip_list,
2679                         count, lookup_type, &ordered);
2680         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS)
2681             && sitename) {
2682                 DEBUG(3,("get_sorted_dc_list: no server for name %s available"
2683                          " in site %s, fallback to all servers\n",
2684                          domain, sitename));
2685                 status = get_dc_list(domain, NULL, ip_list,
2686                                      count, lookup_type, &ordered);
2687         }
2688
2689         if (!NT_STATUS_IS_OK(status)) {
2690                 SAFE_FREE(*ip_list);
2691                 *count = 0;
2692                 return status;
2693         }
2694
2695         /* only sort if we don't already have an ordered list */
2696         if (!ordered) {
2697                 sort_service_list(*ip_list, *count);
2698         }
2699
2700         return NT_STATUS_OK;
2701 }
2702
2703 /*********************************************************************
2704  Get the KDC list - re-use all the logic in get_dc_list.
2705 *********************************************************************/
2706
2707 NTSTATUS get_kdc_list( const char *realm,
2708                         const char *sitename,
2709                         struct ip_service **ip_list,
2710                         int *count)
2711 {
2712         bool ordered;
2713         NTSTATUS status;
2714
2715         *count = 0;
2716         *ip_list = NULL;
2717
2718         status = get_dc_list(realm, sitename, ip_list,
2719                         count, DC_KDC_ONLY, &ordered);
2720
2721         if (!NT_STATUS_IS_OK(status)) {
2722                 SAFE_FREE(*ip_list);
2723                 *count = 0;
2724                 return status;
2725         }
2726
2727         /* only sort if we don't already have an ordered list */
2728         if ( !ordered ) {
2729                 sort_service_list(*ip_list, *count);
2730         }
2731
2732         return NT_STATUS_OK;
2733 }