libsmb: Give unexpected.c its own header
[Samba.git] / source3 / libsmb / namequery.c
blob6107e8ff7b4cbd700bc2c410864ced147cd4b7f1
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 "../lib/addns/dnsquery.h"
25 #include "../libcli/netlogon/netlogon.h"
26 #include "lib/async_req/async_sock.h"
27 #include "lib/tsocket/tsocket.h"
28 #include "libsmb/nmblib.h"
29 #include "libsmb/unexpected.h"
30 #include "../libcli/nbt/libnbt.h"
31 #include "libads/kerberos_proto.h"
33 /* nmbd.c sets this to True. */
34 bool global_in_nmbd = False;
36 /****************************
37 * SERVER AFFINITY ROUTINES *
38 ****************************/
40 /* Server affinity is the concept of preferring the last domain
41 controller with whom you had a successful conversation */
43 /****************************************************************************
44 ****************************************************************************/
45 #define SAFKEY_FMT "SAF/DOMAIN/%s"
46 #define SAF_TTL 900
47 #define SAFJOINKEY_FMT "SAFJOIN/DOMAIN/%s"
48 #define SAFJOIN_TTL 3600
50 static char *saf_key(TALLOC_CTX *mem_ctx, const char *domain)
52 return talloc_asprintf_strupper_m(mem_ctx, SAFKEY_FMT, domain);
55 static char *saf_join_key(TALLOC_CTX *mem_ctx, const char *domain)
57 return talloc_asprintf_strupper_m(mem_ctx, SAFJOINKEY_FMT, domain);
60 /****************************************************************************
61 ****************************************************************************/
63 bool saf_store( const char *domain, const char *servername )
65 char *key;
66 time_t expire;
67 bool ret = False;
69 if ( !domain || !servername ) {
70 DEBUG(2,("saf_store: "
71 "Refusing to store empty domain or servername!\n"));
72 return False;
75 if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
76 DEBUG(0,("saf_store: "
77 "refusing to store 0 length domain or servername!\n"));
78 return False;
81 key = saf_key(talloc_tos(), domain);
82 if (key == NULL) {
83 DEBUG(1, ("saf_key() failed\n"));
84 return false;
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 TALLOC_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(talloc_tos(), domain);
115 if (key == NULL) {
116 DEBUG(1, ("saf_join_key() failed\n"));
117 return false;
119 expire = time( NULL ) + lp_parm_int(-1, "saf","join ttl", SAFJOIN_TTL);
121 DEBUG(10,("saf_join_store: domain = [%s], server = [%s], expire = [%u]\n",
122 domain, servername, (unsigned int)expire ));
124 ret = gencache_set( key, servername, expire );
126 TALLOC_FREE( key );
128 return ret;
131 bool saf_delete( const char *domain )
133 char *key;
134 bool ret = False;
136 if ( !domain ) {
137 DEBUG(2,("saf_delete: Refusing to delete empty domain\n"));
138 return False;
141 key = saf_join_key(talloc_tos(), domain);
142 if (key == NULL) {
143 DEBUG(1, ("saf_join_key() failed\n"));
144 return false;
146 ret = gencache_del(key);
147 TALLOC_FREE(key);
149 if (ret) {
150 DEBUG(10,("saf_delete[join]: domain = [%s]\n", domain ));
153 key = saf_key(talloc_tos(), domain);
154 if (key == NULL) {
155 DEBUG(1, ("saf_key() failed\n"));
156 return false;
158 ret = gencache_del(key);
159 TALLOC_FREE(key);
161 if (ret) {
162 DEBUG(10,("saf_delete: domain = [%s]\n", domain ));
165 return ret;
168 /****************************************************************************
169 ****************************************************************************/
171 char *saf_fetch(TALLOC_CTX *mem_ctx, const char *domain )
173 char *server = NULL;
174 time_t timeout;
175 bool ret = False;
176 char *key = NULL;
178 if ( !domain || strlen(domain) == 0) {
179 DEBUG(2,("saf_fetch: Empty domain name!\n"));
180 return NULL;
183 key = saf_join_key(talloc_tos(), domain);
184 if (key == NULL) {
185 DEBUG(1, ("saf_join_key() failed\n"));
186 return NULL;
189 ret = gencache_get( key, mem_ctx, &server, &timeout );
191 TALLOC_FREE( key );
193 if ( ret ) {
194 DEBUG(5,("saf_fetch[join]: Returning \"%s\" for \"%s\" domain\n",
195 server, domain ));
196 return server;
199 key = saf_key(talloc_tos(), domain);
200 if (key == NULL) {
201 DEBUG(1, ("saf_key() failed\n"));
202 return NULL;
205 ret = gencache_get( key, mem_ctx, &server, &timeout );
207 TALLOC_FREE( key );
209 if ( !ret ) {
210 DEBUG(5,("saf_fetch: failed to find server for \"%s\" domain\n",
211 domain ));
212 } else {
213 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
214 server, domain ));
217 return server;
220 static void set_socket_addr_v4(struct sockaddr_storage *addr)
222 if (!interpret_string_addr(addr, lp_nbt_client_socket_address(),
223 AI_NUMERICHOST|AI_PASSIVE)) {
224 zero_sockaddr(addr);
226 if (addr->ss_family != AF_INET) {
227 zero_sockaddr(addr);
231 static struct in_addr my_socket_addr_v4(void)
233 struct sockaddr_storage my_addr;
234 struct sockaddr_in *in_addr = (struct sockaddr_in *)((char *)&my_addr);
236 set_socket_addr_v4(&my_addr);
237 return in_addr->sin_addr;
240 /****************************************************************************
241 Generate a random trn_id.
242 ****************************************************************************/
244 static int generate_trn_id(void)
246 uint16_t id;
248 generate_random_buffer((uint8_t *)&id, sizeof(id));
250 return id % (unsigned)0x7FFF;
253 /****************************************************************************
254 Parse a node status response into an array of structures.
255 ****************************************************************************/
257 static struct node_status *parse_node_status(TALLOC_CTX *mem_ctx, char *p,
258 int *num_names,
259 struct node_status_extra *extra)
261 struct node_status *ret;
262 int i;
264 *num_names = CVAL(p,0);
266 if (*num_names == 0)
267 return NULL;
269 ret = talloc_array(mem_ctx, struct node_status,*num_names);
270 if (!ret)
271 return NULL;
273 p++;
274 for (i=0;i< *num_names;i++) {
275 StrnCpy(ret[i].name,p,15);
276 trim_char(ret[i].name,'\0',' ');
277 ret[i].type = CVAL(p,15);
278 ret[i].flags = p[16];
279 p += 18;
280 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
281 ret[i].type, ret[i].flags));
284 * Also, pick up the MAC address ...
286 if (extra) {
287 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
289 return ret;
292 struct sock_packet_read_state {
293 struct tevent_context *ev;
294 enum packet_type type;
295 int trn_id;
297 struct nb_packet_reader *reader;
298 struct tevent_req *reader_req;
300 struct tdgram_context *sock;
301 struct tevent_req *socket_req;
302 uint8_t *buf;
303 struct tsocket_address *addr;
305 bool (*validator)(struct packet_struct *p,
306 void *private_data);
307 void *private_data;
309 struct packet_struct *packet;
312 static int sock_packet_read_state_destructor(struct sock_packet_read_state *s);
313 static void sock_packet_read_got_packet(struct tevent_req *subreq);
314 static void sock_packet_read_got_socket(struct tevent_req *subreq);
316 static struct tevent_req *sock_packet_read_send(
317 TALLOC_CTX *mem_ctx,
318 struct tevent_context *ev,
319 struct tdgram_context *sock,
320 struct nb_packet_reader *reader,
321 enum packet_type type,
322 int trn_id,
323 bool (*validator)(struct packet_struct *p, void *private_data),
324 void *private_data)
326 struct tevent_req *req;
327 struct sock_packet_read_state *state;
329 req = tevent_req_create(mem_ctx, &state,
330 struct sock_packet_read_state);
331 if (req == NULL) {
332 return NULL;
334 talloc_set_destructor(state, sock_packet_read_state_destructor);
335 state->ev = ev;
336 state->reader = reader;
337 state->sock = sock;
338 state->type = type;
339 state->trn_id = trn_id;
340 state->validator = validator;
341 state->private_data = private_data;
343 if (reader != NULL) {
344 state->reader_req = nb_packet_read_send(state, ev, reader);
345 if (tevent_req_nomem(state->reader_req, req)) {
346 return tevent_req_post(req, ev);
348 tevent_req_set_callback(
349 state->reader_req, sock_packet_read_got_packet, req);
352 state->socket_req = tdgram_recvfrom_send(state, ev, state->sock);
353 if (tevent_req_nomem(state->socket_req, req)) {
354 return tevent_req_post(req, ev);
356 tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
357 req);
359 return req;
362 static int sock_packet_read_state_destructor(struct sock_packet_read_state *s)
364 if (s->packet != NULL) {
365 free_packet(s->packet);
366 s->packet = NULL;
368 return 0;
371 static void sock_packet_read_got_packet(struct tevent_req *subreq)
373 struct tevent_req *req = tevent_req_callback_data(
374 subreq, struct tevent_req);
375 struct sock_packet_read_state *state = tevent_req_data(
376 req, struct sock_packet_read_state);
377 NTSTATUS status;
379 status = nb_packet_read_recv(subreq, &state->packet);
381 TALLOC_FREE(state->reader_req);
383 if (!NT_STATUS_IS_OK(status)) {
384 if (state->socket_req != NULL) {
386 * Still waiting for socket
388 return;
391 * Both socket and packet reader failed
393 tevent_req_nterror(req, status);
394 return;
397 if ((state->validator != NULL) &&
398 !state->validator(state->packet, state->private_data)) {
399 DEBUG(10, ("validator failed\n"));
401 free_packet(state->packet);
402 state->packet = NULL;
404 state->reader_req = nb_packet_read_send(state, state->ev,
405 state->reader);
406 if (tevent_req_nomem(state->reader_req, req)) {
407 return;
409 tevent_req_set_callback(
410 state->reader_req, sock_packet_read_got_packet, req);
411 return;
414 TALLOC_FREE(state->socket_req);
415 tevent_req_done(req);
418 static void sock_packet_read_got_socket(struct tevent_req *subreq)
420 struct tevent_req *req = tevent_req_callback_data(
421 subreq, struct tevent_req);
422 struct sock_packet_read_state *state = tevent_req_data(
423 req, struct sock_packet_read_state);
424 union {
425 struct sockaddr sa;
426 struct sockaddr_in sin;
427 } addr;
428 ssize_t ret;
429 ssize_t received;
430 int err;
431 bool ok;
433 received = tdgram_recvfrom_recv(subreq, &err, state,
434 &state->buf, &state->addr);
436 TALLOC_FREE(state->socket_req);
438 if (received == -1) {
439 if (state->reader_req != NULL) {
441 * Still waiting for reader
443 return;
446 * Both socket and reader failed
448 tevent_req_nterror(req, map_nt_error_from_unix(err));
449 return;
451 ok = tsocket_address_is_inet(state->addr, "ipv4");
452 if (!ok) {
453 goto retry;
455 ret = tsocket_address_bsd_sockaddr(state->addr,
456 &addr.sa,
457 sizeof(addr.sin));
458 if (ret == -1) {
459 tevent_req_nterror(req, map_nt_error_from_unix(errno));
460 return;
463 state->packet = parse_packet((char *)state->buf, received, state->type,
464 addr.sin.sin_addr, addr.sin.sin_port);
465 if (state->packet == NULL) {
466 DEBUG(10, ("parse_packet failed\n"));
467 goto retry;
469 if ((state->trn_id != -1) &&
470 (state->trn_id != packet_trn_id(state->packet))) {
471 DEBUG(10, ("Expected transaction id %d, got %d\n",
472 state->trn_id, packet_trn_id(state->packet)));
473 goto retry;
476 if ((state->validator != NULL) &&
477 !state->validator(state->packet, state->private_data)) {
478 DEBUG(10, ("validator failed\n"));
479 goto retry;
482 tevent_req_done(req);
483 return;
485 retry:
486 if (state->packet != NULL) {
487 free_packet(state->packet);
488 state->packet = NULL;
490 TALLOC_FREE(state->buf);
491 TALLOC_FREE(state->addr);
493 state->socket_req = tdgram_recvfrom_send(state, state->ev, state->sock);
494 if (tevent_req_nomem(state->socket_req, req)) {
495 return;
497 tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
498 req);
501 static NTSTATUS sock_packet_read_recv(struct tevent_req *req,
502 struct packet_struct **ppacket)
504 struct sock_packet_read_state *state = tevent_req_data(
505 req, struct sock_packet_read_state);
506 NTSTATUS status;
508 if (tevent_req_is_nterror(req, &status)) {
509 return status;
511 *ppacket = state->packet;
512 state->packet = NULL;
513 return NT_STATUS_OK;
516 struct nb_trans_state {
517 struct tevent_context *ev;
518 struct tdgram_context *sock;
519 struct nb_packet_reader *reader;
521 struct tsocket_address *src_addr;
522 struct tsocket_address *dst_addr;
523 uint8_t *buf;
524 size_t buflen;
525 enum packet_type type;
526 int trn_id;
528 bool (*validator)(struct packet_struct *p,
529 void *private_data);
530 void *private_data;
532 struct packet_struct *packet;
535 static int nb_trans_state_destructor(struct nb_trans_state *s);
536 static void nb_trans_got_reader(struct tevent_req *subreq);
537 static void nb_trans_done(struct tevent_req *subreq);
538 static void nb_trans_sent(struct tevent_req *subreq);
539 static void nb_trans_send_next(struct tevent_req *subreq);
541 static struct tevent_req *nb_trans_send(
542 TALLOC_CTX *mem_ctx,
543 struct tevent_context *ev,
544 const struct sockaddr_storage *_my_addr,
545 const struct sockaddr_storage *_dst_addr,
546 bool bcast,
547 uint8_t *buf, size_t buflen,
548 enum packet_type type, int trn_id,
549 bool (*validator)(struct packet_struct *p,
550 void *private_data),
551 void *private_data)
553 const struct sockaddr *my_addr =
554 discard_const_p(const struct sockaddr, _my_addr);
555 size_t my_addr_len = sizeof(*_my_addr);
556 const struct sockaddr *dst_addr =
557 discard_const_p(const struct sockaddr, _dst_addr);
558 size_t dst_addr_len = sizeof(*_dst_addr);
559 struct tevent_req *req, *subreq;
560 struct nb_trans_state *state;
561 int ret;
563 req = tevent_req_create(mem_ctx, &state, struct nb_trans_state);
564 if (req == NULL) {
565 return NULL;
567 talloc_set_destructor(state, nb_trans_state_destructor);
568 state->ev = ev;
569 state->buf = buf;
570 state->buflen = buflen;
571 state->type = type;
572 state->trn_id = trn_id;
573 state->validator = validator;
574 state->private_data = private_data;
576 ret = tsocket_address_bsd_from_sockaddr(state,
577 my_addr, my_addr_len,
578 &state->src_addr);
579 if (ret == -1) {
580 tevent_req_nterror(req, map_nt_error_from_unix(errno));
581 return tevent_req_post(req, ev);
584 ret = tsocket_address_bsd_from_sockaddr(state,
585 dst_addr, dst_addr_len,
586 &state->dst_addr);
587 if (ret == -1) {
588 tevent_req_nterror(req, map_nt_error_from_unix(errno));
589 return tevent_req_post(req, ev);
592 ret = tdgram_inet_udp_broadcast_socket(state->src_addr, state,
593 &state->sock);
594 if (ret == -1) {
595 tevent_req_nterror(req, map_nt_error_from_unix(errno));
596 return tevent_req_post(req, ev);
599 subreq = nb_packet_reader_send(state, ev, type, state->trn_id, NULL);
600 if (tevent_req_nomem(subreq, req)) {
601 return tevent_req_post(req, ev);
603 tevent_req_set_callback(subreq, nb_trans_got_reader, req);
604 return req;
607 static int nb_trans_state_destructor(struct nb_trans_state *s)
609 if (s->packet != NULL) {
610 free_packet(s->packet);
611 s->packet = NULL;
613 return 0;
616 static void nb_trans_got_reader(struct tevent_req *subreq)
618 struct tevent_req *req = tevent_req_callback_data(
619 subreq, struct tevent_req);
620 struct nb_trans_state *state = tevent_req_data(
621 req, struct nb_trans_state);
622 NTSTATUS status;
624 status = nb_packet_reader_recv(subreq, state, &state->reader);
625 TALLOC_FREE(subreq);
627 if (!NT_STATUS_IS_OK(status)) {
628 DEBUG(10, ("nmbd not around\n"));
629 state->reader = NULL;
632 subreq = sock_packet_read_send(
633 state, state->ev, state->sock,
634 state->reader, state->type, state->trn_id,
635 state->validator, state->private_data);
636 if (tevent_req_nomem(subreq, req)) {
637 return;
639 tevent_req_set_callback(subreq, nb_trans_done, req);
641 subreq = tdgram_sendto_send(state, state->ev,
642 state->sock,
643 state->buf, state->buflen,
644 state->dst_addr);
645 if (tevent_req_nomem(subreq, req)) {
646 return;
648 tevent_req_set_callback(subreq, nb_trans_sent, req);
651 static void nb_trans_sent(struct tevent_req *subreq)
653 struct tevent_req *req = tevent_req_callback_data(
654 subreq, struct tevent_req);
655 struct nb_trans_state *state = tevent_req_data(
656 req, struct nb_trans_state);
657 ssize_t sent;
658 int err;
660 sent = tdgram_sendto_recv(subreq, &err);
661 TALLOC_FREE(subreq);
662 if (sent == -1) {
663 DEBUG(10, ("sendto failed: %s\n", strerror(err)));
664 tevent_req_nterror(req, map_nt_error_from_unix(err));
665 return;
667 subreq = tevent_wakeup_send(state, state->ev,
668 timeval_current_ofs(1, 0));
669 if (tevent_req_nomem(subreq, req)) {
670 return;
672 tevent_req_set_callback(subreq, nb_trans_send_next, req);
675 static void nb_trans_send_next(struct tevent_req *subreq)
677 struct tevent_req *req = tevent_req_callback_data(
678 subreq, struct tevent_req);
679 struct nb_trans_state *state = tevent_req_data(
680 req, struct nb_trans_state);
681 bool ret;
683 ret = tevent_wakeup_recv(subreq);
684 TALLOC_FREE(subreq);
685 if (!ret) {
686 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
687 return;
689 subreq = tdgram_sendto_send(state, state->ev,
690 state->sock,
691 state->buf, state->buflen,
692 state->dst_addr);
693 if (tevent_req_nomem(subreq, req)) {
694 return;
696 tevent_req_set_callback(subreq, nb_trans_sent, req);
699 static void nb_trans_done(struct tevent_req *subreq)
701 struct tevent_req *req = tevent_req_callback_data(
702 subreq, struct tevent_req);
703 struct nb_trans_state *state = tevent_req_data(
704 req, struct nb_trans_state);
705 NTSTATUS status;
707 status = sock_packet_read_recv(subreq, &state->packet);
708 TALLOC_FREE(subreq);
709 if (tevent_req_nterror(req, status)) {
710 return;
712 tevent_req_done(req);
715 static NTSTATUS nb_trans_recv(struct tevent_req *req,
716 struct packet_struct **ppacket)
718 struct nb_trans_state *state = tevent_req_data(
719 req, struct nb_trans_state);
720 NTSTATUS status;
722 if (tevent_req_is_nterror(req, &status)) {
723 return status;
725 *ppacket = state->packet;
726 state->packet = NULL;
727 return NT_STATUS_OK;
730 /****************************************************************************
731 Do a NBT node status query on an open socket and return an array of
732 structures holding the returned names or NULL if the query failed.
733 **************************************************************************/
735 struct node_status_query_state {
736 struct sockaddr_storage my_addr;
737 struct sockaddr_storage addr;
738 uint8_t buf[1024];
739 ssize_t buflen;
740 struct packet_struct *packet;
743 static int node_status_query_state_destructor(
744 struct node_status_query_state *s);
745 static bool node_status_query_validator(struct packet_struct *p,
746 void *private_data);
747 static void node_status_query_done(struct tevent_req *subreq);
749 struct tevent_req *node_status_query_send(TALLOC_CTX *mem_ctx,
750 struct tevent_context *ev,
751 struct nmb_name *name,
752 const struct sockaddr_storage *addr)
754 struct tevent_req *req, *subreq;
755 struct node_status_query_state *state;
756 struct packet_struct p;
757 struct nmb_packet *nmb = &p.packet.nmb;
758 struct sockaddr_in *in_addr;
760 req = tevent_req_create(mem_ctx, &state,
761 struct node_status_query_state);
762 if (req == NULL) {
763 return NULL;
765 talloc_set_destructor(state, node_status_query_state_destructor);
767 if (addr->ss_family != AF_INET) {
768 /* Can't do node status to IPv6 */
769 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
770 return tevent_req_post(req, ev);
773 state->addr = *addr;
774 in_addr = (struct sockaddr_in *)(void *)&state->addr;
775 in_addr->sin_port = htons(NMB_PORT);
777 set_socket_addr_v4(&state->my_addr);
779 ZERO_STRUCT(p);
780 nmb->header.name_trn_id = generate_trn_id();
781 nmb->header.opcode = 0;
782 nmb->header.response = false;
783 nmb->header.nm_flags.bcast = false;
784 nmb->header.nm_flags.recursion_available = false;
785 nmb->header.nm_flags.recursion_desired = false;
786 nmb->header.nm_flags.trunc = false;
787 nmb->header.nm_flags.authoritative = false;
788 nmb->header.rcode = 0;
789 nmb->header.qdcount = 1;
790 nmb->header.ancount = 0;
791 nmb->header.nscount = 0;
792 nmb->header.arcount = 0;
793 nmb->question.question_name = *name;
794 nmb->question.question_type = 0x21;
795 nmb->question.question_class = 0x1;
797 state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
798 &p);
799 if (state->buflen == 0) {
800 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
801 DEBUG(10, ("build_packet failed\n"));
802 return tevent_req_post(req, ev);
805 subreq = nb_trans_send(state, ev, &state->my_addr, &state->addr, false,
806 state->buf, state->buflen,
807 NMB_PACKET, nmb->header.name_trn_id,
808 node_status_query_validator, NULL);
809 if (tevent_req_nomem(subreq, req)) {
810 DEBUG(10, ("nb_trans_send failed\n"));
811 return tevent_req_post(req, ev);
813 if (!tevent_req_set_endtime(req, ev, timeval_current_ofs(10, 0))) {
814 return tevent_req_post(req, ev);
816 tevent_req_set_callback(subreq, node_status_query_done, req);
817 return req;
820 static bool node_status_query_validator(struct packet_struct *p,
821 void *private_data)
823 struct nmb_packet *nmb = &p->packet.nmb;
824 debug_nmb_packet(p);
826 if (nmb->header.opcode != 0 ||
827 nmb->header.nm_flags.bcast ||
828 nmb->header.rcode ||
829 !nmb->header.ancount ||
830 nmb->answers->rr_type != 0x21) {
832 * XXXX what do we do with this? could be a redirect,
833 * but we'll discard it for the moment
835 return false;
837 return true;
840 static int node_status_query_state_destructor(
841 struct node_status_query_state *s)
843 if (s->packet != NULL) {
844 free_packet(s->packet);
845 s->packet = NULL;
847 return 0;
850 static void node_status_query_done(struct tevent_req *subreq)
852 struct tevent_req *req = tevent_req_callback_data(
853 subreq, struct tevent_req);
854 struct node_status_query_state *state = tevent_req_data(
855 req, struct node_status_query_state);
856 NTSTATUS status;
858 status = nb_trans_recv(subreq, &state->packet);
859 TALLOC_FREE(subreq);
860 if (tevent_req_nterror(req, status)) {
861 return;
863 tevent_req_done(req);
866 NTSTATUS node_status_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
867 struct node_status **pnode_status,
868 int *pnum_names,
869 struct node_status_extra *extra)
871 struct node_status_query_state *state = tevent_req_data(
872 req, struct node_status_query_state);
873 struct node_status *node_status;
874 int num_names;
875 NTSTATUS status;
877 if (tevent_req_is_nterror(req, &status)) {
878 return status;
880 node_status = parse_node_status(
881 mem_ctx, &state->packet->packet.nmb.answers->rdata[0],
882 &num_names, extra);
883 if (node_status == NULL) {
884 return NT_STATUS_NO_MEMORY;
886 *pnode_status = node_status;
887 *pnum_names = num_names;
888 return NT_STATUS_OK;
891 NTSTATUS node_status_query(TALLOC_CTX *mem_ctx, struct nmb_name *name,
892 const struct sockaddr_storage *addr,
893 struct node_status **pnode_status,
894 int *pnum_names,
895 struct node_status_extra *extra)
897 TALLOC_CTX *frame = talloc_stackframe();
898 struct tevent_context *ev;
899 struct tevent_req *req;
900 NTSTATUS status = NT_STATUS_NO_MEMORY;
902 ev = samba_tevent_context_init(frame);
903 if (ev == NULL) {
904 goto fail;
906 req = node_status_query_send(ev, ev, name, addr);
907 if (req == NULL) {
908 goto fail;
910 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
911 goto fail;
913 status = node_status_query_recv(req, mem_ctx, pnode_status,
914 pnum_names, extra);
915 fail:
916 TALLOC_FREE(frame);
917 return status;
920 static bool name_status_lmhosts(const struct sockaddr_storage *paddr,
921 int qname_type, fstring pname)
923 FILE *f;
924 char *name;
925 int name_type;
926 struct sockaddr_storage addr;
928 if (paddr->ss_family != AF_INET) {
929 return false;
932 f = startlmhosts(get_dyn_LMHOSTSFILE());
933 if (f == NULL) {
934 return false;
937 while (getlmhostsent(talloc_tos(), f, &name, &name_type, &addr)) {
938 if (addr.ss_family != AF_INET) {
939 continue;
941 if (name_type != qname_type) {
942 continue;
944 if (memcmp(&((const struct sockaddr_in *)paddr)->sin_addr,
945 &((const struct sockaddr_in *)&addr)->sin_addr,
946 sizeof(struct in_addr)) == 0) {
947 fstrcpy(pname, name);
948 endlmhosts(f);
949 return true;
952 endlmhosts(f);
953 return false;
956 /****************************************************************************
957 Find the first type XX name in a node status reply - used for finding
958 a servers name given its IP. Return the matched name in *name.
959 **************************************************************************/
961 bool name_status_find(const char *q_name,
962 int q_type,
963 int type,
964 const struct sockaddr_storage *to_ss,
965 fstring name)
967 char addr[INET6_ADDRSTRLEN];
968 struct sockaddr_storage ss;
969 struct node_status *addrs = NULL;
970 struct nmb_name nname;
971 int count, i;
972 bool result = false;
973 NTSTATUS status;
975 if (lp_disable_netbios()) {
976 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n",
977 q_name, q_type));
978 return False;
981 print_sockaddr(addr, sizeof(addr), to_ss);
983 DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
984 q_type, addr));
986 /* Check the cache first. */
988 if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
989 return True;
992 if (to_ss->ss_family != AF_INET) {
993 /* Can't do node status to IPv6 */
994 return false;
997 result = name_status_lmhosts(to_ss, type, name);
998 if (result) {
999 DBG_DEBUG("Found name %s in lmhosts\n", name);
1000 namecache_status_store(q_name, q_type, type, to_ss, name);
1001 return true;
1004 set_socket_addr_v4(&ss);
1006 /* W2K PDC's seem not to respond to '*'#0. JRA */
1007 make_nmb_name(&nname, q_name, q_type);
1008 status = node_status_query(talloc_tos(), &nname, to_ss,
1009 &addrs, &count, NULL);
1010 if (!NT_STATUS_IS_OK(status)) {
1011 goto done;
1014 for (i=0;i<count;i++) {
1015 /* Find first one of the requested type that's not a GROUP. */
1016 if (addrs[i].type == type && ! (addrs[i].flags & 0x80))
1017 break;
1019 if (i == count)
1020 goto done;
1022 pull_ascii_nstring(name, sizeof(fstring), addrs[i].name);
1024 /* Store the result in the cache. */
1025 /* but don't store an entry for 0x1c names here. Here we have
1026 a single host and DOMAIN<0x1c> names should be a list of hosts */
1028 if ( q_type != 0x1c ) {
1029 namecache_status_store(q_name, q_type, type, to_ss, name);
1032 result = true;
1034 done:
1035 TALLOC_FREE(addrs);
1037 DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
1039 if (result)
1040 DEBUGADD(10, (", name %s ip address is %s", name, addr));
1042 DEBUG(10, ("\n"));
1044 return result;
1048 comparison function used by sort_addr_list
1051 static int addr_compare(const struct sockaddr_storage *ss1,
1052 const struct sockaddr_storage *ss2)
1054 int max_bits1=0, max_bits2=0;
1055 int num_interfaces = iface_count();
1056 int i;
1058 /* Sort IPv4 addresses first. */
1059 if (ss1->ss_family != ss2->ss_family) {
1060 if (ss2->ss_family == AF_INET) {
1061 return 1;
1062 } else {
1063 return -1;
1067 /* Here we know both addresses are of the same
1068 * family. */
1070 for (i=0;i<num_interfaces;i++) {
1071 const struct sockaddr_storage *pss = iface_n_bcast(i);
1072 const unsigned char *p_ss1 = NULL;
1073 const unsigned char *p_ss2 = NULL;
1074 const unsigned char *p_if = NULL;
1075 size_t len = 0;
1076 int bits1, bits2;
1078 if (pss->ss_family != ss1->ss_family) {
1079 /* Ignore interfaces of the wrong type. */
1080 continue;
1082 if (pss->ss_family == AF_INET) {
1083 p_if = (const unsigned char *)
1084 &((const struct sockaddr_in *)pss)->sin_addr;
1085 p_ss1 = (const unsigned char *)
1086 &((const struct sockaddr_in *)ss1)->sin_addr;
1087 p_ss2 = (const unsigned char *)
1088 &((const struct sockaddr_in *)ss2)->sin_addr;
1089 len = 4;
1091 #if defined(HAVE_IPV6)
1092 if (pss->ss_family == AF_INET6) {
1093 p_if = (const unsigned char *)
1094 &((const struct sockaddr_in6 *)pss)->sin6_addr;
1095 p_ss1 = (const unsigned char *)
1096 &((const struct sockaddr_in6 *)ss1)->sin6_addr;
1097 p_ss2 = (const unsigned char *)
1098 &((const struct sockaddr_in6 *)ss2)->sin6_addr;
1099 len = 16;
1101 #endif
1102 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
1103 continue;
1105 bits1 = matching_len_bits(p_ss1, p_if, len);
1106 bits2 = matching_len_bits(p_ss2, p_if, len);
1107 max_bits1 = MAX(bits1, max_bits1);
1108 max_bits2 = MAX(bits2, max_bits2);
1111 /* Bias towards directly reachable IPs */
1112 if (iface_local((const struct sockaddr *)ss1)) {
1113 if (ss1->ss_family == AF_INET) {
1114 max_bits1 += 32;
1115 } else {
1116 max_bits1 += 128;
1119 if (iface_local((const struct sockaddr *)ss2)) {
1120 if (ss2->ss_family == AF_INET) {
1121 max_bits2 += 32;
1122 } else {
1123 max_bits2 += 128;
1126 return max_bits2 - max_bits1;
1129 /*******************************************************************
1130 compare 2 ldap IPs by nearness to our interfaces - used in qsort
1131 *******************************************************************/
1133 static int ip_service_compare(struct ip_service *ss1, struct ip_service *ss2)
1135 int result;
1137 if ((result = addr_compare(&ss1->ss, &ss2->ss)) != 0) {
1138 return result;
1141 if (ss1->port > ss2->port) {
1142 return 1;
1145 if (ss1->port < ss2->port) {
1146 return -1;
1149 return 0;
1153 sort an IP list so that names that are close to one of our interfaces
1154 are at the top. This prevents the problem where a WINS server returns an IP
1155 that is not reachable from our subnet as the first match
1158 static void sort_addr_list(struct sockaddr_storage *sslist, int count)
1160 if (count <= 1) {
1161 return;
1164 TYPESAFE_QSORT(sslist, count, addr_compare);
1167 static void sort_service_list(struct ip_service *servlist, int count)
1169 if (count <= 1) {
1170 return;
1173 TYPESAFE_QSORT(servlist, count, ip_service_compare);
1176 /**********************************************************************
1177 Remove any duplicate address/port pairs in the list
1178 *********************************************************************/
1180 int remove_duplicate_addrs2(struct ip_service *iplist, int count )
1182 int i, j;
1184 DEBUG(10,("remove_duplicate_addrs2: "
1185 "looking for duplicate address/port pairs\n"));
1187 /* One loop to set duplicates to a zero addr. */
1188 for ( i=0; i<count; i++ ) {
1189 if ( is_zero_addr(&iplist[i].ss)) {
1190 continue;
1193 for ( j=i+1; j<count; j++ ) {
1194 if (sockaddr_equal((struct sockaddr *)(void *)&iplist[i].ss,
1195 (struct sockaddr *)(void *)&iplist[j].ss) &&
1196 iplist[i].port == iplist[j].port) {
1197 zero_sockaddr(&iplist[j].ss);
1202 /* Now remove any addresses set to zero above. */
1203 for (i = 0; i < count; i++) {
1204 while (i < count &&
1205 is_zero_addr(&iplist[i].ss)) {
1206 if (count-i-1>0) {
1207 memmove(&iplist[i],
1208 &iplist[i+1],
1209 (count-i-1)*sizeof(struct ip_service));
1211 count--;
1215 return count;
1218 static bool prioritize_ipv4_list(struct ip_service *iplist, int count)
1220 TALLOC_CTX *frame = talloc_stackframe();
1221 struct ip_service *iplist_new = talloc_array(frame, struct ip_service, count);
1222 int i, j;
1224 if (iplist_new == NULL) {
1225 TALLOC_FREE(frame);
1226 return false;
1229 j = 0;
1231 /* Copy IPv4 first. */
1232 for (i = 0; i < count; i++) {
1233 if (iplist[i].ss.ss_family == AF_INET) {
1234 iplist_new[j++] = iplist[i];
1238 /* Copy IPv6. */
1239 for (i = 0; i < count; i++) {
1240 if (iplist[i].ss.ss_family != AF_INET) {
1241 iplist_new[j++] = iplist[i];
1245 memcpy(iplist, iplist_new, sizeof(struct ip_service)*count);
1246 TALLOC_FREE(frame);
1247 return true;
1250 /****************************************************************************
1251 Do a netbios name query to find someones IP.
1252 Returns an array of IP addresses or NULL if none.
1253 *count will be set to the number of addresses returned.
1254 *timed_out is set if we failed by timing out
1255 ****************************************************************************/
1257 struct name_query_state {
1258 struct sockaddr_storage my_addr;
1259 struct sockaddr_storage addr;
1260 bool bcast;
1263 uint8_t buf[1024];
1264 ssize_t buflen;
1266 NTSTATUS validate_error;
1267 uint8_t flags;
1269 struct sockaddr_storage *addrs;
1270 int num_addrs;
1273 static bool name_query_validator(struct packet_struct *p, void *private_data);
1274 static void name_query_done(struct tevent_req *subreq);
1276 struct tevent_req *name_query_send(TALLOC_CTX *mem_ctx,
1277 struct tevent_context *ev,
1278 const char *name, int name_type,
1279 bool bcast, bool recurse,
1280 const struct sockaddr_storage *addr)
1282 struct tevent_req *req, *subreq;
1283 struct name_query_state *state;
1284 struct packet_struct p;
1285 struct nmb_packet *nmb = &p.packet.nmb;
1286 struct sockaddr_in *in_addr;
1288 req = tevent_req_create(mem_ctx, &state, struct name_query_state);
1289 if (req == NULL) {
1290 return NULL;
1292 state->bcast = bcast;
1294 if (addr->ss_family != AF_INET) {
1295 /* Can't do node status to IPv6 */
1296 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
1297 return tevent_req_post(req, ev);
1300 if (lp_disable_netbios()) {
1301 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
1302 name, name_type));
1303 tevent_req_nterror(req, NT_STATUS_NOT_SUPPORTED);
1304 return tevent_req_post(req, ev);
1307 state->addr = *addr;
1308 in_addr = (struct sockaddr_in *)(void *)&state->addr;
1309 in_addr->sin_port = htons(NMB_PORT);
1311 set_socket_addr_v4(&state->my_addr);
1313 ZERO_STRUCT(p);
1314 nmb->header.name_trn_id = generate_trn_id();
1315 nmb->header.opcode = 0;
1316 nmb->header.response = false;
1317 nmb->header.nm_flags.bcast = bcast;
1318 nmb->header.nm_flags.recursion_available = false;
1319 nmb->header.nm_flags.recursion_desired = recurse;
1320 nmb->header.nm_flags.trunc = false;
1321 nmb->header.nm_flags.authoritative = false;
1322 nmb->header.rcode = 0;
1323 nmb->header.qdcount = 1;
1324 nmb->header.ancount = 0;
1325 nmb->header.nscount = 0;
1326 nmb->header.arcount = 0;
1328 make_nmb_name(&nmb->question.question_name,name,name_type);
1330 nmb->question.question_type = 0x20;
1331 nmb->question.question_class = 0x1;
1333 state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
1334 &p);
1335 if (state->buflen == 0) {
1336 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1337 DEBUG(10, ("build_packet failed\n"));
1338 return tevent_req_post(req, ev);
1341 subreq = nb_trans_send(state, ev, &state->my_addr, &state->addr, bcast,
1342 state->buf, state->buflen,
1343 NMB_PACKET, nmb->header.name_trn_id,
1344 name_query_validator, state);
1345 if (tevent_req_nomem(subreq, req)) {
1346 DEBUG(10, ("nb_trans_send failed\n"));
1347 return tevent_req_post(req, ev);
1349 tevent_req_set_callback(subreq, name_query_done, req);
1350 return req;
1353 static bool name_query_validator(struct packet_struct *p, void *private_data)
1355 struct name_query_state *state = talloc_get_type_abort(
1356 private_data, struct name_query_state);
1357 struct nmb_packet *nmb = &p->packet.nmb;
1358 struct sockaddr_storage *tmp_addrs;
1359 bool got_unique_netbios_name = false;
1360 int i;
1362 debug_nmb_packet(p);
1365 * If we get a Negative Name Query Response from a WINS
1366 * server, we should report it and give up.
1368 if( 0 == nmb->header.opcode /* A query response */
1369 && !state->bcast /* from a WINS server */
1370 && nmb->header.rcode /* Error returned */
1373 if( DEBUGLVL( 3 ) ) {
1374 /* Only executed if DEBUGLEVEL >= 3 */
1375 dbgtext( "Negative name query "
1376 "response, rcode 0x%02x: ",
1377 nmb->header.rcode );
1378 switch( nmb->header.rcode ) {
1379 case 0x01:
1380 dbgtext("Request was invalidly formatted.\n");
1381 break;
1382 case 0x02:
1383 dbgtext("Problem with NBNS, cannot process "
1384 "name.\n");
1385 break;
1386 case 0x03:
1387 dbgtext("The name requested does not "
1388 "exist.\n");
1389 break;
1390 case 0x04:
1391 dbgtext("Unsupported request error.\n");
1392 break;
1393 case 0x05:
1394 dbgtext("Query refused error.\n");
1395 break;
1396 default:
1397 dbgtext("Unrecognized error code.\n" );
1398 break;
1403 * We accept this packet as valid, but tell the upper
1404 * layers that it's a negative response.
1406 state->validate_error = NT_STATUS_NOT_FOUND;
1407 return true;
1410 if (nmb->header.opcode != 0 ||
1411 nmb->header.nm_flags.bcast ||
1412 nmb->header.rcode ||
1413 !nmb->header.ancount) {
1415 * XXXX what do we do with this? Could be a redirect,
1416 * but we'll discard it for the moment.
1418 return false;
1421 tmp_addrs = talloc_realloc(
1422 state, state->addrs, struct sockaddr_storage,
1423 state->num_addrs + nmb->answers->rdlength/6);
1424 if (tmp_addrs == NULL) {
1425 state->validate_error = NT_STATUS_NO_MEMORY;
1426 return true;
1428 state->addrs = tmp_addrs;
1430 DEBUG(2,("Got a positive name query response "
1431 "from %s ( ", inet_ntoa(p->ip)));
1433 for (i=0; i<nmb->answers->rdlength/6; i++) {
1434 uint16_t flags;
1435 struct in_addr ip;
1436 struct sockaddr_storage addr;
1437 int j;
1439 flags = RSVAL(&nmb->answers->rdata[i*6], 0);
1440 got_unique_netbios_name |= ((flags & 0x8000) == 0);
1442 putip((char *)&ip,&nmb->answers->rdata[2+i*6]);
1443 in_addr_to_sockaddr_storage(&addr, ip);
1445 if (is_zero_addr(&addr)) {
1446 continue;
1449 for (j=0; j<state->num_addrs; j++) {
1450 if (sockaddr_equal(
1451 (struct sockaddr *)(void *)&addr,
1452 (struct sockaddr *)(void *)&state->addrs[j])) {
1453 break;
1456 if (j < state->num_addrs) {
1457 /* Already got it */
1458 continue;
1461 DEBUGADD(2,("%s ",inet_ntoa(ip)));
1463 state->addrs[state->num_addrs] = addr;
1464 state->num_addrs += 1;
1466 DEBUGADD(2,(")\n"));
1468 /* We add the flags back ... */
1469 if (nmb->header.response)
1470 state->flags |= NM_FLAGS_RS;
1471 if (nmb->header.nm_flags.authoritative)
1472 state->flags |= NM_FLAGS_AA;
1473 if (nmb->header.nm_flags.trunc)
1474 state->flags |= NM_FLAGS_TC;
1475 if (nmb->header.nm_flags.recursion_desired)
1476 state->flags |= NM_FLAGS_RD;
1477 if (nmb->header.nm_flags.recursion_available)
1478 state->flags |= NM_FLAGS_RA;
1479 if (nmb->header.nm_flags.bcast)
1480 state->flags |= NM_FLAGS_B;
1482 if (state->bcast) {
1484 * We have to collect all entries coming in from broadcast
1485 * queries. If we got a unique name, we're done.
1487 return got_unique_netbios_name;
1490 * WINS responses are accepted when they are received
1492 return true;
1495 static void name_query_done(struct tevent_req *subreq)
1497 struct tevent_req *req = tevent_req_callback_data(
1498 subreq, struct tevent_req);
1499 struct name_query_state *state = tevent_req_data(
1500 req, struct name_query_state);
1501 NTSTATUS status;
1502 struct packet_struct *p = NULL;
1504 status = nb_trans_recv(subreq, &p);
1505 TALLOC_FREE(subreq);
1506 if (tevent_req_nterror(req, status)) {
1507 return;
1509 if (!NT_STATUS_IS_OK(state->validate_error)) {
1510 tevent_req_nterror(req, state->validate_error);
1511 return;
1513 if (p != NULL) {
1515 * Free the packet here, we've collected the response in the
1516 * validator
1518 free_packet(p);
1520 tevent_req_done(req);
1523 NTSTATUS name_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1524 struct sockaddr_storage **addrs, int *num_addrs,
1525 uint8_t *flags)
1527 struct name_query_state *state = tevent_req_data(
1528 req, struct name_query_state);
1529 NTSTATUS status;
1531 if (tevent_req_is_nterror(req, &status)) {
1532 if (state->bcast &&
1533 NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
1535 * In the broadcast case we collect replies until the
1536 * timeout.
1538 status = NT_STATUS_OK;
1540 if (!NT_STATUS_IS_OK(status)) {
1541 return status;
1544 if (state->num_addrs == 0) {
1545 return NT_STATUS_NOT_FOUND;
1547 *addrs = talloc_move(mem_ctx, &state->addrs);
1548 sort_addr_list(*addrs, state->num_addrs);
1549 *num_addrs = state->num_addrs;
1550 if (flags != NULL) {
1551 *flags = state->flags;
1553 return NT_STATUS_OK;
1556 NTSTATUS name_query(const char *name, int name_type,
1557 bool bcast, bool recurse,
1558 const struct sockaddr_storage *to_ss,
1559 TALLOC_CTX *mem_ctx,
1560 struct sockaddr_storage **addrs,
1561 int *num_addrs, uint8_t *flags)
1563 TALLOC_CTX *frame = talloc_stackframe();
1564 struct tevent_context *ev;
1565 struct tevent_req *req;
1566 struct timeval timeout;
1567 NTSTATUS status = NT_STATUS_NO_MEMORY;
1569 ev = samba_tevent_context_init(frame);
1570 if (ev == NULL) {
1571 goto fail;
1573 req = name_query_send(ev, ev, name, name_type, bcast, recurse, to_ss);
1574 if (req == NULL) {
1575 goto fail;
1577 if (bcast) {
1578 timeout = timeval_current_ofs(0, 250000);
1579 } else {
1580 timeout = timeval_current_ofs(2, 0);
1582 if (!tevent_req_set_endtime(req, ev, timeout)) {
1583 goto fail;
1585 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
1586 goto fail;
1588 status = name_query_recv(req, mem_ctx, addrs, num_addrs, flags);
1589 fail:
1590 TALLOC_FREE(frame);
1591 return status;
1594 /********************************************************
1595 Convert an array if struct sockaddr_storage to struct ip_service
1596 return false on failure. Port is set to PORT_NONE;
1597 pcount is [in/out] - it is the length of ss_list on input,
1598 and the length of return_iplist on output as we remove any
1599 zero addresses from ss_list.
1600 *********************************************************/
1602 static bool convert_ss2service(struct ip_service **return_iplist,
1603 const struct sockaddr_storage *ss_list,
1604 int *pcount)
1606 int i;
1607 int orig_count = *pcount;
1608 int real_count = 0;
1610 if (orig_count==0 || !ss_list )
1611 return False;
1613 /* Filter out zero addrs. */
1614 for ( i=0; i<orig_count; i++ ) {
1615 if (is_zero_addr(&ss_list[i])) {
1616 continue;
1618 real_count++;
1620 if (real_count==0) {
1621 return false;
1624 /* copy the ip address; port will be PORT_NONE */
1625 if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, real_count)) ==
1626 NULL) {
1627 DEBUG(0,("convert_ip2service: malloc failed "
1628 "for %d enetries!\n", real_count ));
1629 return False;
1632 for ( i=0, real_count = 0; i<orig_count; i++ ) {
1633 if (is_zero_addr(&ss_list[i])) {
1634 continue;
1636 (*return_iplist)[real_count].ss = ss_list[i];
1637 (*return_iplist)[real_count].port = PORT_NONE;
1638 real_count++;
1641 *pcount = real_count;
1642 return true;
1645 struct name_queries_state {
1646 struct tevent_context *ev;
1647 const char *name;
1648 int name_type;
1649 bool bcast;
1650 bool recurse;
1651 const struct sockaddr_storage *addrs;
1652 int num_addrs;
1653 int wait_msec;
1654 int timeout_msec;
1656 struct tevent_req **subreqs;
1657 int num_received;
1658 int num_sent;
1660 int received_index;
1661 struct sockaddr_storage *result_addrs;
1662 int num_result_addrs;
1663 uint8_t flags;
1666 static void name_queries_done(struct tevent_req *subreq);
1667 static void name_queries_next(struct tevent_req *subreq);
1670 * Send a name query to multiple destinations with a wait time in between
1673 static struct tevent_req *name_queries_send(
1674 TALLOC_CTX *mem_ctx, struct tevent_context *ev,
1675 const char *name, int name_type,
1676 bool bcast, bool recurse,
1677 const struct sockaddr_storage *addrs,
1678 int num_addrs, int wait_msec, int timeout_msec)
1680 struct tevent_req *req, *subreq;
1681 struct name_queries_state *state;
1683 req = tevent_req_create(mem_ctx, &state,
1684 struct name_queries_state);
1685 if (req == NULL) {
1686 return NULL;
1688 state->ev = ev;
1689 state->name = name;
1690 state->name_type = name_type;
1691 state->bcast = bcast;
1692 state->recurse = recurse;
1693 state->addrs = addrs;
1694 state->num_addrs = num_addrs;
1695 state->wait_msec = wait_msec;
1696 state->timeout_msec = timeout_msec;
1698 state->subreqs = talloc_zero_array(
1699 state, struct tevent_req *, num_addrs);
1700 if (tevent_req_nomem(state->subreqs, req)) {
1701 return tevent_req_post(req, ev);
1703 state->num_sent = 0;
1705 subreq = name_query_send(
1706 state->subreqs, state->ev, name, name_type, bcast, recurse,
1707 &state->addrs[state->num_sent]);
1708 if (tevent_req_nomem(subreq, req)) {
1709 return tevent_req_post(req, ev);
1711 if (!tevent_req_set_endtime(
1712 subreq, state->ev,
1713 timeval_current_ofs(0, state->timeout_msec * 1000))) {
1714 tevent_req_oom(req);
1715 return tevent_req_post(req, ev);
1717 tevent_req_set_callback(subreq, name_queries_done, req);
1719 state->subreqs[state->num_sent] = subreq;
1720 state->num_sent += 1;
1722 if (state->num_sent < state->num_addrs) {
1723 subreq = tevent_wakeup_send(
1724 state, state->ev,
1725 timeval_current_ofs(0, state->wait_msec * 1000));
1726 if (tevent_req_nomem(subreq, req)) {
1727 return tevent_req_post(req, ev);
1729 tevent_req_set_callback(subreq, name_queries_next, req);
1731 return req;
1734 static void name_queries_done(struct tevent_req *subreq)
1736 struct tevent_req *req = tevent_req_callback_data(
1737 subreq, struct tevent_req);
1738 struct name_queries_state *state = tevent_req_data(
1739 req, struct name_queries_state);
1740 int i;
1741 NTSTATUS status;
1743 status = name_query_recv(subreq, state, &state->result_addrs,
1744 &state->num_result_addrs, &state->flags);
1746 for (i=0; i<state->num_sent; i++) {
1747 if (state->subreqs[i] == subreq) {
1748 break;
1751 if (i == state->num_sent) {
1752 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1753 return;
1755 TALLOC_FREE(state->subreqs[i]);
1757 state->num_received += 1;
1759 if (!NT_STATUS_IS_OK(status)) {
1761 if (state->num_received >= state->num_addrs) {
1762 tevent_req_nterror(req, status);
1763 return;
1766 * Still outstanding requests, just wait
1768 return;
1770 state->received_index = i;
1771 tevent_req_done(req);
1774 static void name_queries_next(struct tevent_req *subreq)
1776 struct tevent_req *req = tevent_req_callback_data(
1777 subreq, struct tevent_req);
1778 struct name_queries_state *state = tevent_req_data(
1779 req, struct name_queries_state);
1781 if (!tevent_wakeup_recv(subreq)) {
1782 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1783 return;
1786 subreq = name_query_send(
1787 state->subreqs, state->ev,
1788 state->name, state->name_type, state->bcast, state->recurse,
1789 &state->addrs[state->num_sent]);
1790 if (tevent_req_nomem(subreq, req)) {
1791 return;
1793 tevent_req_set_callback(subreq, name_queries_done, req);
1794 if (!tevent_req_set_endtime(
1795 subreq, state->ev,
1796 timeval_current_ofs(0, state->timeout_msec * 1000))) {
1797 tevent_req_oom(req);
1798 return;
1800 state->subreqs[state->num_sent] = subreq;
1801 state->num_sent += 1;
1803 if (state->num_sent < state->num_addrs) {
1804 subreq = tevent_wakeup_send(
1805 state, state->ev,
1806 timeval_current_ofs(0, state->wait_msec * 1000));
1807 if (tevent_req_nomem(subreq, req)) {
1808 return;
1810 tevent_req_set_callback(subreq, name_queries_next, req);
1814 static NTSTATUS name_queries_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1815 struct sockaddr_storage **result_addrs,
1816 int *num_result_addrs, uint8_t *flags,
1817 int *received_index)
1819 struct name_queries_state *state = tevent_req_data(
1820 req, struct name_queries_state);
1821 NTSTATUS status;
1823 if (tevent_req_is_nterror(req, &status)) {
1824 return status;
1827 if (result_addrs != NULL) {
1828 *result_addrs = talloc_move(mem_ctx, &state->result_addrs);
1830 if (num_result_addrs != NULL) {
1831 *num_result_addrs = state->num_result_addrs;
1833 if (flags != NULL) {
1834 *flags = state->flags;
1836 if (received_index != NULL) {
1837 *received_index = state->received_index;
1839 return NT_STATUS_OK;
1842 /********************************************************
1843 Resolve via "bcast" method.
1844 *********************************************************/
1846 struct name_resolve_bcast_state {
1847 struct sockaddr_storage *addrs;
1848 int num_addrs;
1851 static void name_resolve_bcast_done(struct tevent_req *subreq);
1853 struct tevent_req *name_resolve_bcast_send(TALLOC_CTX *mem_ctx,
1854 struct tevent_context *ev,
1855 const char *name,
1856 int name_type)
1858 struct tevent_req *req, *subreq;
1859 struct name_resolve_bcast_state *state;
1860 struct sockaddr_storage *bcast_addrs;
1861 int i, num_addrs, num_bcast_addrs;
1863 req = tevent_req_create(mem_ctx, &state,
1864 struct name_resolve_bcast_state);
1865 if (req == NULL) {
1866 return NULL;
1869 if (lp_disable_netbios()) {
1870 DEBUG(5, ("name_resolve_bcast(%s#%02x): netbios is disabled\n",
1871 name, name_type));
1872 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1873 return tevent_req_post(req, ev);
1877 * "bcast" means do a broadcast lookup on all the local interfaces.
1880 DEBUG(3, ("name_resolve_bcast: Attempting broadcast lookup "
1881 "for name %s<0x%x>\n", name, name_type));
1883 num_addrs = iface_count();
1884 bcast_addrs = talloc_array(state, struct sockaddr_storage, num_addrs);
1885 if (tevent_req_nomem(bcast_addrs, req)) {
1886 return tevent_req_post(req, ev);
1890 * Lookup the name on all the interfaces, return on
1891 * the first successful match.
1893 num_bcast_addrs = 0;
1895 for (i=0; i<num_addrs; i++) {
1896 const struct sockaddr_storage *pss = iface_n_bcast(i);
1898 if (pss->ss_family != AF_INET) {
1899 continue;
1901 bcast_addrs[num_bcast_addrs] = *pss;
1902 num_bcast_addrs += 1;
1905 subreq = name_queries_send(state, ev, name, name_type, true, true,
1906 bcast_addrs, num_bcast_addrs, 0, 1000);
1907 if (tevent_req_nomem(subreq, req)) {
1908 return tevent_req_post(req, ev);
1910 tevent_req_set_callback(subreq, name_resolve_bcast_done, req);
1911 return req;
1914 static void name_resolve_bcast_done(struct tevent_req *subreq)
1916 struct tevent_req *req = tevent_req_callback_data(
1917 subreq, struct tevent_req);
1918 struct name_resolve_bcast_state *state = tevent_req_data(
1919 req, struct name_resolve_bcast_state);
1920 NTSTATUS status;
1922 status = name_queries_recv(subreq, state,
1923 &state->addrs, &state->num_addrs,
1924 NULL, NULL);
1925 TALLOC_FREE(subreq);
1926 if (tevent_req_nterror(req, status)) {
1927 return;
1929 tevent_req_done(req);
1932 NTSTATUS name_resolve_bcast_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1933 struct sockaddr_storage **addrs,
1934 int *num_addrs)
1936 struct name_resolve_bcast_state *state = tevent_req_data(
1937 req, struct name_resolve_bcast_state);
1938 NTSTATUS status;
1940 if (tevent_req_is_nterror(req, &status)) {
1941 return status;
1943 *addrs = talloc_move(mem_ctx, &state->addrs);
1944 *num_addrs = state->num_addrs;
1945 return NT_STATUS_OK;
1948 NTSTATUS name_resolve_bcast(const char *name,
1949 int name_type,
1950 TALLOC_CTX *mem_ctx,
1951 struct sockaddr_storage **return_iplist,
1952 int *return_count)
1954 TALLOC_CTX *frame = talloc_stackframe();
1955 struct tevent_context *ev;
1956 struct tevent_req *req;
1957 NTSTATUS status = NT_STATUS_NO_MEMORY;
1959 ev = samba_tevent_context_init(frame);
1960 if (ev == NULL) {
1961 goto fail;
1963 req = name_resolve_bcast_send(frame, ev, name, name_type);
1964 if (req == NULL) {
1965 goto fail;
1967 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
1968 goto fail;
1970 status = name_resolve_bcast_recv(req, mem_ctx, return_iplist,
1971 return_count);
1972 fail:
1973 TALLOC_FREE(frame);
1974 return status;
1977 struct query_wins_list_state {
1978 struct tevent_context *ev;
1979 const char *name;
1980 uint8_t name_type;
1981 struct in_addr *servers;
1982 uint32_t num_servers;
1983 struct sockaddr_storage server;
1984 uint32_t num_sent;
1986 struct sockaddr_storage *addrs;
1987 int num_addrs;
1988 uint8_t flags;
1991 static void query_wins_list_done(struct tevent_req *subreq);
1994 * Query a list of (replicating) wins servers in sequence, call them
1995 * dead if they don't reply
1998 static struct tevent_req *query_wins_list_send(
1999 TALLOC_CTX *mem_ctx, struct tevent_context *ev,
2000 struct in_addr src_ip, const char *name, uint8_t name_type,
2001 struct in_addr *servers, int num_servers)
2003 struct tevent_req *req, *subreq;
2004 struct query_wins_list_state *state;
2006 req = tevent_req_create(mem_ctx, &state,
2007 struct query_wins_list_state);
2008 if (req == NULL) {
2009 return NULL;
2011 state->ev = ev;
2012 state->name = name;
2013 state->name_type = name_type;
2014 state->servers = servers;
2015 state->num_servers = num_servers;
2017 if (state->num_servers == 0) {
2018 tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
2019 return tevent_req_post(req, ev);
2022 in_addr_to_sockaddr_storage(
2023 &state->server, state->servers[state->num_sent]);
2025 subreq = name_query_send(state, state->ev,
2026 state->name, state->name_type,
2027 false, true, &state->server);
2028 state->num_sent += 1;
2029 if (tevent_req_nomem(subreq, req)) {
2030 return tevent_req_post(req, ev);
2032 if (!tevent_req_set_endtime(subreq, state->ev,
2033 timeval_current_ofs(2, 0))) {
2034 tevent_req_oom(req);
2035 return tevent_req_post(req, ev);
2037 tevent_req_set_callback(subreq, query_wins_list_done, req);
2038 return req;
2041 static void query_wins_list_done(struct tevent_req *subreq)
2043 struct tevent_req *req = tevent_req_callback_data(
2044 subreq, struct tevent_req);
2045 struct query_wins_list_state *state = tevent_req_data(
2046 req, struct query_wins_list_state);
2047 NTSTATUS status;
2049 status = name_query_recv(subreq, state,
2050 &state->addrs, &state->num_addrs,
2051 &state->flags);
2052 TALLOC_FREE(subreq);
2053 if (NT_STATUS_IS_OK(status)) {
2054 tevent_req_done(req);
2055 return;
2057 if (!NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
2058 tevent_req_nterror(req, status);
2059 return;
2061 wins_srv_died(state->servers[state->num_sent-1],
2062 my_socket_addr_v4());
2064 if (state->num_sent == state->num_servers) {
2065 tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
2066 return;
2069 in_addr_to_sockaddr_storage(
2070 &state->server, state->servers[state->num_sent]);
2072 subreq = name_query_send(state, state->ev,
2073 state->name, state->name_type,
2074 false, true, &state->server);
2075 state->num_sent += 1;
2076 if (tevent_req_nomem(subreq, req)) {
2077 return;
2079 if (!tevent_req_set_endtime(subreq, state->ev,
2080 timeval_current_ofs(2, 0))) {
2081 tevent_req_oom(req);
2082 return;
2084 tevent_req_set_callback(subreq, query_wins_list_done, req);
2087 static NTSTATUS query_wins_list_recv(struct tevent_req *req,
2088 TALLOC_CTX *mem_ctx,
2089 struct sockaddr_storage **addrs,
2090 int *num_addrs,
2091 uint8_t *flags)
2093 struct query_wins_list_state *state = tevent_req_data(
2094 req, struct query_wins_list_state);
2095 NTSTATUS status;
2097 if (tevent_req_is_nterror(req, &status)) {
2098 return status;
2100 if (addrs != NULL) {
2101 *addrs = talloc_move(mem_ctx, &state->addrs);
2103 if (num_addrs != NULL) {
2104 *num_addrs = state->num_addrs;
2106 if (flags != NULL) {
2107 *flags = state->flags;
2109 return NT_STATUS_OK;
2112 struct resolve_wins_state {
2113 int num_sent;
2114 int num_received;
2116 struct sockaddr_storage *addrs;
2117 int num_addrs;
2118 uint8_t flags;
2121 static void resolve_wins_done(struct tevent_req *subreq);
2123 struct tevent_req *resolve_wins_send(TALLOC_CTX *mem_ctx,
2124 struct tevent_context *ev,
2125 const char *name,
2126 int name_type)
2128 struct tevent_req *req, *subreq;
2129 struct resolve_wins_state *state;
2130 char **wins_tags = NULL;
2131 struct sockaddr_storage src_ss;
2132 struct in_addr src_ip;
2133 int i, num_wins_tags;
2135 req = tevent_req_create(mem_ctx, &state,
2136 struct resolve_wins_state);
2137 if (req == NULL) {
2138 return NULL;
2141 if (wins_srv_count() < 1) {
2142 DEBUG(3,("resolve_wins: WINS server resolution selected "
2143 "and no WINS servers listed.\n"));
2144 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2145 goto fail;
2148 /* the address we will be sending from */
2149 if (!interpret_string_addr(&src_ss, lp_nbt_client_socket_address(),
2150 AI_NUMERICHOST|AI_PASSIVE)) {
2151 zero_sockaddr(&src_ss);
2154 if (src_ss.ss_family != AF_INET) {
2155 char addr[INET6_ADDRSTRLEN];
2156 print_sockaddr(addr, sizeof(addr), &src_ss);
2157 DEBUG(3,("resolve_wins: cannot receive WINS replies "
2158 "on IPv6 address %s\n",
2159 addr));
2160 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2161 goto fail;
2164 src_ip = ((const struct sockaddr_in *)(void *)&src_ss)->sin_addr;
2166 wins_tags = wins_srv_tags();
2167 if (wins_tags == NULL) {
2168 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2169 goto fail;
2172 num_wins_tags = 0;
2173 while (wins_tags[num_wins_tags] != NULL) {
2174 num_wins_tags += 1;
2177 for (i=0; i<num_wins_tags; i++) {
2178 int num_servers, num_alive;
2179 struct in_addr *servers, *alive;
2180 int j;
2182 if (!wins_server_tag_ips(wins_tags[i], talloc_tos(),
2183 &servers, &num_servers)) {
2184 DEBUG(10, ("wins_server_tag_ips failed for tag %s\n",
2185 wins_tags[i]));
2186 continue;
2189 alive = talloc_array(state, struct in_addr, num_servers);
2190 if (tevent_req_nomem(alive, req)) {
2191 goto fail;
2194 num_alive = 0;
2195 for (j=0; j<num_servers; j++) {
2196 struct in_addr wins_ip = servers[j];
2198 if (global_in_nmbd && ismyip_v4(wins_ip)) {
2199 /* yikes! we'll loop forever */
2200 continue;
2202 /* skip any that have been unresponsive lately */
2203 if (wins_srv_is_dead(wins_ip, src_ip)) {
2204 continue;
2206 DEBUG(3, ("resolve_wins: using WINS server %s "
2207 "and tag '%s'\n",
2208 inet_ntoa(wins_ip), wins_tags[i]));
2209 alive[num_alive] = wins_ip;
2210 num_alive += 1;
2212 TALLOC_FREE(servers);
2214 if (num_alive == 0) {
2215 continue;
2218 subreq = query_wins_list_send(
2219 state, ev, src_ip, name, name_type,
2220 alive, num_alive);
2221 if (tevent_req_nomem(subreq, req)) {
2222 goto fail;
2224 tevent_req_set_callback(subreq, resolve_wins_done, req);
2225 state->num_sent += 1;
2228 if (state->num_sent == 0) {
2229 tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
2230 goto fail;
2233 wins_srv_tags_free(wins_tags);
2234 return req;
2235 fail:
2236 wins_srv_tags_free(wins_tags);
2237 return tevent_req_post(req, ev);
2240 static void resolve_wins_done(struct tevent_req *subreq)
2242 struct tevent_req *req = tevent_req_callback_data(
2243 subreq, struct tevent_req);
2244 struct resolve_wins_state *state = tevent_req_data(
2245 req, struct resolve_wins_state);
2246 NTSTATUS status;
2248 status = query_wins_list_recv(subreq, state, &state->addrs,
2249 &state->num_addrs, &state->flags);
2250 if (NT_STATUS_IS_OK(status)) {
2251 tevent_req_done(req);
2252 return;
2255 state->num_received += 1;
2257 if (state->num_received < state->num_sent) {
2259 * Wait for the others
2261 return;
2263 tevent_req_nterror(req, status);
2266 NTSTATUS resolve_wins_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
2267 struct sockaddr_storage **addrs,
2268 int *num_addrs, uint8_t *flags)
2270 struct resolve_wins_state *state = tevent_req_data(
2271 req, struct resolve_wins_state);
2272 NTSTATUS status;
2274 if (tevent_req_is_nterror(req, &status)) {
2275 return status;
2277 if (addrs != NULL) {
2278 *addrs = talloc_move(mem_ctx, &state->addrs);
2280 if (num_addrs != NULL) {
2281 *num_addrs = state->num_addrs;
2283 if (flags != NULL) {
2284 *flags = state->flags;
2286 return NT_STATUS_OK;
2289 /********************************************************
2290 Resolve via "wins" method.
2291 *********************************************************/
2293 NTSTATUS resolve_wins(const char *name,
2294 int name_type,
2295 TALLOC_CTX *mem_ctx,
2296 struct sockaddr_storage **return_iplist,
2297 int *return_count)
2299 struct tevent_context *ev;
2300 struct tevent_req *req;
2301 NTSTATUS status = NT_STATUS_NO_MEMORY;
2303 ev = samba_tevent_context_init(talloc_tos());
2304 if (ev == NULL) {
2305 goto fail;
2307 req = resolve_wins_send(ev, ev, name, name_type);
2308 if (req == NULL) {
2309 goto fail;
2311 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
2312 goto fail;
2314 status = resolve_wins_recv(req, mem_ctx, return_iplist, return_count,
2315 NULL);
2316 fail:
2317 TALLOC_FREE(ev);
2318 return status;
2321 /********************************************************
2322 Resolve via "hosts" method.
2323 *********************************************************/
2325 static NTSTATUS resolve_hosts(const char *name, int name_type,
2326 TALLOC_CTX *mem_ctx,
2327 struct sockaddr_storage **return_iplist,
2328 int *return_count)
2331 * "host" means do a localhost, or dns lookup.
2333 struct addrinfo hints;
2334 struct addrinfo *ailist = NULL;
2335 struct addrinfo *res = NULL;
2336 int ret = -1;
2337 int i = 0;
2339 if ( name_type != 0x20 && name_type != 0x0) {
2340 DEBUG(5, ("resolve_hosts: not appropriate "
2341 "for name type <0x%x>\n",
2342 name_type));
2343 return NT_STATUS_INVALID_PARAMETER;
2346 *return_iplist = NULL;
2347 *return_count = 0;
2349 DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
2350 name, name_type));
2352 ZERO_STRUCT(hints);
2353 /* By default make sure it supports TCP. */
2354 hints.ai_socktype = SOCK_STREAM;
2355 hints.ai_flags = AI_ADDRCONFIG;
2357 #if !defined(HAVE_IPV6)
2358 /* Unless we have IPv6, we really only want IPv4 addresses back. */
2359 hints.ai_family = AF_INET;
2360 #endif
2362 ret = getaddrinfo(name,
2363 NULL,
2364 &hints,
2365 &ailist);
2366 if (ret) {
2367 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
2368 name,
2369 gai_strerror(ret) ));
2372 for (res = ailist; res; res = res->ai_next) {
2373 struct sockaddr_storage ss;
2375 if (!res->ai_addr || res->ai_addrlen == 0) {
2376 continue;
2379 ZERO_STRUCT(ss);
2380 memcpy(&ss, res->ai_addr, res->ai_addrlen);
2382 if (is_zero_addr(&ss)) {
2383 continue;
2386 *return_count += 1;
2388 *return_iplist = talloc_realloc(
2389 mem_ctx, *return_iplist, struct sockaddr_storage,
2390 *return_count);
2391 if (!*return_iplist) {
2392 DEBUG(3,("resolve_hosts: malloc fail !\n"));
2393 freeaddrinfo(ailist);
2394 return NT_STATUS_NO_MEMORY;
2396 (*return_iplist)[i] = ss;
2397 i++;
2399 if (ailist) {
2400 freeaddrinfo(ailist);
2402 if (*return_count) {
2403 return NT_STATUS_OK;
2405 return NT_STATUS_UNSUCCESSFUL;
2408 /********************************************************
2409 Resolve via "ADS" method.
2410 *********************************************************/
2412 /* Special name type used to cause a _kerberos DNS lookup. */
2413 #define KDC_NAME_TYPE 0xDCDC
2415 static NTSTATUS resolve_ads(const char *name,
2416 int name_type,
2417 const char *sitename,
2418 struct ip_service **return_iplist,
2419 int *return_count)
2421 int i;
2422 NTSTATUS status;
2423 TALLOC_CTX *ctx;
2424 struct dns_rr_srv *dcs = NULL;
2425 int numdcs = 0;
2426 int numaddrs = 0;
2428 if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
2429 (name_type != 0x1b)) {
2430 return NT_STATUS_INVALID_PARAMETER;
2433 if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
2434 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
2435 return NT_STATUS_NO_MEMORY;
2438 /* The DNS code needs fixing to find IPv6 addresses... JRA. */
2439 switch (name_type) {
2440 case 0x1b:
2441 DEBUG(5,("resolve_ads: Attempting to resolve "
2442 "PDC for %s using DNS\n", name));
2443 status = ads_dns_query_pdc(ctx,
2444 name,
2445 &dcs,
2446 &numdcs);
2447 break;
2449 case 0x1c:
2450 DEBUG(5,("resolve_ads: Attempting to resolve "
2451 "DCs for %s using DNS\n", name));
2452 status = ads_dns_query_dcs(ctx,
2453 name,
2454 sitename,
2455 &dcs,
2456 &numdcs);
2457 break;
2458 case KDC_NAME_TYPE:
2459 DEBUG(5,("resolve_ads: Attempting to resolve "
2460 "KDCs for %s using DNS\n", name));
2461 status = ads_dns_query_kdcs(ctx,
2462 name,
2463 sitename,
2464 &dcs,
2465 &numdcs);
2466 break;
2467 default:
2468 status = NT_STATUS_INVALID_PARAMETER;
2469 break;
2472 if ( !NT_STATUS_IS_OK( status ) ) {
2473 talloc_destroy(ctx);
2474 return status;
2477 if (numdcs == 0) {
2478 *return_iplist = NULL;
2479 *return_count = 0;
2480 talloc_destroy(ctx);
2481 return NT_STATUS_OK;
2484 for (i=0;i<numdcs;i++) {
2485 if (!dcs[i].ss_s) {
2486 numaddrs += 1;
2487 } else {
2488 numaddrs += dcs[i].num_ips;
2492 if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
2493 NULL ) {
2494 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
2495 numaddrs ));
2496 talloc_destroy(ctx);
2497 return NT_STATUS_NO_MEMORY;
2500 /* now unroll the list of IP addresses */
2502 *return_count = 0;
2504 for (i = 0; i < numdcs && (*return_count<numaddrs); i++ ) {
2505 /* If we don't have an IP list for a name, lookup it up */
2506 if (!dcs[i].ss_s) {
2507 /* We need to get all IP addresses here. */
2508 struct addrinfo *res = NULL;
2509 struct addrinfo *p;
2510 int extra_addrs = 0;
2512 if (!interpret_string_addr_internal(&res,
2513 dcs[i].hostname,
2514 0)) {
2515 continue;
2517 /* Add in every IP from the lookup. How
2518 many is that ? */
2519 for (p = res; p; p = p->ai_next) {
2520 struct sockaddr_storage ss;
2521 memcpy(&ss, p->ai_addr, p->ai_addrlen);
2522 if (is_zero_addr(&ss)) {
2523 continue;
2525 extra_addrs++;
2527 if (extra_addrs > 1) {
2528 /* We need to expand the return_iplist array
2529 as we only budgeted for one address. */
2530 numaddrs += (extra_addrs-1);
2531 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
2532 struct ip_service,
2533 numaddrs);
2534 if (*return_iplist == NULL) {
2535 if (res) {
2536 freeaddrinfo(res);
2538 talloc_destroy(ctx);
2539 return NT_STATUS_NO_MEMORY;
2542 for (p = res; p; p = p->ai_next) {
2543 (*return_iplist)[*return_count].port = dcs[i].port;
2544 memcpy(&(*return_iplist)[*return_count].ss,
2545 p->ai_addr,
2546 p->ai_addrlen);
2547 if (is_zero_addr(&(*return_iplist)[*return_count].ss)) {
2548 continue;
2550 (*return_count)++;
2551 /* Should never happen, but still... */
2552 if (*return_count>=numaddrs) {
2553 break;
2556 if (res) {
2557 freeaddrinfo(res);
2559 } else {
2560 /* use all the IP addresses from the SRV response */
2561 int j;
2562 for (j = 0; j < dcs[i].num_ips; j++) {
2563 (*return_iplist)[*return_count].port = dcs[i].port;
2564 (*return_iplist)[*return_count].ss = dcs[i].ss_s[j];
2565 if (is_zero_addr(&(*return_iplist)[*return_count].ss)) {
2566 continue;
2568 (*return_count)++;
2569 /* Should never happen, but still... */
2570 if (*return_count>=numaddrs) {
2571 break;
2577 talloc_destroy(ctx);
2578 return NT_STATUS_OK;
2581 static const char **filter_out_nbt_lookup(TALLOC_CTX *mem_ctx,
2582 const char **resolve_order)
2584 size_t i, len, result_idx;
2585 const char **result;
2587 len = 0;
2588 while (resolve_order[len] != NULL) {
2589 len += 1;
2592 result = talloc_array(mem_ctx, const char *, len+1);
2593 if (result == NULL) {
2594 return NULL;
2597 result_idx = 0;
2599 for (i=0; i<len; i++) {
2600 const char *tok = resolve_order[i];
2602 if (strequal(tok, "lmhosts") || strequal(tok, "wins") ||
2603 strequal(tok, "bcast")) {
2604 continue;
2606 result[result_idx++] = tok;
2608 result[result_idx] = NULL;
2610 return result;
2613 /*******************************************************************
2614 Internal interface to resolve a name into an IP address.
2615 Use this function if the string is either an IP address, DNS
2616 or host name or NetBIOS name. This uses the name switch in the
2617 smb.conf to determine the order of name resolution.
2619 Added support for ip addr/port to support ADS ldap servers.
2620 the only place we currently care about the port is in the
2621 resolve_hosts() when looking up DC's via SRV RR entries in DNS
2622 **********************************************************************/
2624 NTSTATUS internal_resolve_name(const char *name,
2625 int name_type,
2626 const char *sitename,
2627 struct ip_service **return_iplist,
2628 int *return_count,
2629 const char **resolve_order)
2631 const char *tok;
2632 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2633 int i;
2634 TALLOC_CTX *frame = NULL;
2636 *return_iplist = NULL;
2637 *return_count = 0;
2639 DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
2640 name, name_type, sitename ? sitename : "(null)"));
2642 if (is_ipaddress(name)) {
2643 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
2644 NULL) {
2645 DEBUG(0,("internal_resolve_name: malloc fail !\n"));
2646 return NT_STATUS_NO_MEMORY;
2649 /* ignore the port here */
2650 (*return_iplist)->port = PORT_NONE;
2652 /* if it's in the form of an IP address then get the lib to interpret it */
2653 if (!interpret_string_addr(&(*return_iplist)->ss,
2654 name, AI_NUMERICHOST)) {
2655 DEBUG(1,("internal_resolve_name: interpret_string_addr "
2656 "failed on %s\n",
2657 name));
2658 SAFE_FREE(*return_iplist);
2659 return NT_STATUS_INVALID_PARAMETER;
2661 if (is_zero_addr(&(*return_iplist)->ss)) {
2662 SAFE_FREE(*return_iplist);
2663 return NT_STATUS_UNSUCCESSFUL;
2665 *return_count = 1;
2666 return NT_STATUS_OK;
2669 /* Check name cache */
2671 if (namecache_fetch(name, name_type, return_iplist, return_count)) {
2672 *return_count = remove_duplicate_addrs2(*return_iplist,
2673 *return_count );
2674 /* This could be a negative response */
2675 if (*return_count > 0) {
2676 return NT_STATUS_OK;
2677 } else {
2678 return NT_STATUS_UNSUCCESSFUL;
2682 /* set the name resolution order */
2684 if (resolve_order && strcmp(resolve_order[0], "NULL") == 0) {
2685 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
2686 return NT_STATUS_INVALID_PARAMETER;
2689 if (!resolve_order || !resolve_order[0]) {
2690 static const char *host_order[] = { "host", NULL };
2691 resolve_order = host_order;
2694 frame = talloc_stackframe();
2696 if ((strlen(name) > MAX_NETBIOSNAME_LEN - 1) ||
2697 (strchr(name, '.') != NULL)) {
2699 * Don't do NBT lookup, the name would not fit anyway
2701 resolve_order = filter_out_nbt_lookup(frame, resolve_order);
2702 if (resolve_order == NULL) {
2703 TALLOC_FREE(frame);
2704 return NT_STATUS_NO_MEMORY;
2708 /* iterate through the name resolution backends */
2710 for (i=0; resolve_order[i]; i++) {
2711 tok = resolve_order[i];
2713 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
2714 struct sockaddr_storage *ss_list;
2715 status = resolve_hosts(name, name_type,
2716 talloc_tos(), &ss_list,
2717 return_count);
2718 if (NT_STATUS_IS_OK(status)) {
2719 if (!convert_ss2service(return_iplist,
2720 ss_list,
2721 return_count)) {
2722 status = NT_STATUS_NO_MEMORY;
2724 goto done;
2726 } else if(strequal( tok, "kdc")) {
2727 /* deal with KDC_NAME_TYPE names here.
2728 * This will result in a SRV record lookup */
2729 status = resolve_ads(name, KDC_NAME_TYPE, sitename,
2730 return_iplist, return_count);
2731 if (NT_STATUS_IS_OK(status)) {
2732 /* Ensure we don't namecache
2733 * this with the KDC port. */
2734 name_type = KDC_NAME_TYPE;
2735 goto done;
2737 } else if(strequal( tok, "ads")) {
2738 /* deal with 0x1c and 0x1b names here.
2739 * This will result in a SRV record lookup */
2740 status = resolve_ads(name, name_type, sitename,
2741 return_iplist, return_count);
2742 if (NT_STATUS_IS_OK(status)) {
2743 goto done;
2745 } else if (strequal(tok, "lmhosts")) {
2746 struct sockaddr_storage *ss_list;
2747 status = resolve_lmhosts_file_as_sockaddr(
2748 get_dyn_LMHOSTSFILE(), name, name_type,
2749 talloc_tos(), &ss_list, return_count);
2750 if (NT_STATUS_IS_OK(status)) {
2751 if (!convert_ss2service(return_iplist,
2752 ss_list,
2753 return_count)) {
2754 status = NT_STATUS_NO_MEMORY;
2756 goto done;
2758 } else if (strequal(tok, "wins")) {
2759 /* don't resolve 1D via WINS */
2760 struct sockaddr_storage *ss_list;
2761 if (name_type != 0x1D) {
2762 status = resolve_wins(name, name_type,
2763 talloc_tos(),
2764 &ss_list,
2765 return_count);
2766 if (NT_STATUS_IS_OK(status)) {
2767 if (!convert_ss2service(return_iplist,
2768 ss_list,
2769 return_count)) {
2770 status = NT_STATUS_NO_MEMORY;
2772 goto done;
2775 } else if (strequal(tok, "bcast")) {
2776 struct sockaddr_storage *ss_list;
2777 status = name_resolve_bcast(
2778 name, name_type, talloc_tos(),
2779 &ss_list, return_count);
2780 if (NT_STATUS_IS_OK(status)) {
2781 if (!convert_ss2service(return_iplist,
2782 ss_list,
2783 return_count)) {
2784 status = NT_STATUS_NO_MEMORY;
2786 goto done;
2788 } else {
2789 DEBUG(0,("resolve_name: unknown name switch type %s\n",
2790 tok));
2794 /* All of the resolve_* functions above have returned false. */
2796 TALLOC_FREE(frame);
2797 SAFE_FREE(*return_iplist);
2798 *return_count = 0;
2800 return NT_STATUS_UNSUCCESSFUL;
2802 done:
2804 /* Remove duplicate entries. Some queries, notably #1c (domain
2805 controllers) return the PDC in iplist[0] and then all domain
2806 controllers including the PDC in iplist[1..n]. Iterating over
2807 the iplist when the PDC is down will cause two sets of timeouts. */
2809 *return_count = remove_duplicate_addrs2(*return_iplist, *return_count );
2811 /* Save in name cache */
2812 if ( DEBUGLEVEL >= 100 ) {
2813 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
2814 char addr[INET6_ADDRSTRLEN];
2815 print_sockaddr(addr, sizeof(addr),
2816 &(*return_iplist)[i].ss);
2817 DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
2818 name,
2819 name_type,
2820 addr,
2821 (*return_iplist)[i].port));
2825 if (*return_count) {
2826 namecache_store(name, name_type, *return_count, *return_iplist);
2829 /* Display some debugging info */
2831 if ( DEBUGLEVEL >= 10 ) {
2832 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
2833 *return_count));
2835 for (i = 0; i < *return_count; i++) {
2836 char addr[INET6_ADDRSTRLEN];
2837 print_sockaddr(addr, sizeof(addr),
2838 &(*return_iplist)[i].ss);
2839 DEBUGADD(10, ("%s:%d ",
2840 addr,
2841 (*return_iplist)[i].port));
2843 DEBUG(10, ("\n"));
2846 TALLOC_FREE(frame);
2847 return status;
2850 /********************************************************
2851 Internal interface to resolve a name into one IP address.
2852 Use this function if the string is either an IP address, DNS
2853 or host name or NetBIOS name. This uses the name switch in the
2854 smb.conf to determine the order of name resolution.
2855 *********************************************************/
2857 bool resolve_name(const char *name,
2858 struct sockaddr_storage *return_ss,
2859 int name_type,
2860 bool prefer_ipv4)
2862 struct ip_service *ss_list = NULL;
2863 char *sitename = NULL;
2864 int count = 0;
2865 NTSTATUS status;
2866 TALLOC_CTX *frame = NULL;
2868 if (is_ipaddress(name)) {
2869 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
2872 frame = talloc_stackframe();
2874 sitename = sitename_fetch(frame, lp_realm()); /* wild guess */
2876 status = internal_resolve_name(name, name_type, sitename,
2877 &ss_list, &count,
2878 lp_name_resolve_order());
2879 if (NT_STATUS_IS_OK(status)) {
2880 int i;
2882 if (prefer_ipv4) {
2883 for (i=0; i<count; i++) {
2884 if (!is_zero_addr(&ss_list[i].ss) &&
2885 !is_broadcast_addr((struct sockaddr *)(void *)&ss_list[i].ss) &&
2886 (ss_list[i].ss.ss_family == AF_INET)) {
2887 *return_ss = ss_list[i].ss;
2888 SAFE_FREE(ss_list);
2889 TALLOC_FREE(frame);
2890 return True;
2895 /* only return valid addresses for TCP connections */
2896 for (i=0; i<count; i++) {
2897 if (!is_zero_addr(&ss_list[i].ss) &&
2898 !is_broadcast_addr((struct sockaddr *)(void *)&ss_list[i].ss)) {
2899 *return_ss = ss_list[i].ss;
2900 SAFE_FREE(ss_list);
2901 TALLOC_FREE(frame);
2902 return True;
2907 SAFE_FREE(ss_list);
2908 TALLOC_FREE(frame);
2909 return False;
2912 /********************************************************
2913 Internal interface to resolve a name into a list of IP addresses.
2914 Use this function if the string is either an IP address, DNS
2915 or host name or NetBIOS name. This uses the name switch in the
2916 smb.conf to determine the order of name resolution.
2917 *********************************************************/
2919 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
2920 const char *name,
2921 int name_type,
2922 struct sockaddr_storage **return_ss_arr,
2923 unsigned int *p_num_entries)
2925 struct ip_service *ss_list = NULL;
2926 char *sitename = NULL;
2927 int count = 0;
2928 int i;
2929 unsigned int num_entries;
2930 NTSTATUS status;
2932 *p_num_entries = 0;
2933 *return_ss_arr = NULL;
2935 if (is_ipaddress(name)) {
2936 *return_ss_arr = talloc(ctx, struct sockaddr_storage);
2937 if (!*return_ss_arr) {
2938 return NT_STATUS_NO_MEMORY;
2940 if (!interpret_string_addr(*return_ss_arr, name, AI_NUMERICHOST)) {
2941 TALLOC_FREE(*return_ss_arr);
2942 return NT_STATUS_BAD_NETWORK_NAME;
2944 *p_num_entries = 1;
2945 return NT_STATUS_OK;
2948 sitename = sitename_fetch(ctx, lp_realm()); /* wild guess */
2950 status = internal_resolve_name(name, name_type, sitename,
2951 &ss_list, &count,
2952 lp_name_resolve_order());
2953 TALLOC_FREE(sitename);
2955 if (!NT_STATUS_IS_OK(status)) {
2956 return status;
2959 /* only return valid addresses for TCP connections */
2960 for (i=0, num_entries = 0; i<count; i++) {
2961 if (!is_zero_addr(&ss_list[i].ss) &&
2962 !is_broadcast_addr((struct sockaddr *)(void *)&ss_list[i].ss)) {
2963 num_entries++;
2966 if (num_entries == 0) {
2967 SAFE_FREE(ss_list);
2968 return NT_STATUS_BAD_NETWORK_NAME;
2971 *return_ss_arr = talloc_array(ctx,
2972 struct sockaddr_storage,
2973 num_entries);
2974 if (!(*return_ss_arr)) {
2975 SAFE_FREE(ss_list);
2976 return NT_STATUS_NO_MEMORY;
2979 for (i=0, num_entries = 0; i<count; i++) {
2980 if (!is_zero_addr(&ss_list[i].ss) &&
2981 !is_broadcast_addr((struct sockaddr *)(void *)&ss_list[i].ss)) {
2982 (*return_ss_arr)[num_entries++] = ss_list[i].ss;
2986 status = NT_STATUS_OK;
2987 *p_num_entries = num_entries;
2989 SAFE_FREE(ss_list);
2990 return NT_STATUS_OK;
2993 /********************************************************
2994 Find the IP address of the master browser or DMB for a workgroup.
2995 *********************************************************/
2997 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
2999 struct ip_service *ip_list = NULL;
3000 int count = 0;
3001 NTSTATUS status;
3003 if (lp_disable_netbios()) {
3004 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
3005 return false;
3008 status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
3009 lp_name_resolve_order());
3010 if (NT_STATUS_IS_OK(status)) {
3011 *master_ss = ip_list[0].ss;
3012 SAFE_FREE(ip_list);
3013 return true;
3016 status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
3017 lp_name_resolve_order());
3018 if (NT_STATUS_IS_OK(status)) {
3019 *master_ss = ip_list[0].ss;
3020 SAFE_FREE(ip_list);
3021 return true;
3024 SAFE_FREE(ip_list);
3025 return false;
3028 /********************************************************
3029 Get the IP address list of the primary domain controller
3030 for a domain.
3031 *********************************************************/
3033 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
3035 struct ip_service *ip_list = NULL;
3036 int count = 0;
3037 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
3038 static const char *ads_order[] = { "ads", NULL };
3039 /* Look up #1B name */
3041 if (lp_security() == SEC_ADS) {
3042 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
3043 &count, ads_order);
3046 if (!NT_STATUS_IS_OK(status) || count == 0) {
3047 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
3048 &count,
3049 lp_name_resolve_order());
3050 if (!NT_STATUS_IS_OK(status)) {
3051 SAFE_FREE(ip_list);
3052 return false;
3056 /* if we get more than 1 IP back we have to assume it is a
3057 multi-homed PDC and not a mess up */
3059 if ( count > 1 ) {
3060 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
3061 sort_service_list(ip_list, count);
3064 *pss = ip_list[0].ss;
3065 SAFE_FREE(ip_list);
3066 return true;
3069 /* Private enum type for lookups. */
3071 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
3073 /********************************************************
3074 Get the IP address list of the domain controllers for
3075 a domain.
3076 *********************************************************/
3078 static NTSTATUS get_dc_list(const char *domain,
3079 const char *sitename,
3080 struct ip_service **ip_list,
3081 int *count,
3082 enum dc_lookup_type lookup_type,
3083 bool *ordered)
3085 const char **resolve_order = NULL;
3086 char *saf_servername = NULL;
3087 char *pserver = NULL;
3088 const char *p;
3089 char *port_str = NULL;
3090 int port;
3091 char *name;
3092 int num_addresses = 0;
3093 int local_count, i, j;
3094 struct ip_service *return_iplist = NULL;
3095 struct ip_service *auto_ip_list = NULL;
3096 bool done_auto_lookup = false;
3097 int auto_count = 0;
3098 NTSTATUS status;
3099 TALLOC_CTX *ctx = talloc_stackframe();
3100 int auto_name_type = 0x1C;
3102 *ip_list = NULL;
3103 *count = 0;
3105 *ordered = False;
3107 /* if we are restricted to solely using DNS for looking
3108 up a domain controller, make sure that host lookups
3109 are enabled for the 'name resolve order'. If host lookups
3110 are disabled and ads_only is True, then set the string to
3111 NULL. */
3113 resolve_order = lp_name_resolve_order();
3114 if (!resolve_order) {
3115 status = NT_STATUS_NO_MEMORY;
3116 goto out;
3118 if (lookup_type == DC_ADS_ONLY) {
3119 if (str_list_check_ci(resolve_order, "host")) {
3120 static const char *ads_order[] = { "ads", NULL };
3121 resolve_order = ads_order;
3123 /* DNS SRV lookups used by the ads resolver
3124 are already sorted by priority and weight */
3125 *ordered = true;
3126 } else {
3127 /* this is quite bizarre! */
3128 static const char *null_order[] = { "NULL", NULL };
3129 resolve_order = null_order;
3131 } else if (lookup_type == DC_KDC_ONLY) {
3132 static const char *kdc_order[] = { "kdc", NULL };
3133 /* DNS SRV lookups used by the ads/kdc resolver
3134 are already sorted by priority and weight */
3135 *ordered = true;
3136 resolve_order = kdc_order;
3137 auto_name_type = KDC_NAME_TYPE;
3140 /* fetch the server we have affinity for. Add the
3141 'password server' list to a search for our domain controllers */
3143 saf_servername = saf_fetch(ctx, domain);
3145 if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
3146 pserver = talloc_asprintf(ctx, "%s, %s",
3147 saf_servername ? saf_servername : "",
3148 lp_password_server());
3149 } else {
3150 pserver = talloc_asprintf(ctx, "%s, *",
3151 saf_servername ? saf_servername : "");
3154 TALLOC_FREE(saf_servername);
3155 if (!pserver) {
3156 status = NT_STATUS_NO_MEMORY;
3157 goto out;
3160 DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
3163 * if '*' appears in the "password server" list then add
3164 * an auto lookup to the list of manually configured
3165 * DC's. If any DC is listed by name, then the list should be
3166 * considered to be ordered
3169 p = pserver;
3170 while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
3171 if (!done_auto_lookup && strequal(name, "*")) {
3172 status = internal_resolve_name(domain, auto_name_type,
3173 sitename,
3174 &auto_ip_list,
3175 &auto_count,
3176 resolve_order);
3177 if (NT_STATUS_IS_OK(status)) {
3178 num_addresses += auto_count;
3180 done_auto_lookup = true;
3181 DEBUG(8,("Adding %d DC's from auto lookup\n",
3182 auto_count));
3183 } else {
3184 num_addresses++;
3188 /* if we have no addresses and haven't done the auto lookup, then
3189 just return the list of DC's. Or maybe we just failed. */
3191 if (num_addresses == 0) {
3192 if (done_auto_lookup) {
3193 DEBUG(4,("get_dc_list: no servers found\n"));
3194 status = NT_STATUS_NO_LOGON_SERVERS;
3195 goto out;
3197 status = internal_resolve_name(domain, auto_name_type,
3198 sitename, ip_list,
3199 count, resolve_order);
3200 goto out;
3203 if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
3204 num_addresses)) == NULL) {
3205 DEBUG(3,("get_dc_list: malloc fail !\n"));
3206 status = NT_STATUS_NO_MEMORY;
3207 goto out;
3210 p = pserver;
3211 local_count = 0;
3213 /* fill in the return list now with real IP's */
3215 while ((local_count<num_addresses) &&
3216 next_token_talloc(ctx, &p, &name, LIST_SEP)) {
3217 struct sockaddr_storage name_ss;
3219 /* copy any addresses from the auto lookup */
3221 if (strequal(name, "*")) {
3222 for (j=0; j<auto_count; j++) {
3223 char addr[INET6_ADDRSTRLEN];
3224 print_sockaddr(addr,
3225 sizeof(addr),
3226 &auto_ip_list[j].ss);
3227 /* Check for and don't copy any
3228 * known bad DC IP's. */
3229 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
3230 domain,
3231 addr))) {
3232 DEBUG(5,("get_dc_list: "
3233 "negative entry %s removed "
3234 "from DC list\n",
3235 addr));
3236 continue;
3238 return_iplist[local_count].ss =
3239 auto_ip_list[j].ss;
3240 return_iplist[local_count].port =
3241 auto_ip_list[j].port;
3242 local_count++;
3244 continue;
3247 /* added support for address:port syntax for ads
3248 * (not that I think anyone will ever run the LDAP
3249 * server in an AD domain on something other than
3250 * port 389
3251 * However, the port should not be used for kerberos
3254 port = (lookup_type == DC_ADS_ONLY) ? LDAP_PORT :
3255 ((lookup_type == DC_KDC_ONLY) ? DEFAULT_KRB5_PORT :
3256 PORT_NONE);
3257 if ((port_str=strchr(name, ':')) != NULL) {
3258 *port_str = '\0';
3259 if (lookup_type != DC_KDC_ONLY) {
3260 port_str++;
3261 port = atoi(port_str);
3265 /* explicit lookup; resolve_name() will
3266 * handle names & IP addresses */
3267 if (resolve_name( name, &name_ss, 0x20, true )) {
3268 char addr[INET6_ADDRSTRLEN];
3269 print_sockaddr(addr,
3270 sizeof(addr),
3271 &name_ss);
3273 /* Check for and don't copy any known bad DC IP's. */
3274 if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
3275 addr)) ) {
3276 DEBUG(5,("get_dc_list: negative entry %s "
3277 "removed from DC list\n",
3278 name ));
3279 continue;
3282 return_iplist[local_count].ss = name_ss;
3283 return_iplist[local_count].port = port;
3284 local_count++;
3285 *ordered = true;
3289 /* need to remove duplicates in the list if we have any
3290 explicit password servers */
3292 local_count = remove_duplicate_addrs2(return_iplist, local_count );
3294 /* For DC's we always prioritize IPv4 due to W2K3 not
3295 * supporting LDAP, KRB5 or CLDAP over IPv6. */
3297 if (local_count && return_iplist) {
3298 prioritize_ipv4_list(return_iplist, local_count);
3301 if ( DEBUGLEVEL >= 4 ) {
3302 DEBUG(4,("get_dc_list: returning %d ip addresses "
3303 "in an %sordered list\n",
3304 local_count,
3305 *ordered ? "":"un"));
3306 DEBUG(4,("get_dc_list: "));
3307 for ( i=0; i<local_count; i++ ) {
3308 char addr[INET6_ADDRSTRLEN];
3309 print_sockaddr(addr,
3310 sizeof(addr),
3311 &return_iplist[i].ss);
3312 DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
3314 DEBUGADD(4,("\n"));
3317 *ip_list = return_iplist;
3318 *count = local_count;
3320 status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
3322 out:
3324 if (!NT_STATUS_IS_OK(status)) {
3325 SAFE_FREE(return_iplist);
3326 *ip_list = NULL;
3327 *count = 0;
3330 SAFE_FREE(auto_ip_list);
3331 TALLOC_FREE(ctx);
3332 return status;
3335 /*********************************************************************
3336 Small wrapper function to get the DC list and sort it if neccessary.
3337 *********************************************************************/
3339 NTSTATUS get_sorted_dc_list( const char *domain,
3340 const char *sitename,
3341 struct ip_service **ip_list,
3342 int *count,
3343 bool ads_only )
3345 bool ordered = false;
3346 NTSTATUS status;
3347 enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
3349 *ip_list = NULL;
3350 *count = 0;
3352 DEBUG(8,("get_sorted_dc_list: attempting lookup "
3353 "for name %s (sitename %s)\n",
3354 domain,
3355 sitename ? sitename : "NULL"));
3357 if (ads_only) {
3358 lookup_type = DC_ADS_ONLY;
3361 status = get_dc_list(domain, sitename, ip_list,
3362 count, lookup_type, &ordered);
3363 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS)
3364 && sitename) {
3365 DEBUG(3,("get_sorted_dc_list: no server for name %s available"
3366 " in site %s, fallback to all servers\n",
3367 domain, sitename));
3368 status = get_dc_list(domain, NULL, ip_list,
3369 count, lookup_type, &ordered);
3372 if (!NT_STATUS_IS_OK(status)) {
3373 SAFE_FREE(*ip_list);
3374 *count = 0;
3375 return status;
3378 /* only sort if we don't already have an ordered list */
3379 if (!ordered) {
3380 sort_service_list(*ip_list, *count);
3383 return NT_STATUS_OK;
3386 /*********************************************************************
3387 Get the KDC list - re-use all the logic in get_dc_list.
3388 *********************************************************************/
3390 NTSTATUS get_kdc_list( const char *realm,
3391 const char *sitename,
3392 struct ip_service **ip_list,
3393 int *count)
3395 bool ordered;
3396 NTSTATUS status;
3398 *count = 0;
3399 *ip_list = NULL;
3401 status = get_dc_list(realm, sitename, ip_list,
3402 count, DC_KDC_ONLY, &ordered);
3404 if (!NT_STATUS_IS_OK(status)) {
3405 SAFE_FREE(*ip_list);
3406 *count = 0;
3407 return status;
3410 /* only sort if we don't already have an ordered list */
3411 if ( !ordered ) {
3412 sort_service_list(*ip_list, *count);
3415 return NT_STATUS_OK;