s3: Tune broadcast namequeries for unique names
[Samba.git] / source3 / libsmb / namequery.c
blob4ce56e684e238b899fa981f1b3c19518117cf328
1 /*
2 Unix SMB/CIFS implementation.
3 name query routines
4 Copyright (C) Andrew Tridgell 1994-1998
5 Copyright (C) Jeremy Allison 2007.
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.
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.
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/>.
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"
29 /* nmbd.c sets this to True. */
30 bool global_in_nmbd = False;
32 /****************************
33 * SERVER AFFINITY ROUTINES *
34 ****************************/
36 /* Server affinity is the concept of preferring the last domain
37 controller with whom you had a successful conversation */
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
46 static char *saf_key(const char *domain)
48 char *keystr;
50 asprintf_strupper_m(&keystr, SAFKEY_FMT, domain);
52 return keystr;
55 static char *saf_join_key(const char *domain)
57 char *keystr;
59 asprintf_strupper_m(&keystr, SAFJOINKEY_FMT, domain);
61 return keystr;
64 /****************************************************************************
65 ****************************************************************************/
67 bool saf_store( const char *domain, const char *servername )
69 char *key;
70 time_t expire;
71 bool ret = False;
73 if ( !domain || !servername ) {
74 DEBUG(2,("saf_store: "
75 "Refusing to store empty domain or servername!\n"));
76 return False;
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;
85 key = saf_key( domain );
86 expire = time( NULL ) + lp_parm_int(-1, "saf","ttl", SAF_TTL);
88 DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
89 domain, servername, (unsigned int)expire ));
91 ret = gencache_set( key, servername, expire );
93 SAFE_FREE( key );
95 return ret;
98 bool saf_join_store( const char *domain, const char *servername )
100 char *key;
101 time_t expire;
102 bool ret = False;
104 if ( !domain || !servername ) {
105 DEBUG(2,("saf_join_store: Refusing to store empty domain or servername!\n"));
106 return False;
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;
114 key = saf_join_key( domain );
115 expire = time( NULL ) + lp_parm_int(-1, "saf","join ttl", SAFJOIN_TTL);
117 DEBUG(10,("saf_join_store: domain = [%s], server = [%s], expire = [%u]\n",
118 domain, servername, (unsigned int)expire ));
120 ret = gencache_set( key, servername, expire );
122 SAFE_FREE( key );
124 return ret;
127 bool saf_delete( const char *domain )
129 char *key;
130 bool ret = False;
132 if ( !domain ) {
133 DEBUG(2,("saf_delete: Refusing to delete empty domain\n"));
134 return False;
137 key = saf_join_key(domain);
138 ret = gencache_del(key);
139 SAFE_FREE(key);
141 if (ret) {
142 DEBUG(10,("saf_delete[join]: domain = [%s]\n", domain ));
145 key = saf_key(domain);
146 ret = gencache_del(key);
147 SAFE_FREE(key);
149 if (ret) {
150 DEBUG(10,("saf_delete: domain = [%s]\n", domain ));
153 return ret;
156 /****************************************************************************
157 ****************************************************************************/
159 char *saf_fetch( const char *domain )
161 char *server = NULL;
162 time_t timeout;
163 bool ret = False;
164 char *key = NULL;
166 if ( !domain || strlen(domain) == 0) {
167 DEBUG(2,("saf_fetch: Empty domain name!\n"));
168 return NULL;
171 key = saf_join_key( domain );
173 ret = gencache_get( key, &server, &timeout );
175 SAFE_FREE( key );
177 if ( ret ) {
178 DEBUG(5,("saf_fetch[join]: Returning \"%s\" for \"%s\" domain\n",
179 server, domain ));
180 return server;
183 key = saf_key( domain );
185 ret = gencache_get( key, &server, &timeout );
187 SAFE_FREE( key );
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 ));
197 return server;
200 /****************************************************************************
201 Generate a random trn_id.
202 ****************************************************************************/
204 static int generate_trn_id(void)
206 uint16 id;
208 generate_random_buffer((uint8 *)&id, sizeof(id));
210 return id % (unsigned)0x7FFF;
213 /****************************************************************************
214 Parse a node status response into an array of structures.
215 ****************************************************************************/
217 static struct node_status *parse_node_status(TALLOC_CTX *mem_ctx, char *p,
218 int *num_names,
219 struct node_status_extra *extra)
221 struct node_status *ret;
222 int i;
224 *num_names = CVAL(p,0);
226 if (*num_names == 0)
227 return NULL;
229 ret = TALLOC_ARRAY(mem_ctx, struct node_status,*num_names);
230 if (!ret)
231 return NULL;
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));
244 * Also, pick up the MAC address ...
246 if (extra) {
247 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
249 return ret;
252 struct sock_packet_read_state {
253 struct tevent_context *ev;
254 enum packet_type type;
255 int trn_id;
257 struct nb_packet_reader *reader;
258 struct tevent_req *reader_req;
260 int sock;
261 struct tevent_req *socket_req;
262 uint8_t buf[1024];
263 struct sockaddr_storage addr;
264 socklen_t addr_len;
266 bool (*validator)(struct packet_struct *p,
267 void *private_data);
268 void *private_data;
270 struct packet_struct *packet;
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);
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)
287 struct tevent_req *req;
288 struct sock_packet_read_state *state;
290 req = tevent_req_create(mem_ctx, &state,
291 struct sock_packet_read_state);
292 if (req == NULL) {
293 return NULL;
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;
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);
309 tevent_req_set_callback(
310 state->reader_req, sock_packet_read_got_packet, req);
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);
320 tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
321 req);
323 return req;
326 static int sock_packet_read_state_destructor(struct sock_packet_read_state *s)
328 if (s->packet != NULL) {
329 free_packet(s->packet);
330 s->packet = NULL;
332 return 0;
335 static void sock_packet_read_got_packet(struct tevent_req *subreq)
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;
343 status = nb_packet_read_recv(subreq, &state->packet);
345 TALLOC_FREE(state->reader_req);
347 if (!NT_STATUS_IS_OK(status)) {
348 if (state->socket_req != NULL) {
350 * Still waiting for socket
352 return;
355 * Both socket and packet reader failed
357 tevent_req_nterror(req, status);
358 return;
361 if ((state->validator != NULL) &&
362 !state->validator(state->packet, state->private_data)) {
363 DEBUG(10, ("validator failed\n"));
365 free_packet(state->packet);
366 state->packet = NULL;
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;
373 tevent_req_set_callback(
374 state->reader_req, sock_packet_read_got_packet, req);
375 return;
378 TALLOC_FREE(state->socket_req);
379 tevent_req_done(req);
382 static void sock_packet_read_got_socket(struct tevent_req *subreq)
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;
392 received = recvfrom_recv(subreq, &err);
394 TALLOC_FREE(state->socket_req);
396 if (received == -1) {
397 if (state->reader_req != NULL) {
399 * Still waiting for reader
401 return;
404 * Both socket and reader failed
406 tevent_req_nterror(req, map_nt_error_from_unix(err));
407 return;
409 if (state->addr.ss_family != AF_INET) {
410 goto retry;
412 in_addr = (struct sockaddr_in *)(void *)&state->addr;
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;
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;
427 if ((state->validator != NULL) &&
428 !state->validator(state->packet, state->private_data)) {
429 DEBUG(10, ("validator failed\n"));
430 goto retry;
433 tevent_req_done(req);
434 return;
436 retry:
437 if (state->packet != NULL) {
438 free_packet(state->packet);
439 state->packet = NULL;
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;
447 tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
448 req);
451 static NTSTATUS sock_packet_read_recv(struct tevent_req *req,
452 struct packet_struct **ppacket)
454 struct sock_packet_read_state *state = tevent_req_data(
455 req, struct sock_packet_read_state);
456 NTSTATUS status;
458 if (tevent_req_is_nterror(req, &status)) {
459 return status;
461 *ppacket = state->packet;
462 state->packet = NULL;
463 return NT_STATUS_OK;
466 struct nb_trans_state {
467 struct tevent_context *ev;
468 int sock;
469 struct nb_packet_reader *reader;
471 const struct sockaddr_storage *dst_addr;
472 uint8_t *buf;
473 size_t buflen;
474 enum packet_type type;
475 int trn_id;
477 bool (*validator)(struct packet_struct *p,
478 void *private_data);
479 void *private_data;
481 struct packet_struct *packet;
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);
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)
502 struct tevent_req *req, *subreq;
503 struct nb_trans_state *state;
505 req = tevent_req_create(mem_ctx, &state, struct nb_trans_state);
506 if (req == NULL) {
507 return NULL;
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;
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);
526 if (bcast) {
527 set_socket_options(state->sock,"SO_BROADCAST");
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);
534 tevent_req_set_callback(subreq, nb_trans_got_reader, req);
535 return req;
538 static int nb_trans_state_destructor(struct nb_trans_state *s)
540 if (s->sock != -1) {
541 close(s->sock);
542 s->sock = -1;
544 if (s->packet != NULL) {
545 free_packet(s->packet);
546 s->packet = NULL;
548 return 0;
551 static void nb_trans_got_reader(struct tevent_req *subreq)
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;
559 status = nb_packet_reader_recv(subreq, state, &state->reader);
560 TALLOC_FREE(subreq);
562 if (!NT_STATUS_IS_OK(status)) {
563 DEBUG(10, ("nmbd not around\n"));
564 state->reader = NULL;
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;
574 tevent_req_set_callback(subreq, nb_trans_done, req);
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;
581 tevent_req_set_callback(subreq, nb_trans_sent, req);
584 static void nb_trans_sent(struct tevent_req *subreq)
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;
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;
600 subreq = tevent_wakeup_send(state, state->ev,
601 timeval_current_ofs(1, 0));
602 if (tevent_req_nomem(subreq, req)) {
603 return;
605 tevent_req_set_callback(subreq, nb_trans_send_next, req);
608 static void nb_trans_send_next(struct tevent_req *subreq)
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;
616 ret = tevent_wakeup_recv(subreq);
617 TALLOC_FREE(subreq);
618 if (!ret) {
619 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
620 return;
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;
627 tevent_req_set_callback(subreq, nb_trans_sent, req);
630 static void nb_trans_done(struct tevent_req *subreq)
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;
638 status = sock_packet_read_recv(subreq, &state->packet);
639 TALLOC_FREE(subreq);
640 if (tevent_req_nterror(req, status)) {
641 return;
643 tevent_req_done(req);
646 static NTSTATUS nb_trans_recv(struct tevent_req *req,
647 struct packet_struct **ppacket)
649 struct nb_trans_state *state = tevent_req_data(
650 req, struct nb_trans_state);
651 NTSTATUS status;
653 if (tevent_req_is_nterror(req, &status)) {
654 return status;
656 *ppacket = state->packet;
657 state->packet = NULL;
658 return NT_STATUS_OK;
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 **************************************************************************/
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;
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);
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)
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;
691 req = tevent_req_create(mem_ctx, &state,
692 struct node_status_query_state);
693 if (req == NULL) {
694 return NULL;
696 talloc_set_destructor(state, node_status_query_state_destructor);
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);
704 state->addr = *addr;
705 in_addr = (struct sockaddr_in *)(void *)&state->addr;
706 in_addr->sin_port = htons(NMB_PORT);
708 if (!interpret_string_addr(&state->my_addr, lp_socket_address(),
709 AI_NUMERICHOST|AI_PASSIVE)) {
710 zero_sockaddr(&state->my_addr);
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;
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);
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);
747 if (!tevent_req_set_endtime(req, ev, timeval_current_ofs(10, 0))) {
748 return tevent_req_post(req, ev);
750 tevent_req_set_callback(subreq, node_status_query_done, req);
751 return req;
754 static bool node_status_query_validator(struct packet_struct *p,
755 void *private_data)
757 struct nmb_packet *nmb = &p->packet.nmb;
758 debug_nmb_packet(p);
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) {
766 * XXXX what do we do with this? could be a redirect,
767 * but we'll discard it for the moment
769 return false;
771 return true;
774 static int node_status_query_state_destructor(
775 struct node_status_query_state *s)
777 if (s->packet != NULL) {
778 free_packet(s->packet);
779 s->packet = NULL;
781 return 0;
784 static void node_status_query_done(struct tevent_req *subreq)
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;
792 status = nb_trans_recv(subreq, &state->packet);
793 TALLOC_FREE(subreq);
794 if (tevent_req_nterror(req, status)) {
795 return;
797 tevent_req_done(req);
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)
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;
811 if (tevent_req_is_nterror(req, &status)) {
812 return status;
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;
820 *pnode_status = node_status;
821 *pnum_names = num_names;
822 return NT_STATUS_OK;
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)
831 TALLOC_CTX *frame = talloc_stackframe();
832 struct tevent_context *ev;
833 struct tevent_req *req;
834 NTSTATUS status = NT_STATUS_NO_MEMORY;
836 ev = tevent_context_init(frame);
837 if (ev == NULL) {
838 goto fail;
840 req = node_status_query_send(ev, ev, name, addr);
841 if (req == NULL) {
842 goto fail;
844 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
845 goto fail;
847 status = node_status_query_recv(req, mem_ctx, pnode_status,
848 pnum_names, extra);
849 fail:
850 TALLOC_FREE(frame);
851 return status;
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 **************************************************************************/
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)
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;
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;
879 print_sockaddr(addr, sizeof(addr), to_ss);
881 DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
882 q_type, addr));
884 /* Check the cache first. */
886 if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
887 return True;
890 if (to_ss->ss_family != AF_INET) {
891 /* Can't do node status to IPv6 */
892 return false;
895 if (!interpret_string_addr(&ss, lp_socket_address(),
896 AI_NUMERICHOST|AI_PASSIVE)) {
897 zero_sockaddr(&ss);
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;
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;
913 if (i == count)
914 goto done;
916 pull_ascii_nstring(name, sizeof(fstring), addrs[i].name);
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 */
922 if ( q_type != 0x1c ) {
923 namecache_status_store(q_name, q_type, type, to_ss, name);
926 result = true;
928 done:
929 TALLOC_FREE(addrs);
931 DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
933 if (result)
934 DEBUGADD(10, (", name %s ip address is %s", name, addr));
936 DEBUG(10, ("\n"));
938 return result;
942 comparison function used by sort_addr_list
945 static int addr_compare(const struct sockaddr_storage *ss1,
946 const struct sockaddr_storage *ss2)
948 int max_bits1=0, max_bits2=0;
949 int num_interfaces = iface_count();
950 int i;
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;
961 /* Here we know both addresses are of the same
962 * family. */
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;
972 if (pss->ss_family != ss1->ss_family) {
973 /* Ignore interfaces of the wrong type. */
974 continue;
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;
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;
995 #endif
996 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
997 continue;
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);
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;
1013 if (iface_local((struct sockaddr *)ss2)) {
1014 if (ss2->ss_family == AF_INET) {
1015 max_bits2 += 32;
1016 } else {
1017 max_bits2 += 128;
1020 return max_bits2 - max_bits1;
1023 /*******************************************************************
1024 compare 2 ldap IPs by nearness to our interfaces - used in qsort
1025 *******************************************************************/
1027 int ip_service_compare(struct ip_service *ss1, struct ip_service *ss2)
1029 int result;
1031 if ((result = addr_compare(&ss1->ss, &ss2->ss)) != 0) {
1032 return result;
1035 if (ss1->port > ss2->port) {
1036 return 1;
1039 if (ss1->port < ss2->port) {
1040 return -1;
1043 return 0;
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
1052 static void sort_addr_list(struct sockaddr_storage *sslist, int count)
1054 if (count <= 1) {
1055 return;
1058 TYPESAFE_QSORT(sslist, count, addr_compare);
1061 static void sort_service_list(struct ip_service *servlist, int count)
1063 if (count <= 1) {
1064 return;
1067 TYPESAFE_QSORT(servlist, count, ip_service_compare);
1070 /**********************************************************************
1071 Remove any duplicate address/port pairs in the list
1072 *********************************************************************/
1074 static int remove_duplicate_addrs2(struct ip_service *iplist, int count )
1076 int i, j;
1078 DEBUG(10,("remove_duplicate_addrs2: "
1079 "looking for duplicate address/port pairs\n"));
1081 /* one loop to remove duplicates */
1082 for ( i=0; i<count; i++ ) {
1083 if ( is_zero_addr(&iplist[i].ss)) {
1084 continue;
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);
1095 /* one loop to clean up any holes we left */
1096 /* first ip should never be a zero_ip() */
1097 for (i = 0; i<count; ) {
1098 if (is_zero_addr(&iplist[i].ss) ) {
1099 if (i != count-1) {
1100 memmove(&iplist[i], &iplist[i+1],
1101 (count - i - 1)*sizeof(iplist[i]));
1103 count--;
1104 continue;
1106 i++;
1109 return count;
1112 static bool prioritize_ipv4_list(struct ip_service *iplist, int count)
1114 TALLOC_CTX *frame = talloc_stackframe();
1115 struct ip_service *iplist_new = TALLOC_ARRAY(frame, struct ip_service, count);
1116 int i, j;
1118 if (iplist_new == NULL) {
1119 TALLOC_FREE(frame);
1120 return false;
1123 j = 0;
1125 /* Copy IPv4 first. */
1126 for (i = 0; i < count; i++) {
1127 if (iplist[i].ss.ss_family == AF_INET) {
1128 iplist_new[j++] = iplist[i];
1132 /* Copy IPv6. */
1133 for (i = 0; i < count; i++) {
1134 if (iplist[i].ss.ss_family != AF_INET) {
1135 iplist_new[j++] = iplist[i];
1139 memcpy(iplist, iplist_new, sizeof(struct ip_service)*count);
1140 TALLOC_FREE(frame);
1141 return true;
1144 /****************************************************************************
1145 Do a netbios name query to find someones IP.
1146 Returns an array of IP addresses or NULL if none.
1147 *count will be set to the number of addresses returned.
1148 *timed_out is set if we failed by timing out
1149 ****************************************************************************/
1151 struct name_query_state {
1152 struct sockaddr_storage my_addr;
1153 struct sockaddr_storage addr;
1154 bool bcast;
1157 uint8_t buf[1024];
1158 ssize_t buflen;
1160 NTSTATUS validate_error;
1161 uint8_t flags;
1163 struct sockaddr_storage *addrs;
1164 int num_addrs;
1167 static bool name_query_validator(struct packet_struct *p, void *private_data);
1168 static void name_query_done(struct tevent_req *subreq);
1170 struct tevent_req *name_query_send(TALLOC_CTX *mem_ctx,
1171 struct tevent_context *ev,
1172 const char *name, int name_type,
1173 bool bcast, bool recurse,
1174 const struct sockaddr_storage *addr)
1176 struct tevent_req *req, *subreq;
1177 struct name_query_state *state;
1178 struct packet_struct p;
1179 struct nmb_packet *nmb = &p.packet.nmb;
1180 struct sockaddr_in *in_addr;
1182 req = tevent_req_create(mem_ctx, &state, struct name_query_state);
1183 if (req == NULL) {
1184 return NULL;
1186 state->bcast = bcast;
1188 if (addr->ss_family != AF_INET) {
1189 /* Can't do node status to IPv6 */
1190 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
1191 return tevent_req_post(req, ev);
1194 if (lp_disable_netbios()) {
1195 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
1196 name, name_type));
1197 tevent_req_nterror(req, NT_STATUS_NOT_SUPPORTED);
1198 return tevent_req_post(req, ev);
1201 state->addr = *addr;
1202 in_addr = (struct sockaddr_in *)(void *)&state->addr;
1203 in_addr->sin_port = htons(NMB_PORT);
1205 if (!interpret_string_addr(&state->my_addr, lp_socket_address(),
1206 AI_NUMERICHOST|AI_PASSIVE)) {
1207 zero_sockaddr(&state->my_addr);
1210 ZERO_STRUCT(p);
1211 nmb->header.name_trn_id = generate_trn_id();
1212 nmb->header.opcode = 0;
1213 nmb->header.response = false;
1214 nmb->header.nm_flags.bcast = bcast;
1215 nmb->header.nm_flags.recursion_available = false;
1216 nmb->header.nm_flags.recursion_desired = recurse;
1217 nmb->header.nm_flags.trunc = false;
1218 nmb->header.nm_flags.authoritative = false;
1219 nmb->header.rcode = 0;
1220 nmb->header.qdcount = 1;
1221 nmb->header.ancount = 0;
1222 nmb->header.nscount = 0;
1223 nmb->header.arcount = 0;
1225 make_nmb_name(&nmb->question.question_name,name,name_type);
1227 nmb->question.question_type = 0x20;
1228 nmb->question.question_class = 0x1;
1230 state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
1231 &p);
1232 if (state->buflen == 0) {
1233 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1234 DEBUG(10, ("build_packet failed\n"));
1235 return tevent_req_post(req, ev);
1238 subreq = nb_trans_send(state, ev, &state->my_addr, &state->addr, bcast,
1239 state->buf, state->buflen,
1240 NMB_PACKET, nmb->header.name_trn_id,
1241 name_query_validator, state);
1242 if (tevent_req_nomem(subreq, req)) {
1243 DEBUG(10, ("nb_trans_send failed\n"));
1244 return tevent_req_post(req, ev);
1246 tevent_req_set_callback(subreq, name_query_done, req);
1247 return req;
1250 static bool name_query_validator(struct packet_struct *p, void *private_data)
1252 struct name_query_state *state = talloc_get_type_abort(
1253 private_data, struct name_query_state);
1254 struct nmb_packet *nmb = &p->packet.nmb;
1255 struct sockaddr_storage *tmp_addrs;
1256 bool got_unique_netbios_name = false;
1257 int i;
1259 debug_nmb_packet(p);
1262 * If we get a Negative Name Query Response from a WINS
1263 * server, we should report it and give up.
1265 if( 0 == nmb->header.opcode /* A query response */
1266 && !state->bcast /* from a WINS server */
1267 && nmb->header.rcode /* Error returned */
1270 if( DEBUGLVL( 3 ) ) {
1271 /* Only executed if DEBUGLEVEL >= 3 */
1272 dbgtext( "Negative name query "
1273 "response, rcode 0x%02x: ",
1274 nmb->header.rcode );
1275 switch( nmb->header.rcode ) {
1276 case 0x01:
1277 dbgtext("Request was invalidly formatted.\n");
1278 break;
1279 case 0x02:
1280 dbgtext("Problem with NBNS, cannot process "
1281 "name.\n");
1282 break;
1283 case 0x03:
1284 dbgtext("The name requested does not "
1285 "exist.\n");
1286 break;
1287 case 0x04:
1288 dbgtext("Unsupported request error.\n");
1289 break;
1290 case 0x05:
1291 dbgtext("Query refused error.\n");
1292 break;
1293 default:
1294 dbgtext("Unrecognized error code.\n" );
1295 break;
1300 * We accept this packet as valid, but tell the upper
1301 * layers that it's a negative response.
1303 state->validate_error = NT_STATUS_NOT_FOUND;
1304 return true;
1307 if (nmb->header.opcode != 0 ||
1308 nmb->header.nm_flags.bcast ||
1309 nmb->header.rcode ||
1310 !nmb->header.ancount) {
1312 * XXXX what do we do with this? Could be a redirect,
1313 * but we'll discard it for the moment.
1315 return false;
1318 tmp_addrs = TALLOC_REALLOC_ARRAY(
1319 state, state->addrs, struct sockaddr_storage,
1320 state->num_addrs + nmb->answers->rdlength/6);
1321 if (tmp_addrs == NULL) {
1322 state->validate_error = NT_STATUS_NO_MEMORY;
1323 return true;
1325 state->addrs = tmp_addrs;
1327 DEBUG(2,("Got a positive name query response "
1328 "from %s ( ", inet_ntoa(p->ip)));
1330 for (i=0; i<nmb->answers->rdlength/6; i++) {
1331 uint16_t flags;
1332 struct in_addr ip;
1334 flags = RSVAL(&nmb->answers->rdata[i*6], 0);
1335 got_unique_netbios_name |= ((flags & 0x8000) == 0);
1337 putip((char *)&ip,&nmb->answers->rdata[2+i*6]);
1338 in_addr_to_sockaddr_storage(
1339 &state->addrs[state->num_addrs], ip);
1340 DEBUGADD(2,("%s ",inet_ntoa(ip)));
1341 state->num_addrs += 1;
1343 DEBUGADD(2,(")\n"));
1345 /* We add the flags back ... */
1346 if (nmb->header.response)
1347 state->flags |= NM_FLAGS_RS;
1348 if (nmb->header.nm_flags.authoritative)
1349 state->flags |= NM_FLAGS_AA;
1350 if (nmb->header.nm_flags.trunc)
1351 state->flags |= NM_FLAGS_TC;
1352 if (nmb->header.nm_flags.recursion_desired)
1353 state->flags |= NM_FLAGS_RD;
1354 if (nmb->header.nm_flags.recursion_available)
1355 state->flags |= NM_FLAGS_RA;
1356 if (nmb->header.nm_flags.bcast)
1357 state->flags |= NM_FLAGS_B;
1359 if (state->bcast) {
1361 * We have to collect all entries coming in from broadcast
1362 * queries. If we got a unique name, we're done.
1364 return got_unique_netbios_name;
1367 * WINS responses are accepted when they are received
1369 return true;
1372 static void name_query_done(struct tevent_req *subreq)
1374 struct tevent_req *req = tevent_req_callback_data(
1375 subreq, struct tevent_req);
1376 struct name_query_state *state = tevent_req_data(
1377 req, struct name_query_state);
1378 NTSTATUS status;
1379 struct packet_struct *p = NULL;
1381 status = nb_trans_recv(subreq, &p);
1382 TALLOC_FREE(subreq);
1383 if (tevent_req_nterror(req, status)) {
1384 return;
1386 if (!NT_STATUS_IS_OK(state->validate_error)) {
1387 tevent_req_nterror(req, state->validate_error);
1388 return;
1390 if (p != NULL) {
1392 * Free the packet here, we've collected the response in the
1393 * validator
1395 free_packet(p);
1397 tevent_req_done(req);
1400 NTSTATUS name_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1401 struct sockaddr_storage **addrs, int *num_addrs,
1402 uint8_t *flags)
1404 struct name_query_state *state = tevent_req_data(
1405 req, struct name_query_state);
1406 NTSTATUS status;
1408 if (tevent_req_is_nterror(req, &status)
1409 && !NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
1410 return status;
1412 if (state->num_addrs == 0) {
1413 return NT_STATUS_NOT_FOUND;
1415 *addrs = talloc_move(mem_ctx, &state->addrs);
1416 sort_addr_list(*addrs, state->num_addrs);
1417 *num_addrs = state->num_addrs;
1418 if (flags != NULL) {
1419 *flags = state->flags;
1421 return NT_STATUS_OK;
1424 NTSTATUS name_query(const char *name, int name_type,
1425 bool bcast, bool recurse,
1426 const struct sockaddr_storage *to_ss,
1427 TALLOC_CTX *mem_ctx,
1428 struct sockaddr_storage **addrs,
1429 int *num_addrs, uint8_t *flags)
1431 TALLOC_CTX *frame = talloc_stackframe();
1432 struct tevent_context *ev;
1433 struct tevent_req *req;
1434 struct timeval timeout;
1435 NTSTATUS status = NT_STATUS_NO_MEMORY;
1437 ev = tevent_context_init(frame);
1438 if (ev == NULL) {
1439 goto fail;
1441 req = name_query_send(ev, ev, name, name_type, bcast, recurse, to_ss);
1442 if (req == NULL) {
1443 goto fail;
1445 if (bcast) {
1446 timeout = timeval_current_ofs(0, 250000);
1447 } else {
1448 timeout = timeval_current_ofs(2, 0);
1450 if (!tevent_req_set_endtime(req, ev, timeout)) {
1451 goto fail;
1453 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
1454 goto fail;
1456 status = name_query_recv(req, mem_ctx, addrs, num_addrs, flags);
1457 fail:
1458 TALLOC_FREE(frame);
1459 return status;
1462 /********************************************************
1463 convert an array if struct sockaddr_storage to struct ip_service
1464 return false on failure. Port is set to PORT_NONE;
1465 *********************************************************/
1467 static bool convert_ss2service(struct ip_service **return_iplist,
1468 const struct sockaddr_storage *ss_list,
1469 int count)
1471 int i;
1473 if ( count==0 || !ss_list )
1474 return False;
1476 /* copy the ip address; port will be PORT_NONE */
1477 if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) ==
1478 NULL) {
1479 DEBUG(0,("convert_ip2service: malloc failed "
1480 "for %d enetries!\n", count ));
1481 return False;
1484 for ( i=0; i<count; i++ ) {
1485 (*return_iplist)[i].ss = ss_list[i];
1486 (*return_iplist)[i].port = PORT_NONE;
1489 return true;
1492 /********************************************************
1493 Resolve via "bcast" method.
1494 *********************************************************/
1496 NTSTATUS name_resolve_bcast(const char *name,
1497 int name_type,
1498 TALLOC_CTX *mem_ctx,
1499 struct sockaddr_storage **return_iplist,
1500 int *return_count)
1502 int i;
1503 int num_interfaces = iface_count();
1504 struct sockaddr_storage *ss_list;
1505 NTSTATUS status = NT_STATUS_NOT_FOUND;
1507 if (lp_disable_netbios()) {
1508 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n",
1509 name, name_type));
1510 return NT_STATUS_INVALID_PARAMETER;
1513 *return_iplist = NULL;
1514 *return_count = 0;
1517 * "bcast" means do a broadcast lookup on all the local interfaces.
1520 DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup "
1521 "for name %s<0x%x>\n", name, name_type));
1524 * Lookup the name on all the interfaces, return on
1525 * the first successful match.
1527 for( i = num_interfaces-1; i >= 0; i--) {
1528 const struct sockaddr_storage *pss = iface_n_bcast(i);
1530 /* Done this way to fix compiler error on IRIX 5.x */
1531 if (!pss) {
1532 continue;
1534 status = name_query(name, name_type, true, true, pss,
1535 talloc_tos(), &ss_list, return_count,
1536 NULL);
1537 if (NT_STATUS_IS_OK(status)) {
1538 goto success;
1542 /* failed - no response */
1544 return status;
1546 success:
1547 *return_iplist = ss_list;
1548 return status;
1551 /********************************************************
1552 Resolve via "wins" method.
1553 *********************************************************/
1555 NTSTATUS resolve_wins(const char *name,
1556 int name_type,
1557 struct ip_service **return_iplist,
1558 int *return_count)
1560 int t, i;
1561 char **wins_tags;
1562 struct sockaddr_storage src_ss, *ss_list = NULL;
1563 struct in_addr src_ip;
1564 NTSTATUS status;
1566 if (lp_disable_netbios()) {
1567 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n",
1568 name, name_type));
1569 return NT_STATUS_INVALID_PARAMETER;
1572 *return_iplist = NULL;
1573 *return_count = 0;
1575 DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n",
1576 name, name_type));
1578 if (wins_srv_count() < 1) {
1579 DEBUG(3,("resolve_wins: WINS server resolution selected "
1580 "and no WINS servers listed.\n"));
1581 return NT_STATUS_INVALID_PARAMETER;
1584 /* we try a lookup on each of the WINS tags in turn */
1585 wins_tags = wins_srv_tags();
1587 if (!wins_tags) {
1588 /* huh? no tags?? give up in disgust */
1589 return NT_STATUS_INVALID_PARAMETER;
1592 /* the address we will be sending from */
1593 if (!interpret_string_addr(&src_ss, lp_socket_address(),
1594 AI_NUMERICHOST|AI_PASSIVE)) {
1595 zero_sockaddr(&src_ss);
1598 if (src_ss.ss_family != AF_INET) {
1599 char addr[INET6_ADDRSTRLEN];
1600 print_sockaddr(addr, sizeof(addr), &src_ss);
1601 DEBUG(3,("resolve_wins: cannot receive WINS replies "
1602 "on IPv6 address %s\n",
1603 addr));
1604 wins_srv_tags_free(wins_tags);
1605 return NT_STATUS_INVALID_PARAMETER;
1608 src_ip = ((struct sockaddr_in *)&src_ss)->sin_addr;
1610 /* in the worst case we will try every wins server with every
1611 tag! */
1612 for (t=0; wins_tags && wins_tags[t]; t++) {
1613 int srv_count = wins_srv_count_tag(wins_tags[t]);
1614 for (i=0; i<srv_count; i++) {
1615 struct sockaddr_storage wins_ss;
1616 struct in_addr wins_ip;
1618 wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
1620 if (global_in_nmbd && ismyip_v4(wins_ip)) {
1621 /* yikes! we'll loop forever */
1622 continue;
1625 /* skip any that have been unresponsive lately */
1626 if (wins_srv_is_dead(wins_ip, src_ip)) {
1627 continue;
1630 DEBUG(3,("resolve_wins: using WINS server %s "
1631 "and tag '%s'\n",
1632 inet_ntoa(wins_ip), wins_tags[t]));
1634 in_addr_to_sockaddr_storage(&wins_ss, wins_ip);
1635 status = name_query(name,
1636 name_type,
1637 false,
1638 true,
1639 &wins_ss,
1640 talloc_tos(),
1641 &ss_list,
1642 return_count,
1643 NULL);
1645 /* exit loop if we got a list of addresses */
1647 if (NT_STATUS_IS_OK(status)) {
1648 goto success;
1651 if (NT_STATUS_EQUAL(status,
1652 NT_STATUS_IO_TIMEOUT)) {
1653 /* Timed out waiting for WINS server to
1654 * respond.
1655 * Mark it dead. */
1656 wins_srv_died(wins_ip, src_ip);
1657 } else {
1658 /* The name definitely isn't in this
1659 group of WINS servers.
1660 goto the next group */
1661 break;
1666 wins_srv_tags_free(wins_tags);
1667 return NT_STATUS_NO_LOGON_SERVERS;
1669 success:
1671 status = NT_STATUS_OK;
1672 if (!convert_ss2service(return_iplist, ss_list, *return_count))
1673 status = NT_STATUS_INVALID_PARAMETER;
1675 TALLOC_FREE(ss_list);
1676 wins_srv_tags_free(wins_tags);
1678 return status;
1681 /********************************************************
1682 Resolve via "lmhosts" method.
1683 *********************************************************/
1685 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
1686 struct ip_service **return_iplist,
1687 int *return_count)
1690 * "lmhosts" means parse the local lmhosts file.
1692 struct sockaddr_storage *ss_list;
1693 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1694 TALLOC_CTX *ctx = NULL;
1696 *return_iplist = NULL;
1697 *return_count = 0;
1699 DEBUG(3,("resolve_lmhosts: "
1700 "Attempting lmhosts lookup for name %s<0x%x>\n",
1701 name, name_type));
1703 ctx = talloc_init("resolve_lmhosts");
1704 if (!ctx) {
1705 return NT_STATUS_NO_MEMORY;
1708 status = resolve_lmhosts_file_as_sockaddr(get_dyn_LMHOSTSFILE(),
1709 name, name_type,
1710 ctx,
1711 &ss_list,
1712 return_count);
1713 if (NT_STATUS_IS_OK(status)) {
1714 if (convert_ss2service(return_iplist,
1715 ss_list,
1716 *return_count)) {
1717 talloc_free(ctx);
1718 return NT_STATUS_OK;
1719 } else {
1720 talloc_free(ctx);
1721 return NT_STATUS_NO_MEMORY;
1724 talloc_free(ctx);
1725 return status;
1729 /********************************************************
1730 Resolve via "hosts" method.
1731 *********************************************************/
1733 static NTSTATUS resolve_hosts(const char *name, int name_type,
1734 struct ip_service **return_iplist,
1735 int *return_count)
1738 * "host" means do a localhost, or dns lookup.
1740 struct addrinfo hints;
1741 struct addrinfo *ailist = NULL;
1742 struct addrinfo *res = NULL;
1743 int ret = -1;
1744 int i = 0;
1745 const char *dns_hosts_file;
1747 if ( name_type != 0x20 && name_type != 0x0) {
1748 DEBUG(5, ("resolve_hosts: not appropriate "
1749 "for name type <0x%x>\n",
1750 name_type));
1751 return NT_STATUS_INVALID_PARAMETER;
1754 *return_iplist = NULL;
1755 *return_count = 0;
1757 DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
1758 name, name_type));
1760 ZERO_STRUCT(hints);
1761 /* By default make sure it supports TCP. */
1762 hints.ai_socktype = SOCK_STREAM;
1763 hints.ai_flags = AI_ADDRCONFIG;
1765 #if !defined(HAVE_IPV6)
1766 /* Unless we have IPv6, we really only want IPv4 addresses back. */
1767 hints.ai_family = AF_INET;
1768 #endif
1770 dns_hosts_file = lp_parm_const_string(-1, "resolv", "host file", NULL);
1771 if (dns_hosts_file) {
1772 struct sockaddr_storage *ss_list;
1773 NTSTATUS status;
1774 TALLOC_CTX *ctx = talloc_stackframe();
1775 if (!ctx) {
1776 return NT_STATUS_NO_MEMORY;
1779 status = resolve_dns_hosts_file_as_sockaddr(dns_hosts_file, name, false,
1780 ctx, &ss_list, return_count);
1781 if (NT_STATUS_IS_OK(status)) {
1782 if (convert_ss2service(return_iplist,
1783 ss_list,
1784 *return_count)) {
1785 talloc_free(ctx);
1786 return NT_STATUS_OK;
1787 } else {
1788 talloc_free(ctx);
1789 return NT_STATUS_NO_MEMORY;
1792 talloc_free(ctx);
1793 return NT_STATUS_UNSUCCESSFUL;
1796 ret = getaddrinfo(name,
1797 NULL,
1798 &hints,
1799 &ailist);
1800 if (ret) {
1801 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1802 name,
1803 gai_strerror(ret) ));
1806 for (res = ailist; res; res = res->ai_next) {
1807 struct sockaddr_storage ss;
1809 if (!res->ai_addr || res->ai_addrlen == 0) {
1810 continue;
1813 ZERO_STRUCT(ss);
1814 memcpy(&ss, res->ai_addr, res->ai_addrlen);
1816 *return_count += 1;
1818 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1819 struct ip_service,
1820 *return_count);
1821 if (!*return_iplist) {
1822 DEBUG(3,("resolve_hosts: malloc fail !\n"));
1823 freeaddrinfo(ailist);
1824 return NT_STATUS_NO_MEMORY;
1826 (*return_iplist)[i].ss = ss;
1827 (*return_iplist)[i].port = PORT_NONE;
1828 i++;
1830 if (ailist) {
1831 freeaddrinfo(ailist);
1833 if (*return_count) {
1834 return NT_STATUS_OK;
1836 return NT_STATUS_UNSUCCESSFUL;
1839 /********************************************************
1840 Resolve via "ADS" method.
1841 *********************************************************/
1843 /* Special name type used to cause a _kerberos DNS lookup. */
1844 #define KDC_NAME_TYPE 0xDCDC
1846 static NTSTATUS resolve_ads(const char *name,
1847 int name_type,
1848 const char *sitename,
1849 struct ip_service **return_iplist,
1850 int *return_count)
1852 int i, j;
1853 NTSTATUS status;
1854 TALLOC_CTX *ctx;
1855 struct dns_rr_srv *dcs = NULL;
1856 int numdcs = 0;
1857 int numaddrs = 0;
1859 if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1860 (name_type != 0x1b)) {
1861 return NT_STATUS_INVALID_PARAMETER;
1864 if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1865 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1866 return NT_STATUS_NO_MEMORY;
1869 /* The DNS code needs fixing to find IPv6 addresses... JRA. */
1871 switch (name_type) {
1872 case 0x1b:
1873 DEBUG(5,("resolve_ads: Attempting to resolve "
1874 "PDC for %s using DNS\n", name));
1875 status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1876 break;
1878 case 0x1c:
1879 DEBUG(5,("resolve_ads: Attempting to resolve "
1880 "DCs for %s using DNS\n", name));
1881 status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1882 &numdcs);
1883 break;
1884 case KDC_NAME_TYPE:
1885 DEBUG(5,("resolve_ads: Attempting to resolve "
1886 "KDCs for %s using DNS\n", name));
1887 status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1888 &numdcs);
1889 break;
1890 default:
1891 status = NT_STATUS_INVALID_PARAMETER;
1892 break;
1895 if ( !NT_STATUS_IS_OK( status ) ) {
1896 talloc_destroy(ctx);
1897 return status;
1900 for (i=0;i<numdcs;i++) {
1901 numaddrs += MAX(dcs[i].num_ips,1);
1904 if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
1905 NULL ) {
1906 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
1907 numaddrs ));
1908 talloc_destroy(ctx);
1909 return NT_STATUS_NO_MEMORY;
1912 /* now unroll the list of IP addresses */
1914 *return_count = 0;
1915 i = 0;
1916 j = 0;
1917 while ( i < numdcs && (*return_count<numaddrs) ) {
1918 struct ip_service *r = &(*return_iplist)[*return_count];
1920 r->port = dcs[i].port;
1922 /* If we don't have an IP list for a name, lookup it up */
1924 if (!dcs[i].ss_s) {
1925 interpret_string_addr(&r->ss, dcs[i].hostname, 0);
1926 i++;
1927 j = 0;
1928 } else {
1929 /* use the IP addresses from the SRV sresponse */
1931 if ( j >= dcs[i].num_ips ) {
1932 i++;
1933 j = 0;
1934 continue;
1937 r->ss = dcs[i].ss_s[j];
1938 j++;
1941 /* make sure it is a valid IP. I considered checking the
1942 * negative connection cache, but this is the wrong place
1943 * for it. Maybe only as a hack. After think about it, if
1944 * all of the IP addresses returned from DNS are dead, what
1945 * hope does a netbios name lookup have ? The standard reason
1946 * for falling back to netbios lookups is that our DNS server
1947 * doesn't know anything about the DC's -- jerry */
1949 if (!is_zero_addr(&r->ss)) {
1950 (*return_count)++;
1954 talloc_destroy(ctx);
1955 return NT_STATUS_OK;
1958 /*******************************************************************
1959 Internal interface to resolve a name into an IP address.
1960 Use this function if the string is either an IP address, DNS
1961 or host name or NetBIOS name. This uses the name switch in the
1962 smb.conf to determine the order of name resolution.
1964 Added support for ip addr/port to support ADS ldap servers.
1965 the only place we currently care about the port is in the
1966 resolve_hosts() when looking up DC's via SRV RR entries in DNS
1967 **********************************************************************/
1969 NTSTATUS internal_resolve_name(const char *name,
1970 int name_type,
1971 const char *sitename,
1972 struct ip_service **return_iplist,
1973 int *return_count,
1974 const char *resolve_order)
1976 char *tok;
1977 const char *ptr;
1978 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1979 int i;
1980 TALLOC_CTX *frame = NULL;
1982 *return_iplist = NULL;
1983 *return_count = 0;
1985 DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1986 name, name_type, sitename ? sitename : "(null)"));
1988 if (is_ipaddress(name)) {
1989 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
1990 NULL) {
1991 DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1992 return NT_STATUS_NO_MEMORY;
1995 /* ignore the port here */
1996 (*return_iplist)->port = PORT_NONE;
1998 /* if it's in the form of an IP address then get the lib to interpret it */
1999 if (!interpret_string_addr(&(*return_iplist)->ss,
2000 name, AI_NUMERICHOST)) {
2001 DEBUG(1,("internal_resolve_name: interpret_string_addr "
2002 "failed on %s\n",
2003 name));
2004 SAFE_FREE(*return_iplist);
2005 return NT_STATUS_INVALID_PARAMETER;
2007 *return_count = 1;
2008 return NT_STATUS_OK;
2011 /* Check name cache */
2013 if (namecache_fetch(name, name_type, return_iplist, return_count)) {
2014 /* This could be a negative response */
2015 if (*return_count > 0) {
2016 return NT_STATUS_OK;
2017 } else {
2018 return NT_STATUS_UNSUCCESSFUL;
2022 /* set the name resolution order */
2024 if (strcmp( resolve_order, "NULL") == 0) {
2025 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
2026 return NT_STATUS_INVALID_PARAMETER;
2029 if (!resolve_order[0]) {
2030 ptr = "host";
2031 } else {
2032 ptr = resolve_order;
2035 /* iterate through the name resolution backends */
2037 frame = talloc_stackframe();
2038 while (next_token_talloc(frame, &ptr, &tok, LIST_SEP)) {
2039 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
2040 status = resolve_hosts(name, name_type, return_iplist,
2041 return_count);
2042 if (NT_STATUS_IS_OK(status)) {
2043 goto done;
2045 } else if(strequal( tok, "kdc")) {
2046 /* deal with KDC_NAME_TYPE names here.
2047 * This will result in a SRV record lookup */
2048 status = resolve_ads(name, KDC_NAME_TYPE, sitename,
2049 return_iplist, return_count);
2050 if (NT_STATUS_IS_OK(status)) {
2051 /* Ensure we don't namecache
2052 * this with the KDC port. */
2053 name_type = KDC_NAME_TYPE;
2054 goto done;
2056 } else if(strequal( tok, "ads")) {
2057 /* deal with 0x1c and 0x1b names here.
2058 * This will result in a SRV record lookup */
2059 status = resolve_ads(name, name_type, sitename,
2060 return_iplist, return_count);
2061 if (NT_STATUS_IS_OK(status)) {
2062 goto done;
2064 } else if(strequal( tok, "lmhosts")) {
2065 status = resolve_lmhosts(name, name_type,
2066 return_iplist, return_count);
2067 if (NT_STATUS_IS_OK(status)) {
2068 goto done;
2070 } else if(strequal( tok, "wins")) {
2071 /* don't resolve 1D via WINS */
2072 if (name_type != 0x1D) {
2073 status = resolve_wins(name, name_type,
2074 return_iplist,
2075 return_count);
2076 if (NT_STATUS_IS_OK(status)) {
2077 goto done;
2080 } else if(strequal( tok, "bcast")) {
2081 struct sockaddr_storage *ss_list;
2082 status = name_resolve_bcast(
2083 name, name_type, talloc_tos(),
2084 &ss_list, return_count);
2085 if (NT_STATUS_IS_OK(status)) {
2086 if (!convert_ss2service(return_iplist,
2087 ss_list,
2088 *return_count)) {
2089 status = NT_STATUS_NO_MEMORY;
2091 goto done;
2093 } else {
2094 DEBUG(0,("resolve_name: unknown name switch type %s\n",
2095 tok));
2099 /* All of the resolve_* functions above have returned false. */
2101 TALLOC_FREE(frame);
2102 SAFE_FREE(*return_iplist);
2103 *return_count = 0;
2105 return NT_STATUS_UNSUCCESSFUL;
2107 done:
2109 /* Remove duplicate entries. Some queries, notably #1c (domain
2110 controllers) return the PDC in iplist[0] and then all domain
2111 controllers including the PDC in iplist[1..n]. Iterating over
2112 the iplist when the PDC is down will cause two sets of timeouts. */
2114 if ( *return_count ) {
2115 *return_count = remove_duplicate_addrs2(*return_iplist,
2116 *return_count );
2119 /* Save in name cache */
2120 if ( DEBUGLEVEL >= 100 ) {
2121 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
2122 char addr[INET6_ADDRSTRLEN];
2123 print_sockaddr(addr, sizeof(addr),
2124 &(*return_iplist)[i].ss);
2125 DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
2126 name,
2127 name_type,
2128 addr,
2129 (*return_iplist)[i].port));
2133 namecache_store(name, name_type, *return_count, *return_iplist);
2135 /* Display some debugging info */
2137 if ( DEBUGLEVEL >= 10 ) {
2138 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
2139 *return_count));
2141 for (i = 0; i < *return_count; i++) {
2142 char addr[INET6_ADDRSTRLEN];
2143 print_sockaddr(addr, sizeof(addr),
2144 &(*return_iplist)[i].ss);
2145 DEBUGADD(10, ("%s:%d ",
2146 addr,
2147 (*return_iplist)[i].port));
2149 DEBUG(10, ("\n"));
2152 TALLOC_FREE(frame);
2153 return status;
2156 /********************************************************
2157 Internal interface to resolve a name into one IP address.
2158 Use this function if the string is either an IP address, DNS
2159 or host name or NetBIOS name. This uses the name switch in the
2160 smb.conf to determine the order of name resolution.
2161 *********************************************************/
2163 bool resolve_name(const char *name,
2164 struct sockaddr_storage *return_ss,
2165 int name_type,
2166 bool prefer_ipv4)
2168 struct ip_service *ss_list = NULL;
2169 char *sitename = NULL;
2170 int count = 0;
2172 if (is_ipaddress(name)) {
2173 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
2176 sitename = sitename_fetch(lp_realm()); /* wild guess */
2178 if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
2179 &ss_list, &count,
2180 lp_name_resolve_order()))) {
2181 int i;
2183 if (prefer_ipv4) {
2184 for (i=0; i<count; i++) {
2185 if (!is_zero_addr(&ss_list[i].ss) &&
2186 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss) &&
2187 (ss_list[i].ss.ss_family == AF_INET)) {
2188 *return_ss = ss_list[i].ss;
2189 SAFE_FREE(ss_list);
2190 SAFE_FREE(sitename);
2191 return True;
2196 /* only return valid addresses for TCP connections */
2197 for (i=0; i<count; i++) {
2198 if (!is_zero_addr(&ss_list[i].ss) &&
2199 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2200 *return_ss = ss_list[i].ss;
2201 SAFE_FREE(ss_list);
2202 SAFE_FREE(sitename);
2203 return True;
2208 SAFE_FREE(ss_list);
2209 SAFE_FREE(sitename);
2210 return False;
2213 /********************************************************
2214 Internal interface to resolve a name into a list of IP addresses.
2215 Use this function if the string is either an IP address, DNS
2216 or host name or NetBIOS name. This uses the name switch in the
2217 smb.conf to determine the order of name resolution.
2218 *********************************************************/
2220 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
2221 const char *name,
2222 int name_type,
2223 struct sockaddr_storage **return_ss_arr,
2224 unsigned int *p_num_entries)
2226 struct ip_service *ss_list = NULL;
2227 char *sitename = NULL;
2228 int count = 0;
2229 int i;
2230 unsigned int num_entries;
2231 NTSTATUS status;
2233 *p_num_entries = 0;
2234 *return_ss_arr = NULL;
2236 if (is_ipaddress(name)) {
2237 *return_ss_arr = TALLOC_P(ctx, struct sockaddr_storage);
2238 if (!*return_ss_arr) {
2239 return NT_STATUS_NO_MEMORY;
2241 if (!interpret_string_addr(*return_ss_arr, name, AI_NUMERICHOST)) {
2242 TALLOC_FREE(*return_ss_arr);
2243 return NT_STATUS_BAD_NETWORK_NAME;
2245 *p_num_entries = 1;
2246 return NT_STATUS_OK;
2249 sitename = sitename_fetch(lp_realm()); /* wild guess */
2251 status = internal_resolve_name(name, name_type, sitename,
2252 &ss_list, &count,
2253 lp_name_resolve_order());
2254 SAFE_FREE(sitename);
2256 if (!NT_STATUS_IS_OK(status)) {
2257 return status;
2260 /* only return valid addresses for TCP connections */
2261 for (i=0, num_entries = 0; i<count; i++) {
2262 if (!is_zero_addr(&ss_list[i].ss) &&
2263 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2264 num_entries++;
2267 if (num_entries == 0) {
2268 SAFE_FREE(ss_list);
2269 return NT_STATUS_BAD_NETWORK_NAME;
2272 *return_ss_arr = TALLOC_ARRAY(ctx,
2273 struct sockaddr_storage,
2274 num_entries);
2275 if (!(*return_ss_arr)) {
2276 SAFE_FREE(ss_list);
2277 return NT_STATUS_NO_MEMORY;
2280 for (i=0, num_entries = 0; i<count; i++) {
2281 if (!is_zero_addr(&ss_list[i].ss) &&
2282 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
2283 (*return_ss_arr)[num_entries++] = ss_list[i].ss;
2287 status = NT_STATUS_OK;
2288 *p_num_entries = num_entries;
2290 SAFE_FREE(ss_list);
2291 return NT_STATUS_OK;
2294 /********************************************************
2295 Find the IP address of the master browser or DMB for a workgroup.
2296 *********************************************************/
2298 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
2300 struct ip_service *ip_list = NULL;
2301 int count = 0;
2302 NTSTATUS status;
2304 if (lp_disable_netbios()) {
2305 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
2306 return false;
2309 status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
2310 lp_name_resolve_order());
2311 if (NT_STATUS_IS_OK(status)) {
2312 *master_ss = ip_list[0].ss;
2313 SAFE_FREE(ip_list);
2314 return true;
2317 status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
2318 lp_name_resolve_order());
2319 if (NT_STATUS_IS_OK(status)) {
2320 *master_ss = ip_list[0].ss;
2321 SAFE_FREE(ip_list);
2322 return true;
2325 SAFE_FREE(ip_list);
2326 return false;
2329 /********************************************************
2330 Get the IP address list of the primary domain controller
2331 for a domain.
2332 *********************************************************/
2334 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
2336 struct ip_service *ip_list = NULL;
2337 int count = 0;
2338 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2340 /* Look up #1B name */
2342 if (lp_security() == SEC_ADS) {
2343 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2344 &count, "ads");
2347 if (!NT_STATUS_IS_OK(status) || count == 0) {
2348 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
2349 &count,
2350 lp_name_resolve_order());
2351 if (!NT_STATUS_IS_OK(status)) {
2352 return false;
2356 /* if we get more than 1 IP back we have to assume it is a
2357 multi-homed PDC and not a mess up */
2359 if ( count > 1 ) {
2360 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
2361 sort_service_list(ip_list, count);
2364 *pss = ip_list[0].ss;
2365 SAFE_FREE(ip_list);
2366 return true;
2369 /* Private enum type for lookups. */
2371 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
2373 /********************************************************
2374 Get the IP address list of the domain controllers for
2375 a domain.
2376 *********************************************************/
2378 static NTSTATUS get_dc_list(const char *domain,
2379 const char *sitename,
2380 struct ip_service **ip_list,
2381 int *count,
2382 enum dc_lookup_type lookup_type,
2383 bool *ordered)
2385 char *resolve_order = NULL;
2386 char *saf_servername = NULL;
2387 char *pserver = NULL;
2388 const char *p;
2389 char *port_str = NULL;
2390 int port;
2391 char *name;
2392 int num_addresses = 0;
2393 int local_count, i, j;
2394 struct ip_service *return_iplist = NULL;
2395 struct ip_service *auto_ip_list = NULL;
2396 bool done_auto_lookup = false;
2397 int auto_count = 0;
2398 NTSTATUS status;
2399 TALLOC_CTX *ctx = talloc_init("get_dc_list");
2401 *ip_list = NULL;
2402 *count = 0;
2404 if (!ctx) {
2405 return NT_STATUS_NO_MEMORY;
2408 *ordered = False;
2410 /* if we are restricted to solely using DNS for looking
2411 up a domain controller, make sure that host lookups
2412 are enabled for the 'name resolve order'. If host lookups
2413 are disabled and ads_only is True, then set the string to
2414 NULL. */
2416 resolve_order = talloc_strdup(ctx, lp_name_resolve_order());
2417 if (!resolve_order) {
2418 status = NT_STATUS_NO_MEMORY;
2419 goto out;
2421 strlower_m(resolve_order);
2422 if (lookup_type == DC_ADS_ONLY) {
2423 if (strstr( resolve_order, "host")) {
2424 resolve_order = talloc_strdup(ctx, "ads");
2426 /* DNS SRV lookups used by the ads resolver
2427 are already sorted by priority and weight */
2428 *ordered = true;
2429 } else {
2430 resolve_order = talloc_strdup(ctx, "NULL");
2432 } else if (lookup_type == DC_KDC_ONLY) {
2433 /* DNS SRV lookups used by the ads/kdc resolver
2434 are already sorted by priority and weight */
2435 *ordered = true;
2436 resolve_order = talloc_strdup(ctx, "kdc");
2438 if (!resolve_order) {
2439 status = NT_STATUS_NO_MEMORY;
2440 goto out;
2443 /* fetch the server we have affinity for. Add the
2444 'password server' list to a search for our domain controllers */
2446 saf_servername = saf_fetch( domain);
2448 if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
2449 pserver = talloc_asprintf(ctx, "%s, %s",
2450 saf_servername ? saf_servername : "",
2451 lp_passwordserver());
2452 } else {
2453 pserver = talloc_asprintf(ctx, "%s, *",
2454 saf_servername ? saf_servername : "");
2457 SAFE_FREE(saf_servername);
2458 if (!pserver) {
2459 status = NT_STATUS_NO_MEMORY;
2460 goto out;
2463 /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
2465 if (!*pserver ) {
2466 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
2467 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2468 count, resolve_order);
2469 goto out;
2472 DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
2475 * if '*' appears in the "password server" list then add
2476 * an auto lookup to the list of manually configured
2477 * DC's. If any DC is listed by name, then the list should be
2478 * considered to be ordered
2481 p = pserver;
2482 while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2483 if (!done_auto_lookup && strequal(name, "*")) {
2484 status = internal_resolve_name(domain, 0x1C, sitename,
2485 &auto_ip_list,
2486 &auto_count,
2487 resolve_order);
2488 if (NT_STATUS_IS_OK(status)) {
2489 num_addresses += auto_count;
2491 done_auto_lookup = true;
2492 DEBUG(8,("Adding %d DC's from auto lookup\n",
2493 auto_count));
2494 } else {
2495 num_addresses++;
2499 /* if we have no addresses and haven't done the auto lookup, then
2500 just return the list of DC's. Or maybe we just failed. */
2502 if ((num_addresses == 0)) {
2503 if (done_auto_lookup) {
2504 DEBUG(4,("get_dc_list: no servers found\n"));
2505 status = NT_STATUS_NO_LOGON_SERVERS;
2506 goto out;
2508 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2509 count, resolve_order);
2510 goto out;
2513 if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
2514 num_addresses)) == NULL) {
2515 DEBUG(3,("get_dc_list: malloc fail !\n"));
2516 status = NT_STATUS_NO_MEMORY;
2517 goto out;
2520 p = pserver;
2521 local_count = 0;
2523 /* fill in the return list now with real IP's */
2525 while ((local_count<num_addresses) &&
2526 next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2527 struct sockaddr_storage name_ss;
2529 /* copy any addersses from the auto lookup */
2531 if (strequal(name, "*")) {
2532 for (j=0; j<auto_count; j++) {
2533 char addr[INET6_ADDRSTRLEN];
2534 print_sockaddr(addr,
2535 sizeof(addr),
2536 &auto_ip_list[j].ss);
2537 /* Check for and don't copy any
2538 * known bad DC IP's. */
2539 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
2540 domain,
2541 addr))) {
2542 DEBUG(5,("get_dc_list: "
2543 "negative entry %s removed "
2544 "from DC list\n",
2545 addr));
2546 continue;
2548 return_iplist[local_count].ss =
2549 auto_ip_list[j].ss;
2550 return_iplist[local_count].port =
2551 auto_ip_list[j].port;
2552 local_count++;
2554 continue;
2557 /* added support for address:port syntax for ads
2558 * (not that I think anyone will ever run the LDAP
2559 * server in an AD domain on something other than
2560 * port 389 */
2562 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
2563 if ((port_str=strchr(name, ':')) != NULL) {
2564 *port_str = '\0';
2565 port_str++;
2566 port = atoi(port_str);
2569 /* explicit lookup; resolve_name() will
2570 * handle names & IP addresses */
2571 if (resolve_name( name, &name_ss, 0x20, true )) {
2572 char addr[INET6_ADDRSTRLEN];
2573 print_sockaddr(addr,
2574 sizeof(addr),
2575 &name_ss);
2577 /* Check for and don't copy any known bad DC IP's. */
2578 if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
2579 addr)) ) {
2580 DEBUG(5,("get_dc_list: negative entry %s "
2581 "removed from DC list\n",
2582 name ));
2583 continue;
2586 return_iplist[local_count].ss = name_ss;
2587 return_iplist[local_count].port = port;
2588 local_count++;
2589 *ordered = true;
2593 /* need to remove duplicates in the list if we have any
2594 explicit password servers */
2596 if (local_count) {
2597 local_count = remove_duplicate_addrs2(return_iplist,
2598 local_count );
2601 /* For DC's we always prioritize IPv4 due to W2K3 not
2602 * supporting LDAP, KRB5 or CLDAP over IPv6. */
2604 if (local_count && return_iplist) {
2605 prioritize_ipv4_list(return_iplist, local_count);
2608 if ( DEBUGLEVEL >= 4 ) {
2609 DEBUG(4,("get_dc_list: returning %d ip addresses "
2610 "in an %sordered list\n",
2611 local_count,
2612 *ordered ? "":"un"));
2613 DEBUG(4,("get_dc_list: "));
2614 for ( i=0; i<local_count; i++ ) {
2615 char addr[INET6_ADDRSTRLEN];
2616 print_sockaddr(addr,
2617 sizeof(addr),
2618 &return_iplist[i].ss);
2619 DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
2621 DEBUGADD(4,("\n"));
2624 *ip_list = return_iplist;
2625 *count = local_count;
2627 status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
2629 out:
2631 if (!NT_STATUS_IS_OK(status)) {
2632 SAFE_FREE(return_iplist);
2633 *ip_list = NULL;
2634 *count = 0;
2637 SAFE_FREE(auto_ip_list);
2638 TALLOC_FREE(ctx);
2639 return status;
2642 /*********************************************************************
2643 Small wrapper function to get the DC list and sort it if neccessary.
2644 *********************************************************************/
2646 NTSTATUS get_sorted_dc_list( const char *domain,
2647 const char *sitename,
2648 struct ip_service **ip_list,
2649 int *count,
2650 bool ads_only )
2652 bool ordered = false;
2653 NTSTATUS status;
2654 enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
2656 *ip_list = NULL;
2657 *count = 0;
2659 DEBUG(8,("get_sorted_dc_list: attempting lookup "
2660 "for name %s (sitename %s) using [%s]\n",
2661 domain,
2662 sitename ? sitename : "NULL",
2663 (ads_only ? "ads" : lp_name_resolve_order())));
2665 if (ads_only) {
2666 lookup_type = DC_ADS_ONLY;
2669 status = get_dc_list(domain, sitename, ip_list,
2670 count, lookup_type, &ordered);
2671 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS)
2672 && sitename) {
2673 DEBUG(3,("get_sorted_dc_list: no server for name %s available"
2674 " in site %s, fallback to all servers\n",
2675 domain, sitename));
2676 status = get_dc_list(domain, NULL, ip_list,
2677 count, lookup_type, &ordered);
2680 if (!NT_STATUS_IS_OK(status)) {
2681 SAFE_FREE(*ip_list);
2682 *count = 0;
2683 return status;
2686 /* only sort if we don't already have an ordered list */
2687 if (!ordered) {
2688 sort_service_list(*ip_list, *count);
2691 return NT_STATUS_OK;
2694 /*********************************************************************
2695 Get the KDC list - re-use all the logic in get_dc_list.
2696 *********************************************************************/
2698 NTSTATUS get_kdc_list( const char *realm,
2699 const char *sitename,
2700 struct ip_service **ip_list,
2701 int *count)
2703 bool ordered;
2704 NTSTATUS status;
2706 *count = 0;
2707 *ip_list = NULL;
2709 status = get_dc_list(realm, sitename, ip_list,
2710 count, DC_KDC_ONLY, &ordered);
2712 if (!NT_STATUS_IS_OK(status)) {
2713 SAFE_FREE(*ip_list);
2714 *count = 0;
2715 return status;
2718 /* only sort if we don't already have an ordered list */
2719 if ( !ordered ) {
2720 sort_service_list(*ip_list, *count);
2723 return NT_STATUS_OK;