vfs_ceph_new: Remove unused symbol for ceph_readdir
[Samba.git] / source3 / libsmb / namequery.c
blobc855e43284e5b58ab5ac8dfbd967e981af7faa78
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 "libsmb/namequery.h"
23 #include "../lib/util/tevent_ntstatus.h"
24 #include "libads/sitename_cache.h"
25 #include "../lib/addns/dnsquery.h"
26 #include "../lib/addns/dnsquery_srv.h"
27 #include "../libcli/netlogon/netlogon.h"
28 #include "lib/async_req/async_sock.h"
29 #include "lib/tsocket/tsocket.h"
30 #include "libsmb/nmblib.h"
31 #include "libsmb/unexpected.h"
32 #include "../libcli/nbt/libnbt.h"
33 #include "lib/gencache.h"
34 #include "librpc/gen_ndr/dns.h"
35 #include "lib/util/util_net.h"
36 #include "lib/util/tsort.h"
37 #include "lib/util/string_wrappers.h"
39 /* nmbd.c sets this to True. */
40 bool global_in_nmbd = False;
43 * Utility function to convert from a sockaddr_storage
44 * array to a struct samba_sockaddr array.
47 static NTSTATUS sockaddr_array_to_samba_sockaddr_array(
48 TALLOC_CTX *ctx,
49 struct samba_sockaddr **sa_out,
50 size_t *count_out,
51 const struct sockaddr_storage *ss_in,
52 size_t count_in)
54 struct samba_sockaddr *sa = NULL;
55 size_t i;
56 size_t count = 0;
58 if (count_in == 0) {
60 * Zero length arrays are returned as NULL.
61 * in the name resolution code.
63 *count_out = 0;
64 *sa_out = NULL;
65 return NT_STATUS_OK;
67 sa = talloc_zero_array(ctx,
68 struct samba_sockaddr,
69 count_in);
70 if (sa == NULL) {
71 return NT_STATUS_NO_MEMORY;
73 count = 0;
74 for (i = 0; i < count_in; i++) {
75 bool ok;
77 /* Filter out zero addresses. */
78 if (is_zero_addr(&ss_in[i])) {
79 continue;
81 ok = sockaddr_storage_to_samba_sockaddr(&sa[count],
82 &ss_in[i]);
83 if (!ok) {
84 continue;
86 count++;
88 if (count == 0) {
90 * Zero length arrays are returned as NULL.
91 * in the name resolution code.
93 TALLOC_FREE(sa);
95 *count_out = count;
96 *sa_out = sa;
97 return NT_STATUS_OK;
100 /****************************
101 * SERVER AFFINITY ROUTINES *
102 ****************************/
104 /* Server affinity is the concept of preferring the last domain
105 controller with whom you had a successful conversation */
107 /****************************************************************************
108 ****************************************************************************/
109 #define SAFKEY_FMT "SAF/DOMAIN/%s"
110 #define SAF_TTL 900
111 #define SAFJOINKEY_FMT "SAFJOIN/DOMAIN/%s"
112 #define SAFJOIN_TTL 3600
114 static char *saf_key(TALLOC_CTX *mem_ctx, const char *domain)
116 return talloc_asprintf_strupper_m(mem_ctx, SAFKEY_FMT, domain);
119 static char *saf_join_key(TALLOC_CTX *mem_ctx, const char *domain)
121 return talloc_asprintf_strupper_m(mem_ctx, SAFJOINKEY_FMT, domain);
124 /****************************************************************************
125 ****************************************************************************/
127 bool saf_store( const char *domain, const char *servername )
129 char *key;
130 time_t expire;
131 bool ret = False;
133 if ( !domain || !servername ) {
134 DEBUG(2,("saf_store: "
135 "Refusing to store empty domain or servername!\n"));
136 return False;
139 if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
140 DEBUG(0,("saf_store: "
141 "refusing to store 0 length domain or servername!\n"));
142 return False;
145 key = saf_key(talloc_tos(), domain);
146 if (key == NULL) {
147 DEBUG(1, ("saf_key() failed\n"));
148 return false;
150 expire = time( NULL ) + lp_parm_int(-1, "saf","ttl", SAF_TTL);
152 DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
153 domain, servername, (unsigned int)expire ));
155 ret = gencache_set( key, servername, expire );
157 TALLOC_FREE( key );
159 return ret;
162 bool saf_join_store( const char *domain, const char *servername )
164 char *key;
165 time_t expire;
166 bool ret = False;
168 if ( !domain || !servername ) {
169 DEBUG(2,("saf_join_store: Refusing to store empty domain or servername!\n"));
170 return False;
173 if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
174 DEBUG(0,("saf_join_store: refusing to store 0 length domain or servername!\n"));
175 return False;
178 key = saf_join_key(talloc_tos(), domain);
179 if (key == NULL) {
180 DEBUG(1, ("saf_join_key() failed\n"));
181 return false;
183 expire = time( NULL ) + lp_parm_int(-1, "saf","join ttl", SAFJOIN_TTL);
185 DEBUG(10,("saf_join_store: domain = [%s], server = [%s], expire = [%u]\n",
186 domain, servername, (unsigned int)expire ));
188 ret = gencache_set( key, servername, expire );
190 TALLOC_FREE( key );
192 return ret;
195 bool saf_delete( const char *domain )
197 char *key;
198 bool ret = False;
200 if ( !domain ) {
201 DEBUG(2,("saf_delete: Refusing to delete empty domain\n"));
202 return False;
205 key = saf_join_key(talloc_tos(), domain);
206 if (key == NULL) {
207 DEBUG(1, ("saf_join_key() failed\n"));
208 return false;
210 ret = gencache_del(key);
211 TALLOC_FREE(key);
213 if (ret) {
214 DEBUG(10,("saf_delete[join]: domain = [%s]\n", domain ));
217 key = saf_key(talloc_tos(), domain);
218 if (key == NULL) {
219 DEBUG(1, ("saf_key() failed\n"));
220 return false;
222 ret = gencache_del(key);
223 TALLOC_FREE(key);
225 if (ret) {
226 DEBUG(10,("saf_delete: domain = [%s]\n", domain ));
229 return ret;
232 /****************************************************************************
233 ****************************************************************************/
235 char *saf_fetch(TALLOC_CTX *mem_ctx, const char *domain )
237 char *server = NULL;
238 time_t timeout;
239 bool ret = False;
240 char *key = NULL;
242 if ( !domain || strlen(domain) == 0) {
243 DEBUG(2,("saf_fetch: Empty domain name!\n"));
244 return NULL;
247 key = saf_join_key(talloc_tos(), domain);
248 if (key == NULL) {
249 DEBUG(1, ("saf_join_key() failed\n"));
250 return NULL;
253 ret = gencache_get( key, mem_ctx, &server, &timeout );
255 TALLOC_FREE( key );
257 if ( ret ) {
258 DEBUG(5,("saf_fetch[join]: Returning \"%s\" for \"%s\" domain\n",
259 server, domain ));
260 return server;
263 key = saf_key(talloc_tos(), domain);
264 if (key == NULL) {
265 DEBUG(1, ("saf_key() failed\n"));
266 return NULL;
269 ret = gencache_get( key, mem_ctx, &server, &timeout );
271 TALLOC_FREE( key );
273 if ( !ret ) {
274 DEBUG(5,("saf_fetch: failed to find server for \"%s\" domain\n",
275 domain ));
276 } else {
277 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
278 server, domain ));
281 return server;
284 static void set_socket_addr_v4(struct samba_sockaddr *addr)
286 if (!interpret_string_addr(&addr->u.ss, lp_nbt_client_socket_address(),
287 AI_NUMERICHOST|AI_PASSIVE)) {
288 zero_sockaddr(&addr->u.ss);
289 /* zero_sockaddr sets family to AF_INET. */
290 addr->sa_socklen = sizeof(struct sockaddr_in);
292 if (addr->u.ss.ss_family != AF_INET) {
293 zero_sockaddr(&addr->u.ss);
294 /* zero_sockaddr sets family to AF_INET. */
295 addr->sa_socklen = sizeof(struct sockaddr_in);
299 static struct in_addr my_socket_addr_v4(void)
301 struct samba_sockaddr my_addr = {0};
303 set_socket_addr_v4(&my_addr);
304 return my_addr.u.in.sin_addr;
307 /****************************************************************************
308 Generate a random trn_id.
309 ****************************************************************************/
311 static int generate_trn_id(void)
313 uint16_t id;
315 generate_random_buffer((uint8_t *)&id, sizeof(id));
317 return id % (unsigned)0x7FFF;
320 /****************************************************************************
321 Parse a node status response into an array of structures.
322 ****************************************************************************/
324 static struct node_status *parse_node_status(TALLOC_CTX *mem_ctx,
325 const char *rdata,
326 size_t rdlen,
327 size_t *num_names,
328 struct node_status_extra *extra)
330 struct node_status *ret;
331 size_t i;
332 size_t len = 0;
333 size_t result_count = 0;
334 const size_t result_len = MAX_NETBIOSNAME_LEN + sizeof(uint8_t) +
335 sizeof(char);
336 const char *r = NULL;
338 *num_names = 0;
339 if (rdlen == 0) {
340 return NULL;
343 result_count = PULL_LE_U8(rdata, 0);
344 if (result_count == 0) {
345 return NULL;
347 r = rdata + 1;
349 len = result_len * result_count + sizeof(uint8_t);
350 if (len > rdlen) {
351 return NULL;
354 ret = talloc_zero_array(mem_ctx, struct node_status, result_count);
355 if (!ret)
356 return NULL;
358 for (i = 0; i < result_count; i++) {
359 strlcpy(ret[i].name, r, MAX_NETBIOSNAME_LEN);
360 trim_char(ret[i].name,'\0',' ');
361 ret[i].type = PULL_LE_U8(r, 15);
362 ret[i].flags = r[16];
364 r += result_len;
366 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
367 ret[i].type, ret[i].flags));
371 * Also, pick up the MAC address ...
373 if (extra) {
374 if (len + 6 > rdlen) {
375 TALLOC_FREE(ret);
376 return NULL;
378 memcpy(&extra->mac_addr, r, 6); /* Fill in the mac addr */
381 *num_names = result_count;
382 return ret;
385 struct sock_packet_read_state {
386 struct tevent_context *ev;
387 enum packet_type type;
388 int trn_id;
390 struct nb_packet_reader *reader;
391 struct tevent_req *reader_req;
393 struct tdgram_context *sock;
394 struct tevent_req *socket_req;
395 uint8_t *buf;
396 struct tsocket_address *addr;
398 bool (*validator)(struct packet_struct *p,
399 void *private_data);
400 void *private_data;
402 struct packet_struct *packet;
405 static void sock_packet_read_got_packet(struct tevent_req *subreq);
406 static void sock_packet_read_got_socket(struct tevent_req *subreq);
408 static struct tevent_req *sock_packet_read_send(
409 TALLOC_CTX *mem_ctx,
410 struct tevent_context *ev,
411 struct tdgram_context *sock,
412 struct nb_packet_reader *reader,
413 enum packet_type type,
414 int trn_id,
415 bool (*validator)(struct packet_struct *p, void *private_data),
416 void *private_data)
418 struct tevent_req *req;
419 struct sock_packet_read_state *state;
421 req = tevent_req_create(mem_ctx, &state,
422 struct sock_packet_read_state);
423 if (req == NULL) {
424 return NULL;
426 state->ev = ev;
427 state->reader = reader;
428 state->sock = sock;
429 state->type = type;
430 state->trn_id = trn_id;
431 state->validator = validator;
432 state->private_data = private_data;
434 if (reader != NULL) {
435 state->reader_req = nb_packet_read_send(state, ev, reader);
436 if (tevent_req_nomem(state->reader_req, req)) {
437 return tevent_req_post(req, ev);
439 tevent_req_set_callback(
440 state->reader_req, sock_packet_read_got_packet, req);
443 state->socket_req = tdgram_recvfrom_send(state, ev, state->sock);
444 if (tevent_req_nomem(state->socket_req, req)) {
445 return tevent_req_post(req, ev);
447 tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
448 req);
450 return req;
453 static void sock_packet_read_got_packet(struct tevent_req *subreq)
455 struct tevent_req *req = tevent_req_callback_data(
456 subreq, struct tevent_req);
457 struct sock_packet_read_state *state = tevent_req_data(
458 req, struct sock_packet_read_state);
459 NTSTATUS status;
461 status = nb_packet_read_recv(subreq, state, &state->packet);
463 TALLOC_FREE(state->reader_req);
465 if (!NT_STATUS_IS_OK(status)) {
466 if (state->socket_req != NULL) {
468 * Still waiting for socket
470 return;
473 * Both socket and packet reader failed
475 tevent_req_nterror(req, status);
476 return;
479 if ((state->validator != NULL) &&
480 !state->validator(state->packet, state->private_data)) {
481 DEBUG(10, ("validator failed\n"));
483 TALLOC_FREE(state->packet);
485 state->reader_req = nb_packet_read_send(state, state->ev,
486 state->reader);
487 if (tevent_req_nomem(state->reader_req, req)) {
488 return;
490 tevent_req_set_callback(
491 state->reader_req, sock_packet_read_got_packet, req);
492 return;
495 TALLOC_FREE(state->socket_req);
496 tevent_req_done(req);
499 static void sock_packet_read_got_socket(struct tevent_req *subreq)
501 struct tevent_req *req = tevent_req_callback_data(
502 subreq, struct tevent_req);
503 struct sock_packet_read_state *state = tevent_req_data(
504 req, struct sock_packet_read_state);
505 struct samba_sockaddr addr = {0};
506 ssize_t ret;
507 ssize_t received;
508 int err;
509 bool ok;
511 received = tdgram_recvfrom_recv(subreq, &err, state,
512 &state->buf, &state->addr);
514 TALLOC_FREE(state->socket_req);
516 if (received == -1) {
517 if (state->reader_req != NULL) {
519 * Still waiting for reader
521 return;
524 * Both socket and reader failed
526 tevent_req_nterror(req, map_nt_error_from_unix(err));
527 return;
529 ok = tsocket_address_is_inet(state->addr, "ipv4");
530 if (!ok) {
531 goto retry;
533 ret = tsocket_address_bsd_sockaddr(state->addr,
534 &addr.u.sa,
535 sizeof(addr.u.in));
536 if (ret == -1) {
537 tevent_req_nterror(req, map_nt_error_from_unix(errno));
538 return;
541 state->packet = parse_packet_talloc(
542 state, (char *)state->buf, received, state->type,
543 addr.u.in.sin_addr, addr.u.in.sin_port);
544 if (state->packet == NULL) {
545 DEBUG(10, ("parse_packet failed\n"));
546 goto retry;
548 if ((state->trn_id != -1) &&
549 (state->trn_id != packet_trn_id(state->packet))) {
550 DEBUG(10, ("Expected transaction id %d, got %d\n",
551 state->trn_id, packet_trn_id(state->packet)));
552 goto retry;
555 if ((state->validator != NULL) &&
556 !state->validator(state->packet, state->private_data)) {
557 DEBUG(10, ("validator failed\n"));
558 goto retry;
561 tevent_req_done(req);
562 return;
564 retry:
565 TALLOC_FREE(state->packet);
566 TALLOC_FREE(state->buf);
567 TALLOC_FREE(state->addr);
569 state->socket_req = tdgram_recvfrom_send(state, state->ev, state->sock);
570 if (tevent_req_nomem(state->socket_req, req)) {
571 return;
573 tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
574 req);
577 static NTSTATUS sock_packet_read_recv(struct tevent_req *req,
578 TALLOC_CTX *mem_ctx,
579 struct packet_struct **ppacket)
581 struct sock_packet_read_state *state = tevent_req_data(
582 req, struct sock_packet_read_state);
583 NTSTATUS status;
585 if (tevent_req_is_nterror(req, &status)) {
586 return status;
588 *ppacket = talloc_move(mem_ctx, &state->packet);
589 return NT_STATUS_OK;
592 struct nb_trans_state {
593 struct tevent_context *ev;
594 struct tdgram_context *sock;
595 struct nb_packet_reader *reader;
597 struct tsocket_address *src_addr;
598 struct tsocket_address *dst_addr;
599 uint8_t *buf;
600 size_t buflen;
601 enum packet_type type;
602 int trn_id;
604 bool (*validator)(struct packet_struct *p,
605 void *private_data);
606 void *private_data;
608 struct packet_struct *packet;
611 static void nb_trans_got_reader(struct tevent_req *subreq);
612 static void nb_trans_done(struct tevent_req *subreq);
613 static void nb_trans_sent(struct tevent_req *subreq);
614 static void nb_trans_send_next(struct tevent_req *subreq);
616 static struct tevent_req *nb_trans_send(
617 TALLOC_CTX *mem_ctx,
618 struct tevent_context *ev,
619 const struct samba_sockaddr *_my_addr,
620 const struct samba_sockaddr *_dst_addr,
621 bool bcast,
622 uint8_t *buf, size_t buflen,
623 enum packet_type type, int trn_id,
624 bool (*validator)(struct packet_struct *p,
625 void *private_data),
626 void *private_data)
628 const struct sockaddr *my_addr = &_my_addr->u.sa;
629 size_t my_addr_len = sizeof(_my_addr->u.in); /*We know it's AF_INET.*/
630 const struct sockaddr *dst_addr = &_dst_addr->u.sa;
631 size_t dst_addr_len = sizeof(_dst_addr->u.in); /*We know it's AF_INET.*/
632 struct tevent_req *req, *subreq;
633 struct nb_trans_state *state;
634 int ret;
636 req = tevent_req_create(mem_ctx, &state, struct nb_trans_state);
637 if (req == NULL) {
638 return NULL;
640 state->ev = ev;
641 state->buf = buf;
642 state->buflen = buflen;
643 state->type = type;
644 state->trn_id = trn_id;
645 state->validator = validator;
646 state->private_data = private_data;
648 ret = tsocket_address_bsd_from_sockaddr(state,
649 my_addr, my_addr_len,
650 &state->src_addr);
651 if (ret == -1) {
652 tevent_req_nterror(req, map_nt_error_from_unix(errno));
653 return tevent_req_post(req, ev);
656 ret = tsocket_address_bsd_from_sockaddr(state,
657 dst_addr, dst_addr_len,
658 &state->dst_addr);
659 if (ret == -1) {
660 tevent_req_nterror(req, map_nt_error_from_unix(errno));
661 return tevent_req_post(req, ev);
664 ret = tdgram_inet_udp_broadcast_socket(state->src_addr, state,
665 &state->sock);
666 if (ret == -1) {
667 tevent_req_nterror(req, map_nt_error_from_unix(errno));
668 return tevent_req_post(req, ev);
671 subreq = nb_packet_reader_send(state,
673 global_nmbd_socket_dir(),
674 type,
675 state->trn_id,
676 NULL);
677 if (tevent_req_nomem(subreq, req)) {
678 return tevent_req_post(req, ev);
680 tevent_req_set_callback(subreq, nb_trans_got_reader, req);
681 return req;
684 static void nb_trans_got_reader(struct tevent_req *subreq)
686 struct tevent_req *req = tevent_req_callback_data(
687 subreq, struct tevent_req);
688 struct nb_trans_state *state = tevent_req_data(
689 req, struct nb_trans_state);
690 NTSTATUS status;
692 status = nb_packet_reader_recv(subreq, state, &state->reader);
693 TALLOC_FREE(subreq);
695 if (!NT_STATUS_IS_OK(status)) {
696 DEBUG(10, ("nmbd not around\n"));
697 state->reader = NULL;
700 subreq = sock_packet_read_send(
701 state, state->ev, state->sock,
702 state->reader, state->type, state->trn_id,
703 state->validator, state->private_data);
704 if (tevent_req_nomem(subreq, req)) {
705 return;
707 tevent_req_set_callback(subreq, nb_trans_done, req);
709 subreq = tdgram_sendto_send(state, state->ev,
710 state->sock,
711 state->buf, state->buflen,
712 state->dst_addr);
713 if (tevent_req_nomem(subreq, req)) {
714 return;
716 tevent_req_set_callback(subreq, nb_trans_sent, req);
719 static void nb_trans_sent(struct tevent_req *subreq)
721 struct tevent_req *req = tevent_req_callback_data(
722 subreq, struct tevent_req);
723 struct nb_trans_state *state = tevent_req_data(
724 req, struct nb_trans_state);
725 ssize_t sent;
726 int err;
728 sent = tdgram_sendto_recv(subreq, &err);
729 TALLOC_FREE(subreq);
730 if (sent == -1) {
731 DEBUG(10, ("sendto failed: %s\n", strerror(err)));
732 tevent_req_nterror(req, map_nt_error_from_unix(err));
733 return;
735 subreq = tevent_wakeup_send(state, state->ev,
736 timeval_current_ofs(1, 0));
737 if (tevent_req_nomem(subreq, req)) {
738 return;
740 tevent_req_set_callback(subreq, nb_trans_send_next, req);
743 static void nb_trans_send_next(struct tevent_req *subreq)
745 struct tevent_req *req = tevent_req_callback_data(
746 subreq, struct tevent_req);
747 struct nb_trans_state *state = tevent_req_data(
748 req, struct nb_trans_state);
749 bool ret;
751 ret = tevent_wakeup_recv(subreq);
752 TALLOC_FREE(subreq);
753 if (!ret) {
754 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
755 return;
757 subreq = tdgram_sendto_send(state, state->ev,
758 state->sock,
759 state->buf, state->buflen,
760 state->dst_addr);
761 if (tevent_req_nomem(subreq, req)) {
762 return;
764 tevent_req_set_callback(subreq, nb_trans_sent, req);
767 static void nb_trans_done(struct tevent_req *subreq)
769 struct tevent_req *req = tevent_req_callback_data(
770 subreq, struct tevent_req);
771 struct nb_trans_state *state = tevent_req_data(
772 req, struct nb_trans_state);
773 NTSTATUS status;
775 status = sock_packet_read_recv(subreq, state, &state->packet);
776 TALLOC_FREE(subreq);
777 if (tevent_req_nterror(req, status)) {
778 return;
780 tevent_req_done(req);
783 static NTSTATUS nb_trans_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
784 struct packet_struct **ppacket)
786 struct nb_trans_state *state = tevent_req_data(
787 req, struct nb_trans_state);
788 NTSTATUS status;
790 if (tevent_req_is_nterror(req, &status)) {
791 return status;
793 *ppacket = talloc_move(mem_ctx, &state->packet);
794 return NT_STATUS_OK;
797 /****************************************************************************
798 Do a NBT node status query on an open socket and return an array of
799 structures holding the returned names or NULL if the query failed.
800 **************************************************************************/
802 struct node_status_query_state {
803 struct samba_sockaddr my_addr;
804 struct samba_sockaddr addr;
805 uint8_t buf[1024];
806 ssize_t buflen;
807 struct packet_struct *packet;
810 static bool node_status_query_validator(struct packet_struct *p,
811 void *private_data);
812 static void node_status_query_done(struct tevent_req *subreq);
814 struct tevent_req *node_status_query_send(TALLOC_CTX *mem_ctx,
815 struct tevent_context *ev,
816 struct nmb_name *name,
817 const struct sockaddr_storage *addr)
819 struct tevent_req *req, *subreq;
820 struct node_status_query_state *state;
821 struct packet_struct p;
822 struct nmb_packet *nmb = &p.packet.nmb;
823 bool ok;
825 req = tevent_req_create(mem_ctx, &state,
826 struct node_status_query_state);
827 if (req == NULL) {
828 return NULL;
831 if (addr->ss_family != AF_INET) {
832 /* Can't do node status to IPv6 */
833 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
834 return tevent_req_post(req, ev);
837 ok = sockaddr_storage_to_samba_sockaddr(&state->addr, addr);
838 if (!ok) {
839 /* node status must be IPv4 */
840 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
841 return tevent_req_post(req, ev);
843 state->addr.u.in.sin_port = htons(NMB_PORT);
845 set_socket_addr_v4(&state->my_addr);
847 ZERO_STRUCT(p);
848 nmb->header.name_trn_id = generate_trn_id();
849 nmb->header.opcode = 0;
850 nmb->header.response = false;
851 nmb->header.nm_flags.bcast = false;
852 nmb->header.nm_flags.recursion_available = false;
853 nmb->header.nm_flags.recursion_desired = false;
854 nmb->header.nm_flags.trunc = false;
855 nmb->header.nm_flags.authoritative = false;
856 nmb->header.rcode = 0;
857 nmb->header.qdcount = 1;
858 nmb->header.ancount = 0;
859 nmb->header.nscount = 0;
860 nmb->header.arcount = 0;
861 nmb->question.question_name = *name;
862 nmb->question.question_type = 0x21;
863 nmb->question.question_class = 0x1;
865 state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
866 &p);
867 if (state->buflen == 0) {
868 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
869 DEBUG(10, ("build_packet failed\n"));
870 return tevent_req_post(req, ev);
873 subreq = nb_trans_send(state,
875 &state->my_addr,
876 &state->addr,
877 false,
878 state->buf,
879 state->buflen,
880 NMB_PACKET,
881 nmb->header.name_trn_id,
882 node_status_query_validator,
883 NULL);
884 if (tevent_req_nomem(subreq, req)) {
885 DEBUG(10, ("nb_trans_send failed\n"));
886 return tevent_req_post(req, ev);
888 if (!tevent_req_set_endtime(req, ev, timeval_current_ofs(10, 0))) {
889 return tevent_req_post(req, ev);
891 tevent_req_set_callback(subreq, node_status_query_done, req);
892 return req;
895 static bool node_status_query_validator(struct packet_struct *p,
896 void *private_data)
898 struct nmb_packet *nmb = &p->packet.nmb;
899 debug_nmb_packet(p);
901 if (nmb->header.opcode != 0 ||
902 nmb->header.nm_flags.bcast ||
903 nmb->header.rcode ||
904 !nmb->header.ancount ||
905 nmb->answers->rr_type != 0x21) {
907 * XXXX what do we do with this? could be a redirect,
908 * but we'll discard it for the moment
910 return false;
912 return true;
915 static void node_status_query_done(struct tevent_req *subreq)
917 struct tevent_req *req = tevent_req_callback_data(
918 subreq, struct tevent_req);
919 struct node_status_query_state *state = tevent_req_data(
920 req, struct node_status_query_state);
921 NTSTATUS status;
923 status = nb_trans_recv(subreq, state, &state->packet);
924 TALLOC_FREE(subreq);
925 if (tevent_req_nterror(req, status)) {
926 return;
928 tevent_req_done(req);
931 NTSTATUS node_status_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
932 struct node_status **pnode_status,
933 size_t *pnum_names,
934 struct node_status_extra *extra)
936 struct node_status_query_state *state = tevent_req_data(
937 req, struct node_status_query_state);
938 struct node_status *node_status;
939 size_t num_names = 0;
940 NTSTATUS status;
942 if (tevent_req_is_nterror(req, &status)) {
943 return status;
945 node_status = parse_node_status(
946 mem_ctx,
947 state->packet->packet.nmb.answers->rdata,
948 state->packet->packet.nmb.answers->rdlength,
949 &num_names,
950 extra);
951 if (node_status == NULL) {
952 return NT_STATUS_NO_MEMORY;
954 *pnode_status = node_status;
955 *pnum_names = num_names;
956 return NT_STATUS_OK;
959 NTSTATUS node_status_query(TALLOC_CTX *mem_ctx, struct nmb_name *name,
960 const struct sockaddr_storage *addr,
961 struct node_status **pnode_status,
962 size_t *pnum_names,
963 struct node_status_extra *extra)
965 TALLOC_CTX *frame = talloc_stackframe();
966 struct tevent_context *ev;
967 struct tevent_req *req;
968 NTSTATUS status = NT_STATUS_NO_MEMORY;
970 ev = samba_tevent_context_init(frame);
971 if (ev == NULL) {
972 goto fail;
974 req = node_status_query_send(ev, ev, name, addr);
975 if (req == NULL) {
976 goto fail;
978 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
979 goto fail;
981 status = node_status_query_recv(req, mem_ctx, pnode_status,
982 pnum_names, extra);
983 fail:
984 TALLOC_FREE(frame);
985 return status;
988 static bool name_status_lmhosts(const struct sockaddr_storage *paddr,
989 int qname_type, fstring pname)
991 FILE *f;
992 char *name;
993 int name_type;
994 struct samba_sockaddr addr_in = {0};
995 struct samba_sockaddr addr = {0};
996 bool ok;
998 ok = sockaddr_storage_to_samba_sockaddr(&addr_in, paddr);
999 if (!ok) {
1000 return false;
1002 if (addr_in.u.ss.ss_family != AF_INET) {
1003 return false;
1006 f = startlmhosts(get_dyn_LMHOSTSFILE());
1007 if (f == NULL) {
1008 return false;
1011 while (getlmhostsent(talloc_tos(), f, &name, &name_type, &addr.u.ss)) {
1012 if (addr.u.ss.ss_family != AF_INET) {
1013 continue;
1015 if (name_type != qname_type) {
1016 continue;
1018 if (sockaddr_equal(&addr_in.u.sa, &addr.u.sa)) {
1019 fstrcpy(pname, name);
1020 endlmhosts(f);
1021 return true;
1024 endlmhosts(f);
1025 return false;
1028 /****************************************************************************
1029 Find the first type XX name in a node status reply - used for finding
1030 a servers name given its IP. Return the matched name in *name.
1031 **************************************************************************/
1033 bool name_status_find(const char *q_name,
1034 int q_type,
1035 int type,
1036 const struct sockaddr_storage *to_ss,
1037 fstring name)
1039 char addr[INET6_ADDRSTRLEN];
1040 struct node_status *addrs = NULL;
1041 struct nmb_name nname;
1042 size_t count = 0, i;
1043 bool result = false;
1044 NTSTATUS status;
1046 if (lp_disable_netbios()) {
1047 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n",
1048 q_name, q_type));
1049 return False;
1052 print_sockaddr(addr, sizeof(addr), to_ss);
1054 DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
1055 q_type, addr));
1057 /* Check the cache first. */
1059 if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
1060 return True;
1063 if (to_ss->ss_family != AF_INET) {
1064 /* Can't do node status to IPv6 */
1065 return false;
1068 result = name_status_lmhosts(to_ss, type, name);
1069 if (result) {
1070 DBG_DEBUG("Found name %s in lmhosts\n", name);
1071 namecache_status_store(q_name, q_type, type, to_ss, name);
1072 return true;
1075 /* W2K PDC's seem not to respond to '*'#0. JRA */
1076 make_nmb_name(&nname, q_name, q_type);
1077 status = node_status_query(talloc_tos(), &nname, to_ss,
1078 &addrs, &count, NULL);
1079 if (!NT_STATUS_IS_OK(status)) {
1080 goto done;
1083 for (i=0;i<count;i++) {
1084 /* Find first one of the requested type that's not a GROUP. */
1085 if (addrs[i].type == type && ! (addrs[i].flags & 0x80))
1086 break;
1088 if (i == count)
1089 goto done;
1091 pull_ascii_nstring(name, sizeof(fstring), addrs[i].name);
1093 /* Store the result in the cache. */
1094 /* but don't store an entry for 0x1c names here. Here we have
1095 a single host and DOMAIN<0x1c> names should be a list of hosts */
1097 if ( q_type != 0x1c ) {
1098 namecache_status_store(q_name, q_type, type, to_ss, name);
1101 result = true;
1103 done:
1104 TALLOC_FREE(addrs);
1106 DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
1108 if (result)
1109 DEBUGADD(10, (", name %s ip address is %s", name, addr));
1111 DEBUG(10, ("\n"));
1113 return result;
1117 * comparison function used by sort_addr_list
1119 * This comparison is intransitive in sort if a socket has an invalid
1120 * family (i.e., not IPv4 or IPv6), or an interface doesn't support
1121 * the family. Say we have sockaddrs with IP versions {4,5,6}, of
1122 * which 5 is invalid. By this function, 4 == 5 and 6 == 5, but 4 !=
1123 * 6. This is of course a consequence of cmp() being unable to
1124 * communicate error.
1127 static int addr_compare(const struct sockaddr_storage *ss1,
1128 const struct sockaddr_storage *ss2)
1130 int max_bits1=0, max_bits2=0;
1131 int num_interfaces = iface_count();
1132 int i;
1133 struct samba_sockaddr sa1;
1134 struct samba_sockaddr sa2;
1135 bool ok;
1137 ok = sockaddr_storage_to_samba_sockaddr(&sa1, ss1);
1138 if (!ok) {
1139 return 0; /* No change. */
1142 ok = sockaddr_storage_to_samba_sockaddr(&sa2, ss2);
1143 if (!ok) {
1144 return 0; /* No change. */
1147 /* Sort IPv4 addresses first. */
1148 if (sa1.u.ss.ss_family != sa2.u.ss.ss_family) {
1149 if (sa2.u.ss.ss_family == AF_INET) {
1150 return 1;
1151 } else {
1152 return -1;
1156 /* Here we know both addresses are of the same
1157 * family. */
1159 for (i=0;i<num_interfaces;i++) {
1160 struct samba_sockaddr sif = {0};
1161 const unsigned char *p_ss1 = NULL;
1162 const unsigned char *p_ss2 = NULL;
1163 const unsigned char *p_if = NULL;
1164 size_t len = 0;
1165 int bits1, bits2;
1167 ok = sockaddr_storage_to_samba_sockaddr(&sif, iface_n_bcast(i));
1168 if (!ok) {
1169 return 0; /* No change. */
1171 if (sif.u.ss.ss_family != sa1.u.ss.ss_family) {
1172 /* Ignore interfaces of the wrong type. */
1173 continue;
1175 if (sif.u.ss.ss_family == AF_INET) {
1176 p_if = (const unsigned char *)&sif.u.in.sin_addr;
1177 p_ss1 = (const unsigned char *)&sa1.u.in.sin_addr;
1178 p_ss2 = (const unsigned char *)&sa2.u.in.sin_addr;
1179 len = 4;
1181 #if defined(HAVE_IPV6)
1182 if (sif.u.ss.ss_family == AF_INET6) {
1183 p_if = (const unsigned char *)&sif.u.in6.sin6_addr;
1184 p_ss1 = (const unsigned char *)&sa1.u.in6.sin6_addr;
1185 p_ss2 = (const unsigned char *)&sa2.u.in6.sin6_addr;
1186 len = 16;
1188 #endif
1189 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
1190 continue;
1192 bits1 = matching_len_bits(p_ss1, p_if, len);
1193 bits2 = matching_len_bits(p_ss2, p_if, len);
1194 max_bits1 = MAX(bits1, max_bits1);
1195 max_bits2 = MAX(bits2, max_bits2);
1198 /* Bias towards directly reachable IPs */
1199 if (iface_local(&sa1.u.sa)) {
1200 if (sa1.u.ss.ss_family == AF_INET) {
1201 max_bits1 += 32;
1202 } else {
1203 max_bits1 += 128;
1206 if (iface_local(&sa2.u.sa)) {
1207 if (sa2.u.ss.ss_family == AF_INET) {
1208 max_bits2 += 32;
1209 } else {
1210 max_bits2 += 128;
1213 return NUMERIC_CMP(max_bits2, max_bits1);
1217 sort an IP list so that names that are close to one of our interfaces
1218 are at the top. This prevents the problem where a WINS server returns an IP
1219 that is not reachable from our subnet as the first match
1222 static void sort_addr_list(struct sockaddr_storage *sslist, size_t count)
1224 if (count <= 1) {
1225 return;
1228 TYPESAFE_QSORT(sslist, count, addr_compare);
1231 static int samba_sockaddr_compare(struct samba_sockaddr *sa1,
1232 struct samba_sockaddr *sa2)
1234 return addr_compare(&sa1->u.ss, &sa2->u.ss);
1237 static void sort_sa_list(struct samba_sockaddr *salist, size_t count)
1239 if (count <= 1) {
1240 return;
1243 TYPESAFE_QSORT(salist, count, samba_sockaddr_compare);
1246 /**********************************************************************
1247 Remove any duplicate address/port pairs in the samba_sockaddr array.
1248 *********************************************************************/
1250 size_t remove_duplicate_addrs2(struct samba_sockaddr *salist, size_t count )
1252 size_t i, j;
1254 DBG_DEBUG("looking for duplicate address/port pairs\n");
1256 /* One loop to set duplicates to a zero addr. */
1257 for (i=0; i < count; i++) {
1258 if (is_zero_addr(&salist[i].u.ss)) {
1259 continue;
1262 for (j=i+1; j<count; j++) {
1263 if (sockaddr_equal(&salist[i].u.sa, &salist[j].u.sa)) {
1264 zero_sockaddr(&salist[j].u.ss);
1269 /* Now remove any addresses set to zero above. */
1270 for (i = 0; i < count; i++) {
1271 while (i < count &&
1272 is_zero_addr(&salist[i].u.ss)) {
1273 ARRAY_DEL_ELEMENT(salist, i, count);
1274 count--;
1278 return count;
1281 static bool prioritize_ipv4_list(struct samba_sockaddr *salist, size_t count)
1283 TALLOC_CTX *frame = talloc_stackframe();
1284 struct samba_sockaddr *salist_new = talloc_array(frame,
1285 struct samba_sockaddr,
1286 count);
1287 size_t i, j;
1289 if (salist_new == NULL) {
1290 TALLOC_FREE(frame);
1291 return false;
1294 j = 0;
1296 /* Copy IPv4 first. */
1297 for (i = 0; i < count; i++) {
1298 if (salist[i].u.ss.ss_family == AF_INET) {
1299 salist_new[j++] = salist[i];
1303 /* Copy IPv6. */
1304 for (i = 0; i < count; i++) {
1305 if (salist[i].u.ss.ss_family != AF_INET) {
1306 salist_new[j++] = salist[i];
1310 memcpy(salist, salist_new, sizeof(struct samba_sockaddr)*count);
1311 TALLOC_FREE(frame);
1312 return true;
1315 /****************************************************************************
1316 Do a netbios name query to find someones IP.
1317 Returns an array of IP addresses or NULL if none.
1318 *count will be set to the number of addresses returned.
1319 *timed_out is set if we failed by timing out
1320 ****************************************************************************/
1322 struct name_query_state {
1323 struct samba_sockaddr my_addr;
1324 struct samba_sockaddr addr;
1325 bool bcast;
1326 bool bcast_star_query;
1329 uint8_t buf[1024];
1330 ssize_t buflen;
1332 NTSTATUS validate_error;
1333 uint8_t flags;
1335 struct sockaddr_storage *addrs;
1336 size_t num_addrs;
1339 static bool name_query_validator(struct packet_struct *p, void *private_data);
1340 static void name_query_done(struct tevent_req *subreq);
1342 struct tevent_req *name_query_send(TALLOC_CTX *mem_ctx,
1343 struct tevent_context *ev,
1344 const char *name, int name_type,
1345 bool bcast, bool recurse,
1346 const struct sockaddr_storage *addr)
1348 struct tevent_req *req, *subreq;
1349 struct name_query_state *state;
1350 struct packet_struct p;
1351 struct nmb_packet *nmb = &p.packet.nmb;
1352 bool ok;
1354 req = tevent_req_create(mem_ctx, &state, struct name_query_state);
1355 if (req == NULL) {
1356 return NULL;
1358 state->bcast = bcast;
1360 if (addr->ss_family != AF_INET) {
1361 /* Can't do node status to IPv6 */
1362 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
1363 return tevent_req_post(req, ev);
1366 if (lp_disable_netbios()) {
1367 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
1368 name, name_type));
1369 tevent_req_nterror(req, NT_STATUS_NOT_SUPPORTED);
1370 return tevent_req_post(req, ev);
1373 ok = sockaddr_storage_to_samba_sockaddr(&state->addr, addr);
1374 if (!ok) {
1375 /* Node status must be IPv4 */
1376 tevent_req_nterror(req, NT_STATUS_INVALID_ADDRESS);
1377 return tevent_req_post(req, ev);
1379 state->addr.u.in.sin_port = htons(NMB_PORT);
1381 set_socket_addr_v4(&state->my_addr);
1383 ZERO_STRUCT(p);
1384 nmb->header.name_trn_id = generate_trn_id();
1385 nmb->header.opcode = 0;
1386 nmb->header.response = false;
1387 nmb->header.nm_flags.bcast = bcast;
1388 nmb->header.nm_flags.recursion_available = false;
1389 nmb->header.nm_flags.recursion_desired = recurse;
1390 nmb->header.nm_flags.trunc = false;
1391 nmb->header.nm_flags.authoritative = false;
1392 nmb->header.rcode = 0;
1393 nmb->header.qdcount = 1;
1394 nmb->header.ancount = 0;
1395 nmb->header.nscount = 0;
1396 nmb->header.arcount = 0;
1398 if (bcast && (strcmp(name, "*")==0)) {
1400 * We're doing a broadcast query for all
1401 * names in the area. Remember this so
1402 * we will wait for all names within
1403 * the timeout period.
1405 state->bcast_star_query = true;
1408 make_nmb_name(&nmb->question.question_name,name,name_type);
1410 nmb->question.question_type = 0x20;
1411 nmb->question.question_class = 0x1;
1413 state->buflen = build_packet((char *)state->buf, sizeof(state->buf),
1414 &p);
1415 if (state->buflen == 0) {
1416 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1417 DEBUG(10, ("build_packet failed\n"));
1418 return tevent_req_post(req, ev);
1421 subreq = nb_trans_send(state,
1423 &state->my_addr,
1424 &state->addr,
1425 bcast,
1426 state->buf,
1427 state->buflen,
1428 NMB_PACKET,
1429 nmb->header.name_trn_id,
1430 name_query_validator,
1431 state);
1432 if (tevent_req_nomem(subreq, req)) {
1433 DEBUG(10, ("nb_trans_send failed\n"));
1434 return tevent_req_post(req, ev);
1436 tevent_req_set_callback(subreq, name_query_done, req);
1437 return req;
1440 static bool name_query_validator(struct packet_struct *p, void *private_data)
1442 struct name_query_state *state = talloc_get_type_abort(
1443 private_data, struct name_query_state);
1444 struct nmb_packet *nmb = &p->packet.nmb;
1445 struct sockaddr_storage *tmp_addrs;
1446 bool got_unique_netbios_name = false;
1447 int i;
1449 debug_nmb_packet(p);
1452 * If we get a Negative Name Query Response from a WINS
1453 * server, we should report it and give up.
1455 if( 0 == nmb->header.opcode /* A query response */
1456 && !state->bcast /* from a WINS server */
1457 && nmb->header.rcode /* Error returned */
1460 if( DEBUGLVL( 3 ) ) {
1461 /* Only executed if DEBUGLEVEL >= 3 */
1462 dbgtext( "Negative name query "
1463 "response, rcode 0x%02x: ",
1464 nmb->header.rcode );
1465 switch( nmb->header.rcode ) {
1466 case 0x01:
1467 dbgtext("Request was invalidly formatted.\n");
1468 break;
1469 case 0x02:
1470 dbgtext("Problem with NBNS, cannot process "
1471 "name.\n");
1472 break;
1473 case 0x03:
1474 dbgtext("The name requested does not "
1475 "exist.\n");
1476 break;
1477 case 0x04:
1478 dbgtext("Unsupported request error.\n");
1479 break;
1480 case 0x05:
1481 dbgtext("Query refused error.\n");
1482 break;
1483 default:
1484 dbgtext("Unrecognized error code.\n" );
1485 break;
1490 * We accept this packet as valid, but tell the upper
1491 * layers that it's a negative response.
1493 state->validate_error = NT_STATUS_NOT_FOUND;
1494 return true;
1497 if (nmb->header.opcode != 0 ||
1498 nmb->header.nm_flags.bcast ||
1499 nmb->header.rcode ||
1500 !nmb->header.ancount) {
1502 * XXXX what do we do with this? Could be a redirect,
1503 * but we'll discard it for the moment.
1505 return false;
1508 tmp_addrs = talloc_realloc(
1509 state, state->addrs, struct sockaddr_storage,
1510 state->num_addrs + nmb->answers->rdlength/6);
1511 if (tmp_addrs == NULL) {
1512 state->validate_error = NT_STATUS_NO_MEMORY;
1513 return true;
1515 state->addrs = tmp_addrs;
1517 DEBUG(2,("Got a positive name query response "
1518 "from %s ( ", inet_ntoa(p->ip)));
1520 for (i=0; i<nmb->answers->rdlength/6; i++) {
1521 uint16_t flags;
1522 struct in_addr ip;
1523 struct sockaddr_storage addr;
1524 struct samba_sockaddr sa = {0};
1525 bool ok;
1526 size_t j;
1528 flags = RSVAL(&nmb->answers->rdata[i*6], 0);
1529 got_unique_netbios_name |= ((flags & 0x8000) == 0);
1531 putip((char *)&ip,&nmb->answers->rdata[2+i*6]);
1532 in_addr_to_sockaddr_storage(&addr, ip);
1534 ok = sockaddr_storage_to_samba_sockaddr(&sa, &addr);
1535 if (!ok) {
1536 continue;
1539 if (is_zero_addr(&sa.u.ss)) {
1540 continue;
1543 for (j=0; j<state->num_addrs; j++) {
1544 struct samba_sockaddr sa_j = {0};
1546 ok = sockaddr_storage_to_samba_sockaddr(&sa_j,
1547 &state->addrs[j]);
1548 if (!ok) {
1549 continue;
1551 if (sockaddr_equal(&sa.u.sa, &sa_j.u.sa)) {
1552 break;
1555 if (j < state->num_addrs) {
1556 /* Already got it */
1557 continue;
1560 DEBUGADD(2,("%s ",inet_ntoa(ip)));
1562 state->addrs[state->num_addrs] = addr;
1563 /* wrap check. */
1564 if (state->num_addrs + 1 < state->num_addrs) {
1565 return false;
1567 state->num_addrs += 1;
1569 DEBUGADD(2,(")\n"));
1571 /* We add the flags back ... */
1572 if (nmb->header.response)
1573 state->flags |= NM_FLAGS_RS;
1574 if (nmb->header.nm_flags.authoritative)
1575 state->flags |= NM_FLAGS_AA;
1576 if (nmb->header.nm_flags.trunc)
1577 state->flags |= NM_FLAGS_TC;
1578 if (nmb->header.nm_flags.recursion_desired)
1579 state->flags |= NM_FLAGS_RD;
1580 if (nmb->header.nm_flags.recursion_available)
1581 state->flags |= NM_FLAGS_RA;
1582 if (nmb->header.nm_flags.bcast)
1583 state->flags |= NM_FLAGS_B;
1585 if (state->bcast) {
1587 * We have to collect all entries coming in from broadcast
1588 * queries. If we got a unique name and we are not querying
1589 * all names registered within broadcast area (query
1590 * for the name '*', so state->bcast_star_query is set),
1591 * we're done.
1593 return (got_unique_netbios_name && !state->bcast_star_query);
1596 * WINS responses are accepted when they are received
1598 return true;
1601 static void name_query_done(struct tevent_req *subreq)
1603 struct tevent_req *req = tevent_req_callback_data(
1604 subreq, struct tevent_req);
1605 struct name_query_state *state = tevent_req_data(
1606 req, struct name_query_state);
1607 NTSTATUS status;
1608 struct packet_struct *p = NULL;
1610 status = nb_trans_recv(subreq, state, &p);
1611 TALLOC_FREE(subreq);
1612 if (tevent_req_nterror(req, status)) {
1613 return;
1615 if (!NT_STATUS_IS_OK(state->validate_error)) {
1616 tevent_req_nterror(req, state->validate_error);
1617 return;
1619 tevent_req_done(req);
1622 NTSTATUS name_query_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1623 struct sockaddr_storage **addrs, size_t *num_addrs,
1624 uint8_t *flags)
1626 struct name_query_state *state = tevent_req_data(
1627 req, struct name_query_state);
1628 NTSTATUS status;
1630 if (tevent_req_is_nterror(req, &status)) {
1631 if (state->bcast &&
1632 NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
1634 * In the broadcast case we collect replies until the
1635 * timeout.
1637 status = NT_STATUS_OK;
1639 if (!NT_STATUS_IS_OK(status)) {
1640 return status;
1643 if (state->num_addrs == 0) {
1644 return NT_STATUS_NOT_FOUND;
1646 *addrs = talloc_move(mem_ctx, &state->addrs);
1647 sort_addr_list(*addrs, state->num_addrs);
1648 *num_addrs = state->num_addrs;
1649 if (flags != NULL) {
1650 *flags = state->flags;
1652 return NT_STATUS_OK;
1655 NTSTATUS name_query(const char *name, int name_type,
1656 bool bcast, bool recurse,
1657 const struct sockaddr_storage *to_ss,
1658 TALLOC_CTX *mem_ctx,
1659 struct sockaddr_storage **addrs,
1660 size_t *num_addrs, uint8_t *flags)
1662 TALLOC_CTX *frame = talloc_stackframe();
1663 struct tevent_context *ev;
1664 struct tevent_req *req;
1665 struct timeval timeout;
1666 NTSTATUS status = NT_STATUS_NO_MEMORY;
1668 ev = samba_tevent_context_init(frame);
1669 if (ev == NULL) {
1670 goto fail;
1672 req = name_query_send(ev, ev, name, name_type, bcast, recurse, to_ss);
1673 if (req == NULL) {
1674 goto fail;
1676 if (bcast) {
1677 timeout = timeval_current_ofs(0, 250000);
1678 } else {
1679 timeout = timeval_current_ofs(2, 0);
1681 if (!tevent_req_set_endtime(req, ev, timeout)) {
1682 goto fail;
1684 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
1685 goto fail;
1687 status = name_query_recv(req, mem_ctx, addrs, num_addrs, flags);
1688 fail:
1689 TALLOC_FREE(frame);
1690 return status;
1693 struct name_queries_state {
1694 struct tevent_context *ev;
1695 const char *name;
1696 int name_type;
1697 bool bcast;
1698 bool recurse;
1699 const struct sockaddr_storage *addrs;
1700 size_t num_addrs;
1701 int wait_msec;
1702 int timeout_msec;
1704 struct tevent_req **subreqs;
1705 size_t num_received;
1706 size_t num_sent;
1708 size_t received_index;
1709 struct sockaddr_storage *result_addrs;
1710 size_t num_result_addrs;
1711 uint8_t flags;
1714 static void name_queries_done(struct tevent_req *subreq);
1715 static void name_queries_next(struct tevent_req *subreq);
1718 * Send a name query to multiple destinations with a wait time in between
1721 static struct tevent_req *name_queries_send(
1722 TALLOC_CTX *mem_ctx, struct tevent_context *ev,
1723 const char *name, int name_type,
1724 bool bcast, bool recurse,
1725 const struct sockaddr_storage *addrs,
1726 size_t num_addrs, int wait_msec, int timeout_msec)
1728 struct tevent_req *req, *subreq;
1729 struct name_queries_state *state;
1731 if (num_addrs == 0) {
1732 return NULL;
1735 req = tevent_req_create(mem_ctx, &state,
1736 struct name_queries_state);
1737 if (req == NULL) {
1738 return NULL;
1740 state->ev = ev;
1741 state->name = name;
1742 state->name_type = name_type;
1743 state->bcast = bcast;
1744 state->recurse = recurse;
1745 state->addrs = addrs;
1746 state->num_addrs = num_addrs;
1747 state->wait_msec = wait_msec;
1748 state->timeout_msec = timeout_msec;
1750 state->subreqs = talloc_zero_array(
1751 state, struct tevent_req *, num_addrs);
1752 if (tevent_req_nomem(state->subreqs, req)) {
1753 return tevent_req_post(req, ev);
1755 state->num_sent = 0;
1757 subreq = name_query_send(
1758 state->subreqs, state->ev, name, name_type, bcast, recurse,
1759 &state->addrs[state->num_sent]);
1760 if (tevent_req_nomem(subreq, req)) {
1761 return tevent_req_post(req, ev);
1763 if (!tevent_req_set_endtime(
1764 subreq, state->ev,
1765 timeval_current_ofs(0, state->timeout_msec * 1000))) {
1766 return tevent_req_post(req, ev);
1768 tevent_req_set_callback(subreq, name_queries_done, req);
1770 state->subreqs[state->num_sent] = subreq;
1771 state->num_sent += 1;
1773 if (state->num_sent < state->num_addrs) {
1774 subreq = tevent_wakeup_send(
1775 state, state->ev,
1776 timeval_current_ofs(0, state->wait_msec * 1000));
1777 if (tevent_req_nomem(subreq, req)) {
1778 return tevent_req_post(req, ev);
1780 tevent_req_set_callback(subreq, name_queries_next, req);
1782 return req;
1785 static void name_queries_done(struct tevent_req *subreq)
1787 struct tevent_req *req = tevent_req_callback_data(
1788 subreq, struct tevent_req);
1789 struct name_queries_state *state = tevent_req_data(
1790 req, struct name_queries_state);
1791 size_t i;
1792 NTSTATUS status;
1794 status = name_query_recv(subreq, state, &state->result_addrs,
1795 &state->num_result_addrs, &state->flags);
1797 for (i=0; i<state->num_sent; i++) {
1798 if (state->subreqs[i] == subreq) {
1799 break;
1802 if (i == state->num_sent) {
1803 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1804 return;
1806 TALLOC_FREE(state->subreqs[i]);
1808 /* wrap check. */
1809 if (state->num_received + 1 < state->num_received) {
1810 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1811 return;
1813 state->num_received += 1;
1815 if (!NT_STATUS_IS_OK(status)) {
1817 if (state->num_received >= state->num_addrs) {
1818 tevent_req_nterror(req, status);
1819 return;
1822 * Still outstanding requests, just wait
1824 return;
1826 state->received_index = i;
1827 tevent_req_done(req);
1830 static void name_queries_next(struct tevent_req *subreq)
1832 struct tevent_req *req = tevent_req_callback_data(
1833 subreq, struct tevent_req);
1834 struct name_queries_state *state = tevent_req_data(
1835 req, struct name_queries_state);
1837 if (!tevent_wakeup_recv(subreq)) {
1838 tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
1839 return;
1842 subreq = name_query_send(
1843 state->subreqs, state->ev,
1844 state->name, state->name_type, state->bcast, state->recurse,
1845 &state->addrs[state->num_sent]);
1846 if (tevent_req_nomem(subreq, req)) {
1847 return;
1849 tevent_req_set_callback(subreq, name_queries_done, req);
1850 if (!tevent_req_set_endtime(
1851 subreq, state->ev,
1852 timeval_current_ofs(0, state->timeout_msec * 1000))) {
1853 return;
1855 state->subreqs[state->num_sent] = subreq;
1856 state->num_sent += 1;
1858 if (state->num_sent < state->num_addrs) {
1859 subreq = tevent_wakeup_send(
1860 state, state->ev,
1861 timeval_current_ofs(0, state->wait_msec * 1000));
1862 if (tevent_req_nomem(subreq, req)) {
1863 return;
1865 tevent_req_set_callback(subreq, name_queries_next, req);
1869 static NTSTATUS name_queries_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1870 struct sockaddr_storage **result_addrs,
1871 size_t *num_result_addrs, uint8_t *flags,
1872 size_t *received_index)
1874 struct name_queries_state *state = tevent_req_data(
1875 req, struct name_queries_state);
1876 NTSTATUS status;
1878 if (tevent_req_is_nterror(req, &status)) {
1879 return status;
1882 if (result_addrs != NULL) {
1883 *result_addrs = talloc_move(mem_ctx, &state->result_addrs);
1885 if (num_result_addrs != NULL) {
1886 *num_result_addrs = state->num_result_addrs;
1888 if (flags != NULL) {
1889 *flags = state->flags;
1891 if (received_index != NULL) {
1892 *received_index = state->received_index;
1894 return NT_STATUS_OK;
1897 /********************************************************
1898 Resolve via "bcast" method.
1899 *********************************************************/
1901 struct name_resolve_bcast_state {
1902 struct sockaddr_storage *addrs;
1903 size_t num_addrs;
1906 static void name_resolve_bcast_done(struct tevent_req *subreq);
1908 struct tevent_req *name_resolve_bcast_send(TALLOC_CTX *mem_ctx,
1909 struct tevent_context *ev,
1910 const char *name,
1911 int name_type)
1913 struct tevent_req *req, *subreq;
1914 struct name_resolve_bcast_state *state;
1915 struct sockaddr_storage *bcast_addrs;
1916 size_t i, num_addrs, num_bcast_addrs;
1918 req = tevent_req_create(mem_ctx, &state,
1919 struct name_resolve_bcast_state);
1920 if (req == NULL) {
1921 return NULL;
1924 if (lp_disable_netbios()) {
1925 DEBUG(5, ("name_resolve_bcast(%s#%02x): netbios is disabled\n",
1926 name, name_type));
1927 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1928 return tevent_req_post(req, ev);
1932 * "bcast" means do a broadcast lookup on all the local interfaces.
1935 DEBUG(3, ("name_resolve_bcast: Attempting broadcast lookup "
1936 "for name %s<0x%x>\n", name, name_type));
1938 num_addrs = iface_count();
1939 if (num_addrs == 0) {
1940 DBG_INFO("name_resolve_bcast(%s#%02x): no interfaces are available\n",
1941 name,
1942 name_type);
1943 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
1944 return tevent_req_post(req, ev);
1947 bcast_addrs = talloc_array(state, struct sockaddr_storage, num_addrs);
1948 if (tevent_req_nomem(bcast_addrs, req)) {
1949 return tevent_req_post(req, ev);
1953 * Lookup the name on all the interfaces, return on
1954 * the first successful match.
1956 num_bcast_addrs = 0;
1958 for (i=0; i<num_addrs; i++) {
1959 const struct sockaddr_storage *pss = iface_n_bcast(i);
1961 if (pss->ss_family != AF_INET) {
1962 continue;
1964 bcast_addrs[num_bcast_addrs] = *pss;
1965 num_bcast_addrs += 1;
1968 subreq = name_queries_send(state, ev, name, name_type, true, true,
1969 bcast_addrs, num_bcast_addrs, 0, 250);
1970 if (tevent_req_nomem(subreq, req)) {
1971 return tevent_req_post(req, ev);
1973 tevent_req_set_callback(subreq, name_resolve_bcast_done, req);
1974 return req;
1977 static void name_resolve_bcast_done(struct tevent_req *subreq)
1979 struct tevent_req *req = tevent_req_callback_data(
1980 subreq, struct tevent_req);
1981 struct name_resolve_bcast_state *state = tevent_req_data(
1982 req, struct name_resolve_bcast_state);
1983 NTSTATUS status;
1985 status = name_queries_recv(subreq, state,
1986 &state->addrs, &state->num_addrs,
1987 NULL, NULL);
1988 TALLOC_FREE(subreq);
1989 if (tevent_req_nterror(req, status)) {
1990 return;
1992 tevent_req_done(req);
1995 NTSTATUS name_resolve_bcast_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1996 struct sockaddr_storage **addrs,
1997 size_t *num_addrs)
1999 struct name_resolve_bcast_state *state = tevent_req_data(
2000 req, struct name_resolve_bcast_state);
2001 NTSTATUS status;
2003 if (tevent_req_is_nterror(req, &status)) {
2004 return status;
2006 *addrs = talloc_move(mem_ctx, &state->addrs);
2007 *num_addrs = state->num_addrs;
2008 return NT_STATUS_OK;
2011 NTSTATUS name_resolve_bcast(TALLOC_CTX *mem_ctx,
2012 const char *name,
2013 int name_type,
2014 struct sockaddr_storage **return_iplist,
2015 size_t *return_count)
2017 TALLOC_CTX *frame = talloc_stackframe();
2018 struct tevent_context *ev;
2019 struct tevent_req *req;
2020 NTSTATUS status = NT_STATUS_NO_MEMORY;
2022 ev = samba_tevent_context_init(frame);
2023 if (ev == NULL) {
2024 goto fail;
2026 req = name_resolve_bcast_send(frame, ev, name, name_type);
2027 if (req == NULL) {
2028 goto fail;
2030 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
2031 goto fail;
2033 status = name_resolve_bcast_recv(req, mem_ctx, return_iplist,
2034 return_count);
2035 fail:
2036 TALLOC_FREE(frame);
2037 return status;
2040 struct query_wins_list_state {
2041 struct tevent_context *ev;
2042 const char *name;
2043 uint8_t name_type;
2044 struct in_addr *servers;
2045 size_t num_servers;
2046 struct sockaddr_storage server;
2047 size_t num_sent;
2049 struct sockaddr_storage *addrs;
2050 size_t num_addrs;
2051 uint8_t flags;
2054 static void query_wins_list_done(struct tevent_req *subreq);
2057 * Query a list of (replicating) wins servers in sequence, call them
2058 * dead if they don't reply
2061 static struct tevent_req *query_wins_list_send(
2062 TALLOC_CTX *mem_ctx, struct tevent_context *ev,
2063 struct in_addr src_ip, const char *name, uint8_t name_type,
2064 struct in_addr *servers, size_t num_servers)
2066 struct tevent_req *req, *subreq;
2067 struct query_wins_list_state *state;
2069 req = tevent_req_create(mem_ctx, &state,
2070 struct query_wins_list_state);
2071 if (req == NULL) {
2072 return NULL;
2074 state->ev = ev;
2075 state->name = name;
2076 state->name_type = name_type;
2077 state->servers = servers;
2078 state->num_servers = num_servers;
2080 if (state->num_servers == 0) {
2081 tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
2082 return tevent_req_post(req, ev);
2085 in_addr_to_sockaddr_storage(
2086 &state->server, state->servers[state->num_sent]);
2088 subreq = name_query_send(state, state->ev,
2089 state->name, state->name_type,
2090 false, true, &state->server);
2092 if (tevent_req_nomem(subreq, req)) {
2093 return tevent_req_post(req, ev);
2096 /* wrap check */
2097 if (state->num_sent + 1 < state->num_sent) {
2098 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2099 return tevent_req_post(req, ev);
2102 state->num_sent += 1;
2103 if (!tevent_req_set_endtime(subreq, state->ev,
2104 timeval_current_ofs(2, 0))) {
2105 return tevent_req_post(req, ev);
2107 tevent_req_set_callback(subreq, query_wins_list_done, req);
2108 return req;
2111 static void query_wins_list_done(struct tevent_req *subreq)
2113 struct tevent_req *req = tevent_req_callback_data(
2114 subreq, struct tevent_req);
2115 struct query_wins_list_state *state = tevent_req_data(
2116 req, struct query_wins_list_state);
2117 NTSTATUS status;
2119 status = name_query_recv(subreq, state,
2120 &state->addrs, &state->num_addrs,
2121 &state->flags);
2122 TALLOC_FREE(subreq);
2123 if (NT_STATUS_IS_OK(status)) {
2124 tevent_req_done(req);
2125 return;
2127 if (!NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
2128 tevent_req_nterror(req, status);
2129 return;
2131 wins_srv_died(state->servers[state->num_sent-1],
2132 my_socket_addr_v4());
2134 if (state->num_sent == state->num_servers) {
2135 tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
2136 return;
2139 in_addr_to_sockaddr_storage(
2140 &state->server, state->servers[state->num_sent]);
2142 subreq = name_query_send(state, state->ev,
2143 state->name, state->name_type,
2144 false, true, &state->server);
2145 state->num_sent += 1;
2146 if (tevent_req_nomem(subreq, req)) {
2147 return;
2149 if (!tevent_req_set_endtime(subreq, state->ev,
2150 timeval_current_ofs(2, 0))) {
2151 return;
2153 tevent_req_set_callback(subreq, query_wins_list_done, req);
2156 static NTSTATUS query_wins_list_recv(struct tevent_req *req,
2157 TALLOC_CTX *mem_ctx,
2158 struct sockaddr_storage **addrs,
2159 size_t *num_addrs,
2160 uint8_t *flags)
2162 struct query_wins_list_state *state = tevent_req_data(
2163 req, struct query_wins_list_state);
2164 NTSTATUS status;
2166 if (tevent_req_is_nterror(req, &status)) {
2167 return status;
2169 if (addrs != NULL) {
2170 *addrs = talloc_move(mem_ctx, &state->addrs);
2172 if (num_addrs != NULL) {
2173 *num_addrs = state->num_addrs;
2175 if (flags != NULL) {
2176 *flags = state->flags;
2178 return NT_STATUS_OK;
2181 struct resolve_wins_state {
2182 size_t num_sent;
2183 size_t num_received;
2185 struct sockaddr_storage *addrs;
2186 size_t num_addrs;
2187 uint8_t flags;
2190 static void resolve_wins_done(struct tevent_req *subreq);
2192 struct tevent_req *resolve_wins_send(TALLOC_CTX *mem_ctx,
2193 struct tevent_context *ev,
2194 const char *name,
2195 int name_type)
2197 struct tevent_req *req, *subreq;
2198 struct resolve_wins_state *state;
2199 char **wins_tags = NULL;
2200 struct sockaddr_storage src_ss;
2201 struct samba_sockaddr src_sa = {0};
2202 struct in_addr src_ip;
2203 size_t i, num_wins_tags;
2204 bool ok;
2206 req = tevent_req_create(mem_ctx, &state,
2207 struct resolve_wins_state);
2208 if (req == NULL) {
2209 return NULL;
2212 if (wins_srv_count() < 1) {
2213 DEBUG(3,("resolve_wins: WINS server resolution selected "
2214 "and no WINS servers listed.\n"));
2215 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2216 goto fail;
2219 /* the address we will be sending from */
2220 if (!interpret_string_addr(&src_ss, lp_nbt_client_socket_address(),
2221 AI_NUMERICHOST|AI_PASSIVE)) {
2222 zero_sockaddr(&src_ss);
2225 ok = sockaddr_storage_to_samba_sockaddr(&src_sa, &src_ss);
2226 if (!ok) {
2227 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2228 goto fail;
2231 if (src_sa.u.ss.ss_family != AF_INET) {
2232 char addr[INET6_ADDRSTRLEN];
2233 print_sockaddr(addr, sizeof(addr), &src_sa.u.ss);
2234 DEBUG(3,("resolve_wins: cannot receive WINS replies "
2235 "on IPv6 address %s\n",
2236 addr));
2237 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2238 goto fail;
2241 src_ip = src_sa.u.in.sin_addr;
2243 wins_tags = wins_srv_tags();
2244 if (wins_tags == NULL) {
2245 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2246 goto fail;
2249 num_wins_tags = 0;
2250 while (wins_tags[num_wins_tags] != NULL) {
2251 /* wrap check. */
2252 if (num_wins_tags + 1 < num_wins_tags) {
2253 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2254 goto fail;
2256 num_wins_tags += 1;
2259 for (i=0; i<num_wins_tags; i++) {
2260 size_t num_servers, num_alive;
2261 struct in_addr *servers, *alive;
2262 size_t j;
2264 if (!wins_server_tag_ips(wins_tags[i], talloc_tos(),
2265 &servers, &num_servers)) {
2266 DEBUG(10, ("wins_server_tag_ips failed for tag %s\n",
2267 wins_tags[i]));
2268 continue;
2271 alive = talloc_array(state, struct in_addr, num_servers);
2272 if (tevent_req_nomem(alive, req)) {
2273 goto fail;
2276 num_alive = 0;
2277 for (j=0; j<num_servers; j++) {
2278 struct in_addr wins_ip = servers[j];
2280 if (global_in_nmbd && ismyip_v4(wins_ip)) {
2281 /* yikes! we'll loop forever */
2282 continue;
2284 /* skip any that have been unresponsive lately */
2285 if (wins_srv_is_dead(wins_ip, src_ip)) {
2286 continue;
2288 DEBUG(3, ("resolve_wins: using WINS server %s "
2289 "and tag '%s'\n",
2290 inet_ntoa(wins_ip), wins_tags[i]));
2291 alive[num_alive] = wins_ip;
2292 num_alive += 1;
2294 TALLOC_FREE(servers);
2296 if (num_alive == 0) {
2297 continue;
2300 subreq = query_wins_list_send(
2301 state, ev, src_ip, name, name_type,
2302 alive, num_alive);
2303 if (tevent_req_nomem(subreq, req)) {
2304 goto fail;
2306 tevent_req_set_callback(subreq, resolve_wins_done, req);
2307 state->num_sent += 1;
2310 if (state->num_sent == 0) {
2311 tevent_req_nterror(req, NT_STATUS_NOT_FOUND);
2312 goto fail;
2315 wins_srv_tags_free(wins_tags);
2316 return req;
2317 fail:
2318 wins_srv_tags_free(wins_tags);
2319 return tevent_req_post(req, ev);
2322 static void resolve_wins_done(struct tevent_req *subreq)
2324 struct tevent_req *req = tevent_req_callback_data(
2325 subreq, struct tevent_req);
2326 struct resolve_wins_state *state = tevent_req_data(
2327 req, struct resolve_wins_state);
2328 NTSTATUS status;
2330 status = query_wins_list_recv(subreq, state, &state->addrs,
2331 &state->num_addrs, &state->flags);
2332 if (NT_STATUS_IS_OK(status)) {
2333 tevent_req_done(req);
2334 return;
2337 /* wrap check. */
2338 if (state->num_received + 1 < state->num_received) {
2339 tevent_req_nterror(req, NT_STATUS_INVALID_PARAMETER);
2340 return;
2343 state->num_received += 1;
2345 if (state->num_received < state->num_sent) {
2347 * Wait for the others
2349 return;
2351 tevent_req_nterror(req, status);
2354 NTSTATUS resolve_wins_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
2355 struct sockaddr_storage **addrs,
2356 size_t *num_addrs, uint8_t *flags)
2358 struct resolve_wins_state *state = tevent_req_data(
2359 req, struct resolve_wins_state);
2360 NTSTATUS status;
2362 if (tevent_req_is_nterror(req, &status)) {
2363 return status;
2365 if (addrs != NULL) {
2366 *addrs = talloc_move(mem_ctx, &state->addrs);
2368 if (num_addrs != NULL) {
2369 *num_addrs = state->num_addrs;
2371 if (flags != NULL) {
2372 *flags = state->flags;
2374 return NT_STATUS_OK;
2377 /********************************************************
2378 Resolve via "wins" method.
2379 *********************************************************/
2381 NTSTATUS resolve_wins(TALLOC_CTX *mem_ctx,
2382 const char *name,
2383 int name_type,
2384 struct sockaddr_storage **return_iplist,
2385 size_t *return_count)
2387 struct tevent_context *ev;
2388 struct tevent_req *req;
2389 NTSTATUS status = NT_STATUS_NO_MEMORY;
2391 ev = samba_tevent_context_init(talloc_tos());
2392 if (ev == NULL) {
2393 goto fail;
2395 req = resolve_wins_send(ev, ev, name, name_type);
2396 if (req == NULL) {
2397 goto fail;
2399 if (!tevent_req_poll_ntstatus(req, ev, &status)) {
2400 goto fail;
2402 status = resolve_wins_recv(req, mem_ctx, return_iplist, return_count,
2403 NULL);
2404 fail:
2405 TALLOC_FREE(ev);
2406 return status;
2410 /********************************************************
2411 Resolve via "hosts" method.
2412 *********************************************************/
2414 static NTSTATUS resolve_hosts(TALLOC_CTX *mem_ctx,
2415 const char *name,
2416 int name_type,
2417 struct sockaddr_storage **return_iplist,
2418 size_t *return_count)
2421 * "host" means do a localhost, or dns lookup.
2423 struct addrinfo hints;
2424 struct addrinfo *ailist = NULL;
2425 struct addrinfo *res = NULL;
2426 int ret = -1;
2427 size_t i = 0;
2428 size_t ret_count = 0;
2429 struct sockaddr_storage *iplist = NULL;
2431 if ( name_type != 0x20 && name_type != 0x0) {
2432 DEBUG(5, ("resolve_hosts: not appropriate "
2433 "for name type <0x%x>\n",
2434 name_type));
2435 return NT_STATUS_INVALID_PARAMETER;
2438 DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
2439 name, name_type));
2441 ZERO_STRUCT(hints);
2442 /* By default make sure it supports TCP. */
2443 hints.ai_socktype = SOCK_STREAM;
2444 hints.ai_flags = AI_ADDRCONFIG;
2446 #if !defined(HAVE_IPV6)
2447 /* Unless we have IPv6, we really only want IPv4 addresses back. */
2448 hints.ai_family = AF_INET;
2449 #endif
2451 ret = getaddrinfo(name,
2452 NULL,
2453 &hints,
2454 &ailist);
2455 if (ret) {
2456 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
2457 name,
2458 gai_strerror(ret) ));
2461 for (res = ailist; res; res = res->ai_next) {
2462 struct sockaddr_storage ss = {0};
2463 struct sockaddr_storage *tmp = NULL;
2465 if ((res->ai_addr == NULL) ||
2466 (res->ai_addrlen == 0) ||
2467 (res->ai_addrlen > sizeof(ss))) {
2468 continue;
2471 memcpy(&ss, res->ai_addr, res->ai_addrlen);
2473 if (is_zero_addr(&ss)) {
2474 continue;
2477 /* wrap check. */
2478 if (ret_count + 1 < ret_count) {
2479 freeaddrinfo(ailist);
2480 TALLOC_FREE(iplist);
2481 return NT_STATUS_INVALID_PARAMETER;
2483 ret_count += 1;
2485 tmp = talloc_realloc(
2486 mem_ctx, iplist, struct sockaddr_storage,
2487 ret_count);
2488 if (tmp == NULL) {
2489 DEBUG(3,("resolve_hosts: malloc fail !\n"));
2490 freeaddrinfo(ailist);
2491 TALLOC_FREE(iplist);
2492 return NT_STATUS_NO_MEMORY;
2494 iplist = tmp;
2495 iplist[i] = ss;
2496 i++;
2498 if (ailist) {
2499 freeaddrinfo(ailist);
2501 if (ret_count == 0) {
2502 return NT_STATUS_UNSUCCESSFUL;
2504 *return_count = ret_count;
2505 *return_iplist = iplist;
2506 return NT_STATUS_OK;
2509 /********************************************************
2510 Resolve via "ADS" method.
2511 *********************************************************/
2513 /* Special name type used to cause a _kerberos DNS lookup. */
2514 #define KDC_NAME_TYPE 0xDCDC
2516 static NTSTATUS resolve_ads(TALLOC_CTX *ctx,
2517 const char *name,
2518 int name_type,
2519 const char *sitename,
2520 struct sockaddr_storage **return_addrs,
2521 size_t *return_count)
2523 size_t i;
2524 NTSTATUS status;
2525 struct dns_rr_srv *dcs = NULL;
2526 size_t numdcs = 0;
2527 size_t num_srv_addrs = 0;
2528 struct sockaddr_storage *srv_addrs = NULL;
2529 char *query = NULL;
2531 if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
2532 (name_type != 0x1b)) {
2533 return NT_STATUS_INVALID_PARAMETER;
2536 status = NT_STATUS_OK;
2538 switch (name_type) {
2539 case 0x1b:
2540 DEBUG(5,("resolve_ads: Attempting to resolve "
2541 "PDC for %s using DNS\n", name));
2542 query = ads_dns_query_string_pdc(ctx, name);
2543 break;
2545 case 0x1c:
2546 DEBUG(5,("resolve_ads: Attempting to resolve "
2547 "DCs for %s using DNS\n", name));
2548 query = ads_dns_query_string_dcs(ctx, name);
2549 break;
2550 case KDC_NAME_TYPE:
2551 DEBUG(5,("resolve_ads: Attempting to resolve "
2552 "KDCs for %s using DNS\n", name));
2553 query = ads_dns_query_string_kdcs(ctx, name);
2554 break;
2555 default:
2556 status = NT_STATUS_INVALID_PARAMETER;
2557 break;
2560 if (!NT_STATUS_IS_OK(status)) {
2561 return status;
2563 if (query == NULL) {
2564 return NT_STATUS_NO_MEMORY;
2567 DBG_DEBUG("SRV query for %s\n", query);
2569 status = ads_dns_query_srv(
2570 ctx,
2571 lp_get_async_dns_timeout(),
2572 sitename,
2573 query,
2574 &dcs,
2575 &numdcs);
2576 if (!NT_STATUS_IS_OK(status)) {
2577 return status;
2580 if (numdcs == 0) {
2581 *return_addrs = NULL;
2582 *return_count = 0;
2583 TALLOC_FREE(dcs);
2584 return NT_STATUS_OK;
2587 /* First count the sizes of each array. */
2588 for(i = 0; i < numdcs; i++) {
2589 if (dcs[i].ss_s == NULL) {
2591 * Nothing received or timeout in A/AAAA reqs
2593 continue;
2596 if (num_srv_addrs + dcs[i].num_ips < num_srv_addrs) {
2597 /* Wrap check. */
2598 TALLOC_FREE(dcs);
2599 return NT_STATUS_INVALID_PARAMETER;
2601 /* Add in the number of addresses we got. */
2602 num_srv_addrs += dcs[i].num_ips;
2605 /* Allocate the list of IP addresses we already have. */
2606 srv_addrs = talloc_zero_array(ctx,
2607 struct sockaddr_storage,
2608 num_srv_addrs);
2609 if (srv_addrs == NULL) {
2610 TALLOC_FREE(dcs);
2611 return NT_STATUS_NO_MEMORY;
2614 num_srv_addrs = 0;
2615 for(i = 0; i < numdcs; i++) {
2616 /* Copy all the IP addresses from the SRV response */
2617 size_t j;
2618 for (j = 0; j < dcs[i].num_ips; j++) {
2619 char addr[INET6_ADDRSTRLEN];
2621 srv_addrs[num_srv_addrs] = dcs[i].ss_s[j];
2622 if (is_zero_addr(&srv_addrs[num_srv_addrs])) {
2623 continue;
2626 DBG_DEBUG("SRV lookup %s got IP[%zu] %s\n",
2627 name,
2629 print_sockaddr(addr,
2630 sizeof(addr),
2631 &srv_addrs[num_srv_addrs]));
2633 num_srv_addrs++;
2637 TALLOC_FREE(dcs);
2639 *return_addrs = srv_addrs;
2640 *return_count = num_srv_addrs;
2641 return NT_STATUS_OK;
2644 static const char **filter_out_nbt_lookup(TALLOC_CTX *mem_ctx,
2645 const char **resolve_order)
2647 size_t i, len, result_idx;
2648 const char **result;
2650 len = 0;
2651 while (resolve_order[len] != NULL) {
2652 len += 1;
2655 result = talloc_array(mem_ctx, const char *, len+1);
2656 if (result == NULL) {
2657 return NULL;
2660 result_idx = 0;
2662 for (i=0; i<len; i++) {
2663 const char *tok = resolve_order[i];
2665 if (strequal(tok, "lmhosts") || strequal(tok, "wins") ||
2666 strequal(tok, "bcast")) {
2667 continue;
2669 result[result_idx++] = tok;
2671 result[result_idx] = NULL;
2673 return result;
2676 /*******************************************************************
2677 Samba interface to resolve a name into an IP address.
2678 Use this function if the string is either an IP address, DNS
2679 or host name or NetBIOS name. This uses the name switch in the
2680 smb.conf to determine the order of name resolution.
2682 Added support for ip addr/port to support ADS ldap servers.
2683 the only place we currently care about the port is in the
2684 resolve_hosts() when looking up DC's via SRV RR entries in DNS
2685 **********************************************************************/
2687 NTSTATUS internal_resolve_name(TALLOC_CTX *ctx,
2688 const char *name,
2689 int name_type,
2690 const char *sitename,
2691 struct samba_sockaddr **return_salist,
2692 size_t *return_count,
2693 const char **resolve_order)
2695 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2696 size_t i;
2697 size_t nc_count = 0;
2698 size_t ret_count = 0;
2699 bool ok;
2700 struct sockaddr_storage *ss_list = NULL;
2701 struct samba_sockaddr *sa_list = NULL;
2702 TALLOC_CTX *frame = talloc_stackframe();
2704 DBG_DEBUG("looking up %s#%x (sitename %s)\n",
2705 name, name_type, sitename ? sitename : "(null)");
2707 if (is_ipaddress(name)) {
2708 struct sockaddr_storage ss;
2710 /* if it's in the form of an IP address then get the lib to interpret it */
2711 ok = interpret_string_addr(&ss, name, AI_NUMERICHOST);
2712 if (!ok) {
2713 DBG_WARNING("interpret_string_addr failed on %s\n",
2714 name);
2715 TALLOC_FREE(frame);
2716 return NT_STATUS_INVALID_PARAMETER;
2718 if (is_zero_addr(&ss)) {
2719 TALLOC_FREE(frame);
2720 return NT_STATUS_UNSUCCESSFUL;
2723 status = sockaddr_array_to_samba_sockaddr_array(frame,
2724 &sa_list,
2725 &ret_count,
2726 &ss,
2728 if (!NT_STATUS_IS_OK(status)) {
2729 TALLOC_FREE(frame);
2730 return status;
2733 *return_salist = talloc_move(ctx, &sa_list);
2734 *return_count = 1;
2735 TALLOC_FREE(frame);
2736 return NT_STATUS_OK;
2739 /* Check name cache */
2741 ok = namecache_fetch(frame,
2742 name,
2743 name_type,
2744 &sa_list,
2745 &nc_count);
2746 if (ok) {
2748 * remove_duplicate_addrs2() has the
2749 * side effect of removing zero addresses,
2750 * so use it here.
2752 nc_count = remove_duplicate_addrs2(sa_list, nc_count);
2753 if (nc_count == 0) {
2754 TALLOC_FREE(sa_list);
2755 TALLOC_FREE(frame);
2756 return NT_STATUS_UNSUCCESSFUL;
2758 *return_count = nc_count;
2759 *return_salist = talloc_move(ctx, &sa_list);
2760 TALLOC_FREE(frame);
2761 return NT_STATUS_OK;
2764 /* set the name resolution order */
2766 if (resolve_order && strcmp(resolve_order[0], "NULL") == 0) {
2767 DBG_DEBUG("all lookups disabled\n");
2768 TALLOC_FREE(frame);
2769 return NT_STATUS_INVALID_PARAMETER;
2772 if (!resolve_order || !resolve_order[0]) {
2773 static const char *host_order[] = { "host", NULL };
2774 resolve_order = host_order;
2777 if ((strlen(name) > MAX_NETBIOSNAME_LEN - 1) ||
2778 (strchr(name, '.') != NULL)) {
2780 * Don't do NBT lookup, the name would not fit anyway
2782 resolve_order = filter_out_nbt_lookup(frame, resolve_order);
2783 if (resolve_order == NULL) {
2784 TALLOC_FREE(frame);
2785 return NT_STATUS_NO_MEMORY;
2789 /* iterate through the name resolution backends */
2791 for (i=0; resolve_order[i]; i++) {
2792 const char *tok = resolve_order[i];
2794 if ((strequal(tok, "host") || strequal(tok, "hosts"))) {
2795 status = resolve_hosts(talloc_tos(),
2796 name,
2797 name_type,
2798 &ss_list,
2799 &ret_count);
2800 if (!NT_STATUS_IS_OK(status)) {
2801 continue;
2803 goto done;
2806 if (strequal(tok, "kdc")) {
2807 /* deal with KDC_NAME_TYPE names here.
2808 * This will result in a SRV record lookup */
2809 status = resolve_ads(talloc_tos(),
2810 name,
2811 KDC_NAME_TYPE,
2812 sitename,
2813 &ss_list,
2814 &ret_count);
2815 if (!NT_STATUS_IS_OK(status)) {
2816 continue;
2818 /* Ensure we don't namecache
2819 * this with the KDC port. */
2820 name_type = KDC_NAME_TYPE;
2821 goto done;
2824 if (strequal(tok, "ads")) {
2825 /* deal with 0x1c and 0x1b names here.
2826 * This will result in a SRV record lookup */
2827 status = resolve_ads(talloc_tos(),
2828 name,
2829 name_type,
2830 sitename,
2831 &ss_list,
2832 &ret_count);
2833 if (!NT_STATUS_IS_OK(status)) {
2834 continue;
2836 goto done;
2839 if (strequal(tok, "lmhosts")) {
2840 status = resolve_lmhosts_file_as_sockaddr(
2841 talloc_tos(),
2842 get_dyn_LMHOSTSFILE(),
2843 name,
2844 name_type,
2845 &ss_list,
2846 &ret_count);
2847 if (!NT_STATUS_IS_OK(status)) {
2848 continue;
2850 goto done;
2853 if (strequal(tok, "wins")) {
2854 /* don't resolve 1D via WINS */
2855 if (name_type == 0x1D) {
2856 continue;
2858 status = resolve_wins(talloc_tos(),
2859 name,
2860 name_type,
2861 &ss_list,
2862 &ret_count);
2863 if (!NT_STATUS_IS_OK(status)) {
2864 continue;
2866 goto done;
2869 if (strequal(tok, "bcast")) {
2870 status = name_resolve_bcast(
2871 talloc_tos(),
2872 name,
2873 name_type,
2874 &ss_list,
2875 &ret_count);
2876 if (!NT_STATUS_IS_OK(status)) {
2877 continue;
2879 goto done;
2882 DBG_ERR("unknown name switch type %s\n", tok);
2885 /* All of the resolve_* functions above have returned false. */
2887 TALLOC_FREE(frame);
2888 *return_count = 0;
2890 return status;
2892 done:
2894 status = sockaddr_array_to_samba_sockaddr_array(frame,
2895 &sa_list,
2896 &ret_count,
2897 ss_list,
2898 ret_count);
2899 if (!NT_STATUS_IS_OK(status)) {
2900 TALLOC_FREE(frame);
2901 return NT_STATUS_NO_MEMORY;
2904 /* Remove duplicate entries. Some queries, notably #1c (domain
2905 controllers) return the PDC in iplist[0] and then all domain
2906 controllers including the PDC in iplist[1..n]. Iterating over
2907 the iplist when the PDC is down will cause two sets of timeouts. */
2909 ret_count = remove_duplicate_addrs2(sa_list, ret_count);
2911 /* Save in name cache */
2912 if ( DEBUGLEVEL >= 100 ) {
2913 for (i = 0; i < ret_count && DEBUGLEVEL == 100; i++) {
2914 char addr[INET6_ADDRSTRLEN];
2915 print_sockaddr(addr, sizeof(addr),
2916 &sa_list[i].u.ss);
2917 DEBUG(100, ("Storing name %s of type %d (%s:0)\n",
2918 name,
2919 name_type,
2920 addr));
2924 if (ret_count) {
2925 namecache_store(name,
2926 name_type,
2927 ret_count,
2928 sa_list);
2931 /* Display some debugging info */
2933 if ( DEBUGLEVEL >= 10 ) {
2934 DBG_DEBUG("returning %zu addresses: ",
2935 ret_count);
2937 for (i = 0; i < ret_count; i++) {
2938 char addr[INET6_ADDRSTRLEN];
2939 print_sockaddr(addr, sizeof(addr),
2940 &sa_list[i].u.ss);
2941 DEBUGADD(10, ("%s ", addr));
2943 DEBUG(10, ("\n"));
2946 *return_count = ret_count;
2947 *return_salist = talloc_move(ctx, &sa_list);
2949 TALLOC_FREE(frame);
2950 return status;
2953 /********************************************************
2954 Internal interface to resolve a name into one IP address.
2955 Use this function if the string is either an IP address, DNS
2956 or host name or NetBIOS name. This uses the name switch in the
2957 smb.conf to determine the order of name resolution.
2958 *********************************************************/
2960 bool resolve_name(const char *name,
2961 struct sockaddr_storage *return_ss,
2962 int name_type,
2963 bool prefer_ipv4)
2965 struct samba_sockaddr *sa_list = NULL;
2966 char *sitename = NULL;
2967 size_t count = 0;
2968 NTSTATUS status;
2969 TALLOC_CTX *frame = NULL;
2971 if (is_ipaddress(name)) {
2972 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
2975 frame = talloc_stackframe();
2977 sitename = sitename_fetch(frame, lp_realm()); /* wild guess */
2979 status = internal_resolve_name(frame,
2980 name,
2981 name_type,
2982 sitename,
2983 &sa_list,
2984 &count,
2985 lp_name_resolve_order());
2986 if (NT_STATUS_IS_OK(status)) {
2987 size_t i;
2989 if (prefer_ipv4) {
2990 for (i=0; i<count; i++) {
2991 if (!is_broadcast_addr(&sa_list[i].u.sa) &&
2992 (sa_list[i].u.ss.ss_family == AF_INET)) {
2993 *return_ss = sa_list[i].u.ss;
2994 TALLOC_FREE(sa_list);
2995 TALLOC_FREE(frame);
2996 return True;
3001 /* only return valid addresses for TCP connections */
3002 for (i=0; i<count; i++) {
3003 if (!is_broadcast_addr(&sa_list[i].u.sa)) {
3004 *return_ss = sa_list[i].u.ss;
3005 TALLOC_FREE(sa_list);
3006 TALLOC_FREE(frame);
3007 return True;
3012 TALLOC_FREE(sa_list);
3013 TALLOC_FREE(frame);
3014 return False;
3017 /********************************************************
3018 Internal interface to resolve a name into a list of IP addresses.
3019 Use this function if the string is either an IP address, DNS
3020 or host name or NetBIOS name. This uses the name switch in the
3021 smb.conf to determine the order of name resolution.
3022 *********************************************************/
3024 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
3025 const char *name,
3026 int name_type,
3027 struct sockaddr_storage **return_ss_arr,
3028 unsigned int *p_num_entries)
3030 struct samba_sockaddr *sa_list = NULL;
3031 char *sitename = NULL;
3032 size_t count = 0;
3033 size_t i;
3034 unsigned int num_entries = 0;
3035 struct sockaddr_storage *result_arr = NULL;
3036 NTSTATUS status;
3038 if (is_ipaddress(name)) {
3039 result_arr = talloc(ctx, struct sockaddr_storage);
3040 if (result_arr == NULL) {
3041 return NT_STATUS_NO_MEMORY;
3043 if (!interpret_string_addr(result_arr, name, AI_NUMERICHOST)) {
3044 TALLOC_FREE(result_arr);
3045 return NT_STATUS_BAD_NETWORK_NAME;
3047 *p_num_entries = 1;
3048 *return_ss_arr = result_arr;
3049 return NT_STATUS_OK;
3052 sitename = sitename_fetch(ctx, lp_realm()); /* wild guess */
3054 status = internal_resolve_name(ctx,
3055 name,
3056 name_type,
3057 sitename,
3058 &sa_list,
3059 &count,
3060 lp_name_resolve_order());
3061 TALLOC_FREE(sitename);
3063 if (!NT_STATUS_IS_OK(status)) {
3064 return status;
3067 /* only return valid addresses for TCP connections */
3068 for (i=0, num_entries = 0; i<count; i++) {
3069 if (!is_zero_addr(&sa_list[i].u.ss) &&
3070 !is_broadcast_addr(&sa_list[i].u.sa)) {
3071 num_entries++;
3074 if (num_entries == 0) {
3075 status = NT_STATUS_BAD_NETWORK_NAME;
3076 goto done;
3079 result_arr = talloc_array(ctx,
3080 struct sockaddr_storage,
3081 num_entries);
3082 if (result_arr == NULL) {
3083 status = NT_STATUS_NO_MEMORY;
3084 goto done;
3087 for (i=0, num_entries = 0; i<count; i++) {
3088 if (!is_zero_addr(&sa_list[i].u.ss) &&
3089 !is_broadcast_addr(&sa_list[i].u.sa)) {
3090 result_arr[num_entries++] = sa_list[i].u.ss;
3094 if (num_entries == 0) {
3095 TALLOC_FREE(result_arr);
3096 status = NT_STATUS_BAD_NETWORK_NAME;
3097 goto done;
3100 status = NT_STATUS_OK;
3101 *p_num_entries = num_entries;
3102 *return_ss_arr = result_arr;
3103 done:
3104 TALLOC_FREE(sa_list);
3105 return status;
3108 /********************************************************
3109 Find the IP address of the master browser or DMB for a workgroup.
3110 *********************************************************/
3112 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
3114 struct samba_sockaddr *sa_list = NULL;
3115 size_t count = 0;
3116 NTSTATUS status;
3118 if (lp_disable_netbios()) {
3119 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
3120 return false;
3123 status = internal_resolve_name(talloc_tos(),
3124 group,
3125 0x1D,
3126 NULL,
3127 &sa_list,
3128 &count,
3129 lp_name_resolve_order());
3130 if (NT_STATUS_IS_OK(status)) {
3131 *master_ss = sa_list[0].u.ss;
3132 TALLOC_FREE(sa_list);
3133 return true;
3136 TALLOC_FREE(sa_list);
3138 status = internal_resolve_name(talloc_tos(),
3139 group,
3140 0x1B,
3141 NULL,
3142 &sa_list,
3143 &count,
3144 lp_name_resolve_order());
3145 if (NT_STATUS_IS_OK(status)) {
3146 *master_ss = sa_list[0].u.ss;
3147 TALLOC_FREE(sa_list);
3148 return true;
3151 TALLOC_FREE(sa_list);
3152 return false;
3155 /********************************************************
3156 Get the IP address list of the primary domain controller
3157 for a domain.
3158 *********************************************************/
3160 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
3162 struct samba_sockaddr *sa_list = NULL;
3163 size_t count = 0;
3164 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
3165 static const char *ads_order[] = { "ads", NULL };
3166 /* Look up #1B name */
3168 if (lp_security() == SEC_ADS) {
3169 status = internal_resolve_name(talloc_tos(),
3170 domain,
3171 0x1b,
3172 NULL,
3173 &sa_list,
3174 &count,
3175 ads_order);
3178 if (!NT_STATUS_IS_OK(status) || count == 0) {
3179 TALLOC_FREE(sa_list);
3180 status = internal_resolve_name(talloc_tos(),
3181 domain,
3182 0x1b,
3183 NULL,
3184 &sa_list,
3185 &count,
3186 lp_name_resolve_order());
3187 if (!NT_STATUS_IS_OK(status)) {
3188 TALLOC_FREE(sa_list);
3189 return false;
3193 /* if we get more than 1 IP back we have to assume it is a
3194 multi-homed PDC and not a mess up */
3196 if ( count > 1 ) {
3197 DBG_INFO("PDC has %zu IP addresses!\n", count);
3198 sort_sa_list(sa_list, count);
3201 *pss = sa_list[0].u.ss;
3202 TALLOC_FREE(sa_list);
3203 return true;
3206 /* Private enum type for lookups. */
3208 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
3210 /********************************************************
3211 Get the IP address list of the domain controllers for
3212 a domain.
3213 *********************************************************/
3215 static NTSTATUS get_dc_list(TALLOC_CTX *ctx,
3216 const char *domain,
3217 const char *sitename,
3218 struct samba_sockaddr **sa_list_ret,
3219 size_t *ret_count,
3220 enum dc_lookup_type lookup_type,
3221 bool *ordered)
3223 const char **resolve_order = NULL;
3224 char *saf_servername = NULL;
3225 char *pserver = NULL;
3226 const char *p;
3227 char *name;
3228 size_t num_addresses = 0;
3229 size_t local_count = 0;
3230 size_t i;
3231 struct samba_sockaddr *auto_sa_list = NULL;
3232 struct samba_sockaddr *return_salist = NULL;
3233 bool done_auto_lookup = false;
3234 size_t auto_count = 0;
3235 NTSTATUS status;
3236 TALLOC_CTX *frame = talloc_stackframe();
3237 int auto_name_type = 0x1C;
3239 *ordered = False;
3241 /* if we are restricted to solely using DNS for looking
3242 up a domain controller, make sure that host lookups
3243 are enabled for the 'name resolve order'. If host lookups
3244 are disabled and ads_only is True, then set the string to
3245 NULL. */
3247 resolve_order = lp_name_resolve_order();
3248 if (!resolve_order) {
3249 status = NT_STATUS_NO_MEMORY;
3250 goto out;
3252 if (lookup_type == DC_ADS_ONLY) {
3253 if (str_list_check_ci(resolve_order, "host")) {
3254 static const char *ads_order[] = { "ads", NULL };
3255 resolve_order = ads_order;
3257 /* DNS SRV lookups used by the ads resolver
3258 are already sorted by priority and weight */
3259 *ordered = true;
3260 } else {
3261 /* this is quite bizarre! */
3262 static const char *null_order[] = { "NULL", NULL };
3263 resolve_order = null_order;
3265 } else if (lookup_type == DC_KDC_ONLY) {
3266 static const char *kdc_order[] = { "kdc", NULL };
3267 /* DNS SRV lookups used by the ads/kdc resolver
3268 are already sorted by priority and weight */
3269 *ordered = true;
3270 resolve_order = kdc_order;
3271 auto_name_type = KDC_NAME_TYPE;
3274 /* fetch the server we have affinity for. Add the
3275 'password server' list to a search for our domain controllers */
3277 saf_servername = saf_fetch(frame, domain);
3279 if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
3280 pserver = talloc_asprintf(frame, "%s, %s",
3281 saf_servername ? saf_servername : "",
3282 lp_password_server());
3283 } else {
3284 pserver = talloc_asprintf(frame, "%s, *",
3285 saf_servername ? saf_servername : "");
3288 TALLOC_FREE(saf_servername);
3289 if (!pserver) {
3290 status = NT_STATUS_NO_MEMORY;
3291 goto out;
3294 DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
3297 * if '*' appears in the "password server" list then add
3298 * an auto lookup to the list of manually configured
3299 * DC's. If any DC is listed by name, then the list should be
3300 * considered to be ordered
3303 p = pserver;
3304 while (next_token_talloc(frame, &p, &name, LIST_SEP)) {
3305 if (!done_auto_lookup && strequal(name, "*")) {
3306 done_auto_lookup = true;
3308 status = internal_resolve_name(frame,
3309 domain,
3310 auto_name_type,
3311 sitename,
3312 &auto_sa_list,
3313 &auto_count,
3314 resolve_order);
3315 if (!NT_STATUS_IS_OK(status)) {
3316 continue;
3318 /* Wrap check. */
3319 if (num_addresses + auto_count < num_addresses) {
3320 TALLOC_FREE(auto_sa_list);
3321 status = NT_STATUS_INVALID_PARAMETER;
3322 goto out;
3324 num_addresses += auto_count;
3325 DBG_DEBUG("Adding %zu DC's from auto lookup\n",
3326 auto_count);
3327 } else {
3328 /* Wrap check. */
3329 if (num_addresses + 1 < num_addresses) {
3330 TALLOC_FREE(auto_sa_list);
3331 status = NT_STATUS_INVALID_PARAMETER;
3332 goto out;
3334 num_addresses++;
3338 /* if we have no addresses and haven't done the auto lookup, then
3339 just return the list of DC's. Or maybe we just failed. */
3341 if (num_addresses == 0) {
3342 struct samba_sockaddr *dc_salist = NULL;
3343 size_t dc_count = 0;
3345 if (done_auto_lookup) {
3346 DEBUG(4,("get_dc_list: no servers found\n"));
3347 status = NT_STATUS_NO_LOGON_SERVERS;
3348 goto out;
3350 /* talloc off frame, only move to ctx on success. */
3351 status = internal_resolve_name(frame,
3352 domain,
3353 auto_name_type,
3354 sitename,
3355 &dc_salist,
3356 &dc_count,
3357 resolve_order);
3358 if (!NT_STATUS_IS_OK(status)) {
3359 goto out;
3361 return_salist = dc_salist;
3362 local_count = dc_count;
3363 goto out;
3366 return_salist = talloc_zero_array(frame,
3367 struct samba_sockaddr,
3368 num_addresses);
3369 if (return_salist == NULL) {
3370 DEBUG(3,("get_dc_list: malloc fail !\n"));
3371 status = NT_STATUS_NO_MEMORY;
3372 goto out;
3375 p = pserver;
3376 local_count = 0;
3378 /* fill in the return list now with real IP's */
3380 while ((local_count<num_addresses) &&
3381 next_token_talloc(frame, &p, &name, LIST_SEP)) {
3382 struct samba_sockaddr name_sa = {0};
3384 /* copy any addresses from the auto lookup */
3386 if (strequal(name, "*")) {
3387 size_t j;
3388 for (j=0; j<auto_count; j++) {
3389 char addr[INET6_ADDRSTRLEN];
3390 print_sockaddr(addr,
3391 sizeof(addr),
3392 &auto_sa_list[j].u.ss);
3393 /* Check for and don't copy any
3394 * known bad DC IP's. */
3395 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
3396 domain,
3397 addr))) {
3398 DEBUG(5,("get_dc_list: "
3399 "negative entry %s removed "
3400 "from DC list\n",
3401 addr));
3402 continue;
3404 return_salist[local_count] = auto_sa_list[j];
3405 local_count++;
3407 continue;
3410 /* explicit lookup; resolve_name() will
3411 * handle names & IP addresses */
3412 if (resolve_name(name, &name_sa.u.ss, 0x20, true)) {
3413 char addr[INET6_ADDRSTRLEN];
3414 bool ok;
3417 * Ensure we set sa_socklen correctly.
3418 * Doesn't matter now, but eventually we
3419 * will remove ip_service and return samba_sockaddr
3420 * arrays directly.
3422 ok = sockaddr_storage_to_samba_sockaddr(
3423 &name_sa,
3424 &name_sa.u.ss);
3425 if (!ok) {
3426 status = NT_STATUS_INVALID_ADDRESS;
3427 goto out;
3430 print_sockaddr(addr,
3431 sizeof(addr),
3432 &name_sa.u.ss);
3434 /* Check for and don't copy any known bad DC IP's. */
3435 if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
3436 addr)) ) {
3437 DEBUG(5,("get_dc_list: negative entry %s "
3438 "removed from DC list\n",
3439 name ));
3440 continue;
3443 return_salist[local_count] = name_sa;
3444 local_count++;
3445 *ordered = true;
3449 /* need to remove duplicates in the list if we have any
3450 explicit password servers */
3452 local_count = remove_duplicate_addrs2(return_salist, local_count );
3454 /* For DC's we always prioritize IPv4 due to W2K3 not
3455 * supporting LDAP, KRB5 or CLDAP over IPv6. */
3457 if (local_count && return_salist != NULL) {
3458 prioritize_ipv4_list(return_salist, local_count);
3461 if ( DEBUGLEVEL >= 4 ) {
3462 DEBUG(4,("get_dc_list: returning %zu ip addresses "
3463 "in an %sordered list\n",
3464 local_count,
3465 *ordered ? "":"un"));
3466 DEBUG(4,("get_dc_list: "));
3467 for ( i=0; i<local_count; i++ ) {
3468 char addr[INET6_ADDRSTRLEN];
3469 print_sockaddr(addr,
3470 sizeof(addr),
3471 &return_salist[i].u.ss);
3472 DEBUGADD(4,("%s ", addr));
3474 DEBUGADD(4,("\n"));
3477 status = (local_count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS);
3479 out:
3481 if (NT_STATUS_IS_OK(status)) {
3482 *sa_list_ret = talloc_move(ctx, &return_salist);
3483 *ret_count = local_count;
3485 TALLOC_FREE(return_salist);
3486 TALLOC_FREE(auto_sa_list);
3487 TALLOC_FREE(frame);
3488 return status;
3491 /*********************************************************************
3492 Small wrapper function to get the DC list and sort it if necessary.
3493 Returns a samba_sockaddr array.
3494 *********************************************************************/
3496 NTSTATUS get_sorted_dc_list(TALLOC_CTX *ctx,
3497 const char *domain,
3498 const char *sitename,
3499 struct samba_sockaddr **sa_list_ret,
3500 size_t *ret_count,
3501 bool ads_only)
3503 bool ordered = false;
3504 NTSTATUS status;
3505 enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
3506 struct samba_sockaddr *sa_list = NULL;
3507 size_t count = 0;
3509 DBG_INFO("attempting lookup for name %s (sitename %s)\n",
3510 domain,
3511 sitename ? sitename : "NULL");
3513 if (ads_only) {
3514 lookup_type = DC_ADS_ONLY;
3517 status = get_dc_list(ctx,
3518 domain,
3519 sitename,
3520 &sa_list,
3521 &count,
3522 lookup_type,
3523 &ordered);
3524 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS)
3525 && sitename) {
3526 DBG_WARNING("No server for domain '%s' available"
3527 " in site '%s', fallback to all servers\n",
3528 domain,
3529 sitename);
3530 status = get_dc_list(ctx,
3531 domain,
3532 NULL,
3533 &sa_list,
3534 &count,
3535 lookup_type,
3536 &ordered);
3539 if (!NT_STATUS_IS_OK(status)) {
3540 return status;
3543 /* only sort if we don't already have an ordered list */
3544 if (!ordered) {
3545 sort_sa_list(sa_list, count);
3548 *ret_count = count;
3549 *sa_list_ret = sa_list;
3550 return status;
3553 /*********************************************************************
3554 Get the KDC list - re-use all the logic in get_dc_list.
3555 Returns a samba_sockaddr array.
3556 *********************************************************************/
3558 NTSTATUS get_kdc_list(TALLOC_CTX *ctx,
3559 const char *realm,
3560 const char *sitename,
3561 struct samba_sockaddr **sa_list_ret,
3562 size_t *ret_count)
3564 size_t count = 0;
3565 struct samba_sockaddr *sa_list = NULL;
3566 bool ordered = false;
3567 NTSTATUS status;
3569 status = get_dc_list(ctx,
3570 realm,
3571 sitename,
3572 &sa_list,
3573 &count,
3574 DC_KDC_ONLY,
3575 &ordered);
3577 if (!NT_STATUS_IS_OK(status)) {
3578 return status;
3581 /* only sort if we don't already have an ordered list */
3582 if (!ordered ) {
3583 sort_sa_list(sa_list, count);
3586 *ret_count = count;
3587 *sa_list_ret = sa_list;
3588 return status;