2 Unix SMB/CIFS implementation.
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/>.
22 #include "libads/sitename_cache.h"
23 #include "libads/dns.h"
24 #include "../libcli/netlogon.h"
25 #include "librpc/gen_ndr/messaging.h"
26 #include "lib/async_req/async_sock.h"
28 /* nmbd.c sets this to True. */
29 bool global_in_nmbd = False;
31 /****************************
32 * SERVER AFFINITY ROUTINES *
33 ****************************/
35 /* Server affinity is the concept of preferring the last domain
36 controller with whom you had a successful conversation */
38 /****************************************************************************
39 ****************************************************************************/
40 #define SAFKEY_FMT "SAF/DOMAIN/%s"
42 #define SAFJOINKEY_FMT "SAFJOIN/DOMAIN/%s"
43 #define SAFJOIN_TTL 3600
45 static char *saf_key(const char *domain)
49 asprintf_strupper_m(&keystr, SAFKEY_FMT, domain);
54 static char *saf_join_key(const char *domain)
58 asprintf_strupper_m(&keystr, SAFJOINKEY_FMT, domain);
63 /****************************************************************************
64 ****************************************************************************/
66 bool saf_store( const char *domain, const char *servername )
72 if ( !domain || !servername ) {
73 DEBUG(2,("saf_store: "
74 "Refusing to store empty domain or servername!\n"));
78 if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
79 DEBUG(0,("saf_store: "
80 "refusing to store 0 length domain or servername!\n"));
84 key = saf_key( domain );
85 expire = time( NULL ) + lp_parm_int(-1, "saf","ttl", SAF_TTL);
87 DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
88 domain, servername, (unsigned int)expire ));
90 ret = gencache_set( key, servername, expire );
97 bool saf_join_store( const char *domain, const char *servername )
103 if ( !domain || !servername ) {
104 DEBUG(2,("saf_join_store: Refusing to store empty domain or servername!\n"));
108 if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
109 DEBUG(0,("saf_join_store: refusing to store 0 length domain or servername!\n"));
113 key = saf_join_key( domain );
114 expire = time( NULL ) + lp_parm_int(-1, "saf","join ttl", SAFJOIN_TTL);
116 DEBUG(10,("saf_join_store: domain = [%s], server = [%s], expire = [%u]\n",
117 domain, servername, (unsigned int)expire ));
119 ret = gencache_set( key, servername, expire );
126 bool saf_delete( const char *domain )
132 DEBUG(2,("saf_delete: Refusing to delete empty domain\n"));
136 key = saf_join_key(domain);
137 ret = gencache_del(key);
141 DEBUG(10,("saf_delete[join]: domain = [%s]\n", domain ));
144 key = saf_key(domain);
145 ret = gencache_del(key);
149 DEBUG(10,("saf_delete: domain = [%s]\n", domain ));
155 /****************************************************************************
156 ****************************************************************************/
158 char *saf_fetch( const char *domain )
165 if ( !domain || strlen(domain) == 0) {
166 DEBUG(2,("saf_fetch: Empty domain name!\n"));
170 key = saf_join_key( domain );
172 ret = gencache_get( key, &server, &timeout );
177 DEBUG(5,("saf_fetch[join]: Returning \"%s\" for \"%s\" domain\n",
182 key = saf_key( domain );
184 ret = gencache_get( key, &server, &timeout );
189 DEBUG(5,("saf_fetch: failed to find server for \"%s\" domain\n",
192 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
199 /****************************************************************************
200 Generate a random trn_id.
201 ****************************************************************************/
203 static int generate_trn_id(void)
207 generate_random_buffer((uint8 *)&id, sizeof(id));
209 return id % (unsigned)0x7FFF;
212 /****************************************************************************
213 Parse a node status response into an array of structures.
214 ****************************************************************************/
216 static struct node_status *parse_node_status(TALLOC_CTX *mem_ctx, char *p,
218 struct node_status_extra *extra)
220 struct node_status *ret;
223 *num_names = CVAL(p,0);
228 ret = TALLOC_ARRAY(mem_ctx, struct node_status,*num_names);
233 for (i=0;i< *num_names;i++) {
234 StrnCpy(ret[i].name,p,15);
235 trim_char(ret[i].name,'\0',' ');
236 ret[i].type = CVAL(p,15);
237 ret[i].flags = p[16];
239 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
240 ret[i].type, ret[i].flags));
243 * Also, pick up the MAC address ...
246 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
251 struct sock_packet_read_state {
252 struct tevent_context *ev;
253 enum packet_type type;
256 struct nb_packet_reader *reader;
257 struct tevent_req *reader_req;
260 struct tevent_req *socket_req;
262 struct sockaddr_storage addr;
265 bool (*validator)(struct packet_struct *p,
269 struct packet_struct *packet;
272 static int sock_packet_read_state_destructor(struct sock_packet_read_state *s);
273 static void sock_packet_read_got_packet(struct tevent_req *subreq);
274 static void sock_packet_read_got_socket(struct tevent_req *subreq);
276 static struct tevent_req *sock_packet_read_send(
278 struct tevent_context *ev,
279 int sock, /* dgram socket */
280 struct nb_packet_reader *reader,
281 enum packet_type type,
283 bool (*validator)(struct packet_struct *p, void *private_data),
286 struct tevent_req *req;
287 struct sock_packet_read_state *state;
289 req = tevent_req_create(mem_ctx, &state,
290 struct sock_packet_read_state);
294 talloc_set_destructor(state, sock_packet_read_state_destructor);
296 state->reader = reader;
299 state->trn_id = trn_id;
300 state->validator = validator;
301 state->private_data = private_data;
303 if (reader != NULL) {
304 state->reader_req = nb_packet_read_send(state, ev, reader);
305 if (tevent_req_nomem(state->reader_req, req)) {
306 return tevent_req_post(req, ev);
308 tevent_req_set_callback(
309 state->reader_req, sock_packet_read_got_packet, req);
312 state->addr_len = sizeof(state->addr);
313 state->socket_req = recvfrom_send(state, ev, sock,
314 state->buf, sizeof(state->buf), 0,
315 &state->addr, &state->addr_len);
316 if (tevent_req_nomem(state->socket_req, req)) {
317 return tevent_req_post(req, ev);
319 tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
325 static int sock_packet_read_state_destructor(struct sock_packet_read_state *s)
327 if (s->packet != NULL) {
328 free_packet(s->packet);
334 static void sock_packet_read_got_packet(struct tevent_req *subreq)
336 struct tevent_req *req = tevent_req_callback_data(
337 subreq, struct tevent_req);
338 struct sock_packet_read_state *state = tevent_req_data(
339 req, struct sock_packet_read_state);
342 status = nb_packet_read_recv(subreq, &state->packet);
344 TALLOC_FREE(state->reader_req);
346 if (!NT_STATUS_IS_OK(status)) {
347 if (state->socket_req != NULL) {
349 * Still waiting for socket
354 * Both socket and packet reader failed
356 tevent_req_nterror(req, status);
360 if ((state->validator != NULL) &&
361 !state->validator(state->packet, state->private_data)) {
362 DEBUG(10, ("validator failed\n"));
364 free_packet(state->packet);
365 state->packet = NULL;
367 state->reader_req = nb_packet_read_send(state, state->ev,
369 if (tevent_req_nomem(state->reader_req, req)) {
372 tevent_req_set_callback(
373 state->reader_req, sock_packet_read_got_packet, req);
377 TALLOC_FREE(state->socket_req);
378 tevent_req_done(req);
381 static void sock_packet_read_got_socket(struct tevent_req *subreq)
383 struct tevent_req *req = tevent_req_callback_data(
384 subreq, struct tevent_req);
385 struct sock_packet_read_state *state = tevent_req_data(
386 req, struct sock_packet_read_state);
387 struct sockaddr_in *in_addr;
391 received = recvfrom_recv(subreq, &err);
393 TALLOC_FREE(state->socket_req);
395 if (received == -1) {
396 if (state->reader_req != NULL) {
398 * Still waiting for reader
403 * Both socket and reader failed
405 tevent_req_nterror(req, map_nt_error_from_unix(err));
408 if (state->addr.ss_family != AF_INET) {
411 in_addr = (struct sockaddr_in *)(void *)&state->addr;
413 state->packet = parse_packet((char *)state->buf, received, state->type,
414 in_addr->sin_addr, in_addr->sin_port);
415 if (state->packet == NULL) {
416 DEBUG(10, ("parse_packet failed\n"));
419 if ((state->trn_id != -1) &&
420 (state->trn_id != packet_trn_id(state->packet))) {
421 DEBUG(10, ("Expected transaction id %d, got %d\n",
422 state->trn_id, packet_trn_id(state->packet)));
426 if ((state->validator != NULL) &&
427 !state->validator(state->packet, state->private_data)) {
428 DEBUG(10, ("validator failed\n"));
432 tevent_req_done(req);
436 if (state->packet != NULL) {
437 free_packet(state->packet);
438 state->packet = NULL;
440 state->socket_req = recvfrom_send(state, state->ev, state->sock,
441 state->buf, sizeof(state->buf), 0,
442 &state->addr, &state->addr_len);
443 if (tevent_req_nomem(state->socket_req, req)) {
446 tevent_req_set_callback(state->socket_req, sock_packet_read_got_socket,
450 static NTSTATUS sock_packet_read_recv(struct tevent_req *req,
451 struct packet_struct **ppacket)
453 struct sock_packet_read_state *state = tevent_req_data(
454 req, struct sock_packet_read_state);
457 if (tevent_req_is_nterror(req, &status)) {
460 *ppacket = state->packet;
461 state->packet = NULL;
465 /****************************************************************************
466 Try and send a request to nmbd to send a packet_struct packet first.
467 If this fails, use send_packet().
468 **************************************************************************/
470 static bool send_packet_request(struct packet_struct *p)
472 struct messaging_context *msg_ctx = server_messaging_context();
474 pid_t nmbd_pid = pidfile_pid("nmbd");
478 if (NT_STATUS_IS_OK(messaging_send_buf(msg_ctx,
479 pid_to_procid(nmbd_pid),
482 sizeof(struct packet_struct)))) {
488 return send_packet(p);
491 /****************************************************************************
492 Do a NBT node status query on an open socket and return an array of
493 structures holding the returned names or NULL if the query failed.
494 **************************************************************************/
496 NTSTATUS node_status_query(int fd,
497 struct nmb_name *name,
498 const struct sockaddr_storage *to_ss,
500 struct node_status **names,
502 struct node_status_extra *extra)
506 int retry_time = 2000;
508 struct packet_struct p;
509 struct packet_struct *p2;
510 struct nmb_packet *nmb = &p.packet.nmb;
511 struct node_status *ret;
515 if (to_ss->ss_family != AF_INET) {
516 /* Can't do node status to IPv6 */
517 return NT_STATUS_INVALID_ADDRESS;
519 nmb->header.name_trn_id = generate_trn_id();
520 nmb->header.opcode = 0;
521 nmb->header.response = false;
522 nmb->header.nm_flags.bcast = false;
523 nmb->header.nm_flags.recursion_available = false;
524 nmb->header.nm_flags.recursion_desired = false;
525 nmb->header.nm_flags.trunc = false;
526 nmb->header.nm_flags.authoritative = false;
527 nmb->header.rcode = 0;
528 nmb->header.qdcount = 1;
529 nmb->header.ancount = 0;
530 nmb->header.nscount = 0;
531 nmb->header.arcount = 0;
532 nmb->question.question_name = *name;
533 nmb->question.question_type = 0x21;
534 nmb->question.question_class = 0x1;
536 p.ip = ((const struct sockaddr_in *)to_ss)->sin_addr;
540 p.timestamp = time(NULL);
541 p.packet_type = NMB_PACKET;
543 clock_gettime_mono(&tp);
545 if (!send_packet_request(&p))
546 return NT_STATUS_NOT_FOUND;
552 clock_gettime_mono(&tp2);
553 if (nsec_time_diff(&tp2,&tp)/1000000 > retry_time) {
556 if (!found && !send_packet_request(&p))
557 return NT_STATUS_NOT_FOUND;
558 clock_gettime_mono(&tp);
562 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
563 struct nmb_packet *nmb2 = &p2->packet.nmb;
564 debug_nmb_packet(p2);
566 if (nmb2->header.opcode != 0 ||
567 nmb2->header.nm_flags.bcast ||
568 nmb2->header.rcode ||
569 !nmb2->header.ancount ||
570 nmb2->answers->rr_type != 0x21) {
571 /* XXXX what do we do with this? could be a
572 redirect, but we'll discard it for the
578 ret = parse_node_status(
579 mem_ctx, &nmb2->answers->rdata[0], num_names,
584 return NT_STATUS_NO_MEMORY;
591 return NT_STATUS_IO_TIMEOUT;
594 /****************************************************************************
595 Find the first type XX name in a node status reply - used for finding
596 a servers name given its IP. Return the matched name in *name.
597 **************************************************************************/
599 bool name_status_find(const char *q_name,
602 const struct sockaddr_storage *to_ss,
605 char addr[INET6_ADDRSTRLEN];
606 struct sockaddr_storage ss;
607 struct node_status *addrs = NULL;
608 struct nmb_name nname;
614 if (lp_disable_netbios()) {
615 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n",
620 print_sockaddr(addr, sizeof(addr), to_ss);
622 DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
625 /* Check the cache first. */
627 if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
631 if (to_ss->ss_family != AF_INET) {
632 /* Can't do node status to IPv6 */
636 if (!interpret_string_addr(&ss, lp_socket_address(),
637 AI_NUMERICHOST|AI_PASSIVE)) {
641 sock = open_socket_in(SOCK_DGRAM, 0, 3, &ss, True);
645 /* W2K PDC's seem not to respond to '*'#0. JRA */
646 make_nmb_name(&nname, q_name, q_type);
647 status = node_status_query(sock, &nname, to_ss, talloc_tos(),
648 &addrs, &count, NULL);
650 if (!NT_STATUS_IS_OK(status)) {
654 for (i=0;i<count;i++) {
655 /* Find first one of the requested type that's not a GROUP. */
656 if (addrs[i].type == type && ! (addrs[i].flags & 0x80))
662 pull_ascii_nstring(name, sizeof(fstring), addrs[i].name);
664 /* Store the result in the cache. */
665 /* but don't store an entry for 0x1c names here. Here we have
666 a single host and DOMAIN<0x1c> names should be a list of hosts */
668 if ( q_type != 0x1c ) {
669 namecache_status_store(q_name, q_type, type, to_ss, name);
677 DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
680 DEBUGADD(10, (", name %s ip address is %s", name, addr));
688 comparison function used by sort_addr_list
691 static int addr_compare(const struct sockaddr_storage *ss1,
692 const struct sockaddr_storage *ss2)
694 int max_bits1=0, max_bits2=0;
695 int num_interfaces = iface_count();
698 /* Sort IPv4 addresses first. */
699 if (ss1->ss_family != ss2->ss_family) {
700 if (ss2->ss_family == AF_INET) {
707 /* Here we know both addresses are of the same
710 for (i=0;i<num_interfaces;i++) {
711 const struct sockaddr_storage *pss = iface_n_bcast(i);
712 unsigned char *p_ss1 = NULL;
713 unsigned char *p_ss2 = NULL;
714 unsigned char *p_if = NULL;
718 if (pss->ss_family != ss1->ss_family) {
719 /* Ignore interfaces of the wrong type. */
722 if (pss->ss_family == AF_INET) {
723 p_if = (unsigned char *)
724 &((const struct sockaddr_in *)pss)->sin_addr;
725 p_ss1 = (unsigned char *)
726 &((const struct sockaddr_in *)ss1)->sin_addr;
727 p_ss2 = (unsigned char *)
728 &((const struct sockaddr_in *)ss2)->sin_addr;
731 #if defined(HAVE_IPV6)
732 if (pss->ss_family == AF_INET6) {
733 p_if = (unsigned char *)
734 &((const struct sockaddr_in6 *)pss)->sin6_addr;
735 p_ss1 = (unsigned char *)
736 &((const struct sockaddr_in6 *)ss1)->sin6_addr;
737 p_ss2 = (unsigned char *)
738 &((const struct sockaddr_in6 *)ss2)->sin6_addr;
742 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
745 bits1 = matching_len_bits(p_ss1, p_if, len);
746 bits2 = matching_len_bits(p_ss2, p_if, len);
747 max_bits1 = MAX(bits1, max_bits1);
748 max_bits2 = MAX(bits2, max_bits2);
751 /* Bias towards directly reachable IPs */
752 if (iface_local((struct sockaddr *)ss1)) {
753 if (ss1->ss_family == AF_INET) {
759 if (iface_local((struct sockaddr *)ss2)) {
760 if (ss2->ss_family == AF_INET) {
766 return max_bits2 - max_bits1;
769 /*******************************************************************
770 compare 2 ldap IPs by nearness to our interfaces - used in qsort
771 *******************************************************************/
773 int ip_service_compare(struct ip_service *ss1, struct ip_service *ss2)
777 if ((result = addr_compare(&ss1->ss, &ss2->ss)) != 0) {
781 if (ss1->port > ss2->port) {
785 if (ss1->port < ss2->port) {
793 sort an IP list so that names that are close to one of our interfaces
794 are at the top. This prevents the problem where a WINS server returns an IP
795 that is not reachable from our subnet as the first match
798 static void sort_addr_list(struct sockaddr_storage *sslist, int count)
804 TYPESAFE_QSORT(sslist, count, addr_compare);
807 static void sort_service_list(struct ip_service *servlist, int count)
813 TYPESAFE_QSORT(servlist, count, ip_service_compare);
816 /**********************************************************************
817 Remove any duplicate address/port pairs in the list
818 *********************************************************************/
820 static int remove_duplicate_addrs2(struct ip_service *iplist, int count )
824 DEBUG(10,("remove_duplicate_addrs2: "
825 "looking for duplicate address/port pairs\n"));
827 /* one loop to remove duplicates */
828 for ( i=0; i<count; i++ ) {
829 if ( is_zero_addr((struct sockaddr *)&iplist[i].ss)) {
833 for ( j=i+1; j<count; j++ ) {
834 if (sockaddr_equal((struct sockaddr *)&iplist[i].ss, (struct sockaddr *)&iplist[j].ss) &&
835 iplist[i].port == iplist[j].port) {
836 zero_sockaddr(&iplist[j].ss);
841 /* one loop to clean up any holes we left */
842 /* first ip should never be a zero_ip() */
843 for (i = 0; i<count; ) {
844 if (is_zero_addr((struct sockaddr *)&iplist[i].ss) ) {
846 memmove(&iplist[i], &iplist[i+1],
847 (count - i - 1)*sizeof(iplist[i]));
858 static bool prioritize_ipv4_list(struct ip_service *iplist, int count)
860 TALLOC_CTX *frame = talloc_stackframe();
861 struct ip_service *iplist_new = TALLOC_ARRAY(frame, struct ip_service, count);
864 if (iplist_new == NULL) {
871 /* Copy IPv4 first. */
872 for (i = 0; i < count; i++) {
873 if (iplist[i].ss.ss_family == AF_INET) {
874 iplist_new[j++] = iplist[i];
879 for (i = 0; i < count; i++) {
880 if (iplist[i].ss.ss_family != AF_INET) {
881 iplist_new[j++] = iplist[i];
885 memcpy(iplist, iplist_new, sizeof(struct ip_service)*count);
890 /****************************************************************************
891 Do a netbios name query to find someones IP.
892 Returns an array of IP addresses or NULL if none.
893 *count will be set to the number of addresses returned.
894 *timed_out is set if we failed by timing out
895 ****************************************************************************/
897 NTSTATUS name_query(int fd,
902 const struct sockaddr_storage *to_ss,
904 struct sockaddr_storage **addrs,
911 int retry_time = bcast?250:2000;
913 struct packet_struct p;
914 struct packet_struct *p2;
915 struct nmb_packet *nmb = &p.packet.nmb;
916 struct sockaddr_storage *ss_list = NULL;
918 if (lp_disable_netbios()) {
919 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
921 return NT_STATUS_NOT_FOUND;
924 if (to_ss->ss_family != AF_INET) {
925 return NT_STATUS_INVALID_ADDRESS;
932 memset((char *)&p,'\0',sizeof(p));
936 nmb->header.name_trn_id = generate_trn_id();
937 nmb->header.opcode = 0;
938 nmb->header.response = false;
939 nmb->header.nm_flags.bcast = bcast;
940 nmb->header.nm_flags.recursion_available = false;
941 nmb->header.nm_flags.recursion_desired = recurse;
942 nmb->header.nm_flags.trunc = false;
943 nmb->header.nm_flags.authoritative = false;
944 nmb->header.rcode = 0;
945 nmb->header.qdcount = 1;
946 nmb->header.ancount = 0;
947 nmb->header.nscount = 0;
948 nmb->header.arcount = 0;
950 make_nmb_name(&nmb->question.question_name,name,name_type);
952 nmb->question.question_type = 0x20;
953 nmb->question.question_class = 0x1;
955 p.ip = ((struct sockaddr_in *)to_ss)->sin_addr;
959 p.timestamp = time(NULL);
960 p.packet_type = NMB_PACKET;
962 clock_gettime_mono(&tp);
964 if (!send_packet_request(&p))
965 return NT_STATUS_NOT_FOUND;
972 clock_gettime_mono(&tp2);
973 if (nsec_time_diff(&tp2,&tp)/1000000 > retry_time) {
976 if (!found && !send_packet_request(&p))
977 return NT_STATUS_NOT_FOUND;
978 clock_gettime_mono(&tp);
981 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
982 struct nmb_packet *nmb2 = &p2->packet.nmb;
983 debug_nmb_packet(p2);
985 /* If we get a Negative Name Query Response from a WINS
986 * server, we should report it and give up.
988 if( 0 == nmb2->header.opcode /* A query response */
989 && !(bcast) /* from a WINS server */
990 && nmb2->header.rcode /* Error returned */
993 if( DEBUGLVL( 3 ) ) {
994 /* Only executed if DEBUGLEVEL >= 3 */
995 dbgtext( "Negative name query "
996 "response, rcode 0x%02x: ",
997 nmb2->header.rcode );
998 switch( nmb2->header.rcode ) {
1001 "was invalidly formatted.\n" );
1004 dbgtext( "Problem with NBNS, "
1005 "cannot process name.\n");
1008 dbgtext( "The name requested "
1009 "does not exist.\n" );
1012 dbgtext( "Unsupported request "
1016 dbgtext( "Query refused "
1020 dbgtext( "Unrecognized error "
1026 return NT_STATUS_NOT_FOUND;
1029 if (nmb2->header.opcode != 0 ||
1030 nmb2->header.nm_flags.bcast ||
1031 nmb2->header.rcode ||
1032 !nmb2->header.ancount) {
1034 * XXXX what do we do with this? Could be a
1035 * redirect, but we'll discard it for the
1042 ss_list = TALLOC_REALLOC_ARRAY(mem_ctx, ss_list,
1043 struct sockaddr_storage,
1045 nmb2->answers->rdlength/6);
1048 DEBUG(0,("name_query: Realloc failed.\n"));
1050 return NT_STATUS_NO_MEMORY;
1053 DEBUG(2,("Got a positive name query response "
1055 inet_ntoa(p2->ip)));
1057 for (i=0;i<nmb2->answers->rdlength/6;i++) {
1059 putip((char *)&ip,&nmb2->answers->rdata[2+i*6]);
1060 in_addr_to_sockaddr_storage(&ss_list[(*count)],
1062 DEBUGADD(2,("%s ",inet_ntoa(ip)));
1065 DEBUGADD(2,(")\n"));
1069 /* We add the flags back ... */
1070 if (nmb2->header.response)
1071 (*flags) |= NM_FLAGS_RS;
1072 if (nmb2->header.nm_flags.authoritative)
1073 (*flags) |= NM_FLAGS_AA;
1074 if (nmb2->header.nm_flags.trunc)
1075 (*flags) |= NM_FLAGS_TC;
1076 if (nmb2->header.nm_flags.recursion_desired)
1077 (*flags) |= NM_FLAGS_RD;
1078 if (nmb2->header.nm_flags.recursion_available)
1079 (*flags) |= NM_FLAGS_RA;
1080 if (nmb2->header.nm_flags.bcast)
1081 (*flags) |= NM_FLAGS_B;
1084 * If we're doing a unicast lookup we only
1085 * expect one reply. Don't wait the full 2
1086 * seconds if we got one. JRA.
1093 /* only set timed_out if we didn't fund what we where looking for*/
1095 if ( !found && timed_out ) {
1099 /* sort the ip list so we choose close servers first if possible */
1100 sort_addr_list(ss_list, *count);
1103 return NT_STATUS_OK;
1106 /********************************************************
1107 convert an array if struct sockaddr_storage to struct ip_service
1108 return false on failure. Port is set to PORT_NONE;
1109 *********************************************************/
1111 static bool convert_ss2service(struct ip_service **return_iplist,
1112 const struct sockaddr_storage *ss_list,
1117 if ( count==0 || !ss_list )
1120 /* copy the ip address; port will be PORT_NONE */
1121 if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) ==
1123 DEBUG(0,("convert_ip2service: malloc failed "
1124 "for %d enetries!\n", count ));
1128 for ( i=0; i<count; i++ ) {
1129 (*return_iplist)[i].ss = ss_list[i];
1130 (*return_iplist)[i].port = PORT_NONE;
1136 /********************************************************
1137 Resolve via "bcast" method.
1138 *********************************************************/
1140 NTSTATUS name_resolve_bcast(const char *name,
1142 struct ip_service **return_iplist,
1146 int num_interfaces = iface_count();
1147 struct sockaddr_storage *ss_list;
1148 struct sockaddr_storage ss;
1149 NTSTATUS status = NT_STATUS_NOT_FOUND;
1151 if (lp_disable_netbios()) {
1152 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n",
1154 return NT_STATUS_INVALID_PARAMETER;
1157 *return_iplist = NULL;
1161 * "bcast" means do a broadcast lookup on all the local interfaces.
1164 DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup "
1165 "for name %s<0x%x>\n", name, name_type));
1167 if (!interpret_string_addr(&ss, lp_socket_address(),
1168 AI_NUMERICHOST|AI_PASSIVE)) {
1172 sock = open_socket_in( SOCK_DGRAM, 0, 3, &ss, true );
1174 return map_nt_error_from_unix(errno);
1177 set_socket_options(sock,"SO_BROADCAST");
1179 * Lookup the name on all the interfaces, return on
1180 * the first successful match.
1182 for( i = num_interfaces-1; i >= 0; i--) {
1183 const struct sockaddr_storage *pss = iface_n_bcast(i);
1186 /* Done this way to fix compiler error on IRIX 5.x */
1190 status = name_query(sock, name, name_type, true, true, pss,
1191 talloc_tos(), &ss_list, return_count,
1193 if (NT_STATUS_IS_OK(status)) {
1198 /* failed - no response */
1205 if (!convert_ss2service(return_iplist, ss_list, *return_count) )
1206 status = NT_STATUS_NO_MEMORY;
1208 TALLOC_FREE(ss_list);
1213 /********************************************************
1214 Resolve via "wins" method.
1215 *********************************************************/
1217 NTSTATUS resolve_wins(const char *name,
1219 struct ip_service **return_iplist,
1224 struct sockaddr_storage src_ss, *ss_list = NULL;
1225 struct in_addr src_ip;
1228 if (lp_disable_netbios()) {
1229 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n",
1231 return NT_STATUS_INVALID_PARAMETER;
1234 *return_iplist = NULL;
1237 DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n",
1240 if (wins_srv_count() < 1) {
1241 DEBUG(3,("resolve_wins: WINS server resolution selected "
1242 "and no WINS servers listed.\n"));
1243 return NT_STATUS_INVALID_PARAMETER;
1246 /* we try a lookup on each of the WINS tags in turn */
1247 wins_tags = wins_srv_tags();
1250 /* huh? no tags?? give up in disgust */
1251 return NT_STATUS_INVALID_PARAMETER;
1254 /* the address we will be sending from */
1255 if (!interpret_string_addr(&src_ss, lp_socket_address(),
1256 AI_NUMERICHOST|AI_PASSIVE)) {
1257 zero_sockaddr(&src_ss);
1260 if (src_ss.ss_family != AF_INET) {
1261 char addr[INET6_ADDRSTRLEN];
1262 print_sockaddr(addr, sizeof(addr), &src_ss);
1263 DEBUG(3,("resolve_wins: cannot receive WINS replies "
1264 "on IPv6 address %s\n",
1266 wins_srv_tags_free(wins_tags);
1267 return NT_STATUS_INVALID_PARAMETER;
1270 src_ip = ((struct sockaddr_in *)&src_ss)->sin_addr;
1272 /* in the worst case we will try every wins server with every
1274 for (t=0; wins_tags && wins_tags[t]; t++) {
1275 int srv_count = wins_srv_count_tag(wins_tags[t]);
1276 for (i=0; i<srv_count; i++) {
1277 struct sockaddr_storage wins_ss;
1278 struct in_addr wins_ip;
1282 wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
1284 if (global_in_nmbd && ismyip_v4(wins_ip)) {
1285 /* yikes! we'll loop forever */
1289 /* skip any that have been unresponsive lately */
1290 if (wins_srv_is_dead(wins_ip, src_ip)) {
1294 DEBUG(3,("resolve_wins: using WINS server %s "
1296 inet_ntoa(wins_ip), wins_tags[t]));
1298 sock = open_socket_in(SOCK_DGRAM, 0, 3, &src_ss, true);
1303 in_addr_to_sockaddr_storage(&wins_ss, wins_ip);
1304 status = name_query(sock,
1316 /* exit loop if we got a list of addresses */
1318 if (NT_STATUS_IS_OK(status)) {
1325 /* Timed out waiting for WINS server to
1328 wins_srv_died(wins_ip, src_ip);
1330 /* The name definitely isn't in this
1331 group of WINS servers.
1332 goto the next group */
1338 wins_srv_tags_free(wins_tags);
1339 return NT_STATUS_NO_LOGON_SERVERS;
1343 status = NT_STATUS_OK;
1344 if (!convert_ss2service(return_iplist, ss_list, *return_count))
1345 status = NT_STATUS_INVALID_PARAMETER;
1347 TALLOC_FREE(ss_list);
1348 wins_srv_tags_free(wins_tags);
1354 /********************************************************
1355 Resolve via "lmhosts" method.
1356 *********************************************************/
1358 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
1359 struct ip_service **return_iplist,
1363 * "lmhosts" means parse the local lmhosts file.
1365 struct sockaddr_storage *ss_list;
1366 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1367 TALLOC_CTX *ctx = NULL;
1369 *return_iplist = NULL;
1372 DEBUG(3,("resolve_lmhosts: "
1373 "Attempting lmhosts lookup for name %s<0x%x>\n",
1376 ctx = talloc_init("resolve_lmhosts");
1378 return NT_STATUS_NO_MEMORY;
1381 status = resolve_lmhosts_file_as_sockaddr(get_dyn_LMHOSTSFILE(),
1386 if (NT_STATUS_IS_OK(status)) {
1387 if (convert_ss2service(return_iplist,
1391 return NT_STATUS_OK;
1394 return NT_STATUS_NO_MEMORY;
1402 /********************************************************
1403 Resolve via "hosts" method.
1404 *********************************************************/
1406 static NTSTATUS resolve_hosts(const char *name, int name_type,
1407 struct ip_service **return_iplist,
1411 * "host" means do a localhost, or dns lookup.
1413 struct addrinfo hints;
1414 struct addrinfo *ailist = NULL;
1415 struct addrinfo *res = NULL;
1419 if ( name_type != 0x20 && name_type != 0x0) {
1420 DEBUG(5, ("resolve_hosts: not appropriate "
1421 "for name type <0x%x>\n",
1423 return NT_STATUS_INVALID_PARAMETER;
1426 *return_iplist = NULL;
1429 DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
1433 /* By default make sure it supports TCP. */
1434 hints.ai_socktype = SOCK_STREAM;
1435 hints.ai_flags = AI_ADDRCONFIG;
1437 #if !defined(HAVE_IPV6)
1438 /* Unless we have IPv6, we really only want IPv4 addresses back. */
1439 hints.ai_family = AF_INET;
1442 ret = getaddrinfo(name,
1447 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1449 gai_strerror(ret) ));
1452 for (res = ailist; res; res = res->ai_next) {
1453 struct sockaddr_storage ss;
1455 if (!res->ai_addr || res->ai_addrlen == 0) {
1460 memcpy(&ss, res->ai_addr, res->ai_addrlen);
1464 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1467 if (!*return_iplist) {
1468 DEBUG(3,("resolve_hosts: malloc fail !\n"));
1469 freeaddrinfo(ailist);
1470 return NT_STATUS_NO_MEMORY;
1472 (*return_iplist)[i].ss = ss;
1473 (*return_iplist)[i].port = PORT_NONE;
1477 freeaddrinfo(ailist);
1479 if (*return_count) {
1480 return NT_STATUS_OK;
1482 return NT_STATUS_UNSUCCESSFUL;
1485 /********************************************************
1486 Resolve via "ADS" method.
1487 *********************************************************/
1489 static NTSTATUS resolve_ads(const char *name,
1491 const char *sitename,
1492 struct ip_service **return_iplist,
1498 struct dns_rr_srv *dcs = NULL;
1502 if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1503 (name_type != 0x1b)) {
1504 return NT_STATUS_INVALID_PARAMETER;
1507 if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1508 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1509 return NT_STATUS_NO_MEMORY;
1512 /* The DNS code needs fixing to find IPv6 addresses... JRA. */
1514 switch (name_type) {
1516 DEBUG(5,("resolve_ads: Attempting to resolve "
1517 "PDC for %s using DNS\n", name));
1518 status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1522 DEBUG(5,("resolve_ads: Attempting to resolve "
1523 "DCs for %s using DNS\n", name));
1524 status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1528 DEBUG(5,("resolve_ads: Attempting to resolve "
1529 "KDCs for %s using DNS\n", name));
1530 status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1534 status = NT_STATUS_INVALID_PARAMETER;
1538 if ( !NT_STATUS_IS_OK( status ) ) {
1539 talloc_destroy(ctx);
1543 for (i=0;i<numdcs;i++) {
1544 numaddrs += MAX(dcs[i].num_ips,1);
1547 if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
1549 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
1551 talloc_destroy(ctx);
1552 return NT_STATUS_NO_MEMORY;
1555 /* now unroll the list of IP addresses */
1560 while ( i < numdcs && (*return_count<numaddrs) ) {
1561 struct ip_service *r = &(*return_iplist)[*return_count];
1563 r->port = dcs[i].port;
1565 /* If we don't have an IP list for a name, lookup it up */
1568 interpret_string_addr(&r->ss, dcs[i].hostname, 0);
1572 /* use the IP addresses from the SRV sresponse */
1574 if ( j >= dcs[i].num_ips ) {
1580 r->ss = dcs[i].ss_s[j];
1584 /* make sure it is a valid IP. I considered checking the
1585 * negative connection cache, but this is the wrong place
1586 * for it. Maybe only as a hack. After think about it, if
1587 * all of the IP addresses returned from DNS are dead, what
1588 * hope does a netbios name lookup have ? The standard reason
1589 * for falling back to netbios lookups is that our DNS server
1590 * doesn't know anything about the DC's -- jerry */
1592 if (!is_zero_addr((struct sockaddr *)&r->ss)) {
1597 talloc_destroy(ctx);
1598 return NT_STATUS_OK;
1601 /*******************************************************************
1602 Internal interface to resolve a name into an IP address.
1603 Use this function if the string is either an IP address, DNS
1604 or host name or NetBIOS name. This uses the name switch in the
1605 smb.conf to determine the order of name resolution.
1607 Added support for ip addr/port to support ADS ldap servers.
1608 the only place we currently care about the port is in the
1609 resolve_hosts() when looking up DC's via SRV RR entries in DNS
1610 **********************************************************************/
1612 NTSTATUS internal_resolve_name(const char *name,
1614 const char *sitename,
1615 struct ip_service **return_iplist,
1617 const char *resolve_order)
1621 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1623 TALLOC_CTX *frame = NULL;
1625 *return_iplist = NULL;
1628 DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1629 name, name_type, sitename ? sitename : "(null)"));
1631 if (is_ipaddress(name)) {
1632 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
1634 DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1635 return NT_STATUS_NO_MEMORY;
1638 /* ignore the port here */
1639 (*return_iplist)->port = PORT_NONE;
1641 /* if it's in the form of an IP address then get the lib to interpret it */
1642 if (!interpret_string_addr(&(*return_iplist)->ss,
1643 name, AI_NUMERICHOST)) {
1644 DEBUG(1,("internal_resolve_name: interpret_string_addr "
1647 SAFE_FREE(*return_iplist);
1648 return NT_STATUS_INVALID_PARAMETER;
1651 return NT_STATUS_OK;
1654 /* Check name cache */
1656 if (namecache_fetch(name, name_type, return_iplist, return_count)) {
1657 /* This could be a negative response */
1658 if (*return_count > 0) {
1659 return NT_STATUS_OK;
1661 return NT_STATUS_UNSUCCESSFUL;
1665 /* set the name resolution order */
1667 if (strcmp( resolve_order, "NULL") == 0) {
1668 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
1669 return NT_STATUS_INVALID_PARAMETER;
1672 if (!resolve_order[0]) {
1675 ptr = resolve_order;
1678 /* iterate through the name resolution backends */
1680 frame = talloc_stackframe();
1681 while (next_token_talloc(frame, &ptr, &tok, LIST_SEP)) {
1682 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
1683 status = resolve_hosts(name, name_type, return_iplist,
1685 if (NT_STATUS_IS_OK(status)) {
1688 } else if(strequal( tok, "kdc")) {
1689 /* deal with KDC_NAME_TYPE names here.
1690 * This will result in a SRV record lookup */
1691 status = resolve_ads(name, KDC_NAME_TYPE, sitename,
1692 return_iplist, return_count);
1693 if (NT_STATUS_IS_OK(status)) {
1694 /* Ensure we don't namecache
1695 * this with the KDC port. */
1696 name_type = KDC_NAME_TYPE;
1699 } else if(strequal( tok, "ads")) {
1700 /* deal with 0x1c and 0x1b names here.
1701 * This will result in a SRV record lookup */
1702 status = resolve_ads(name, name_type, sitename,
1703 return_iplist, return_count);
1704 if (NT_STATUS_IS_OK(status)) {
1707 } else if(strequal( tok, "lmhosts")) {
1708 status = resolve_lmhosts(name, name_type,
1709 return_iplist, return_count);
1710 if (NT_STATUS_IS_OK(status)) {
1713 } else if(strequal( tok, "wins")) {
1714 /* don't resolve 1D via WINS */
1715 if (name_type != 0x1D) {
1716 status = resolve_wins(name, name_type,
1719 if (NT_STATUS_IS_OK(status)) {
1723 } else if(strequal( tok, "bcast")) {
1724 status = name_resolve_bcast(name, name_type,
1727 if (NT_STATUS_IS_OK(status)) {
1731 DEBUG(0,("resolve_name: unknown name switch type %s\n",
1736 /* All of the resolve_* functions above have returned false. */
1739 SAFE_FREE(*return_iplist);
1742 return NT_STATUS_UNSUCCESSFUL;
1746 /* Remove duplicate entries. Some queries, notably #1c (domain
1747 controllers) return the PDC in iplist[0] and then all domain
1748 controllers including the PDC in iplist[1..n]. Iterating over
1749 the iplist when the PDC is down will cause two sets of timeouts. */
1751 if ( *return_count ) {
1752 *return_count = remove_duplicate_addrs2(*return_iplist,
1756 /* Save in name cache */
1757 if ( DEBUGLEVEL >= 100 ) {
1758 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
1759 char addr[INET6_ADDRSTRLEN];
1760 print_sockaddr(addr, sizeof(addr),
1761 &(*return_iplist)[i].ss);
1762 DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
1766 (*return_iplist)[i].port));
1770 namecache_store(name, name_type, *return_count, *return_iplist);
1772 /* Display some debugging info */
1774 if ( DEBUGLEVEL >= 10 ) {
1775 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
1778 for (i = 0; i < *return_count; i++) {
1779 char addr[INET6_ADDRSTRLEN];
1780 print_sockaddr(addr, sizeof(addr),
1781 &(*return_iplist)[i].ss);
1782 DEBUGADD(10, ("%s:%d ",
1784 (*return_iplist)[i].port));
1793 /********************************************************
1794 Internal interface to resolve a name into one IP address.
1795 Use this function if the string is either an IP address, DNS
1796 or host name or NetBIOS name. This uses the name switch in the
1797 smb.conf to determine the order of name resolution.
1798 *********************************************************/
1800 bool resolve_name(const char *name,
1801 struct sockaddr_storage *return_ss,
1805 struct ip_service *ss_list = NULL;
1806 char *sitename = NULL;
1809 if (is_ipaddress(name)) {
1810 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
1813 sitename = sitename_fetch(lp_realm()); /* wild guess */
1815 if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
1817 lp_name_resolve_order()))) {
1821 for (i=0; i<count; i++) {
1822 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
1823 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss) &&
1824 (ss_list[i].ss.ss_family == AF_INET)) {
1825 *return_ss = ss_list[i].ss;
1827 SAFE_FREE(sitename);
1833 /* only return valid addresses for TCP connections */
1834 for (i=0; i<count; i++) {
1835 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
1836 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
1837 *return_ss = ss_list[i].ss;
1839 SAFE_FREE(sitename);
1846 SAFE_FREE(sitename);
1850 /********************************************************
1851 Internal interface to resolve a name into a list of IP addresses.
1852 Use this function if the string is either an IP address, DNS
1853 or host name or NetBIOS name. This uses the name switch in the
1854 smb.conf to determine the order of name resolution.
1855 *********************************************************/
1857 NTSTATUS resolve_name_list(TALLOC_CTX *ctx,
1860 struct sockaddr_storage **return_ss_arr,
1861 unsigned int *p_num_entries)
1863 struct ip_service *ss_list = NULL;
1864 char *sitename = NULL;
1867 unsigned int num_entries;
1871 *return_ss_arr = NULL;
1873 if (is_ipaddress(name)) {
1874 *return_ss_arr = TALLOC_P(ctx, struct sockaddr_storage);
1875 if (!*return_ss_arr) {
1876 return NT_STATUS_NO_MEMORY;
1878 if (!interpret_string_addr(*return_ss_arr, name, AI_NUMERICHOST)) {
1879 TALLOC_FREE(*return_ss_arr);
1880 return NT_STATUS_BAD_NETWORK_NAME;
1883 return NT_STATUS_OK;
1886 sitename = sitename_fetch(lp_realm()); /* wild guess */
1888 status = internal_resolve_name(name, name_type, sitename,
1890 lp_name_resolve_order());
1891 SAFE_FREE(sitename);
1893 if (!NT_STATUS_IS_OK(status)) {
1897 /* only return valid addresses for TCP connections */
1898 for (i=0, num_entries = 0; i<count; i++) {
1899 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
1900 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
1904 if (num_entries == 0) {
1906 return NT_STATUS_BAD_NETWORK_NAME;
1909 *return_ss_arr = TALLOC_ARRAY(ctx,
1910 struct sockaddr_storage,
1912 if (!(*return_ss_arr)) {
1914 return NT_STATUS_NO_MEMORY;
1917 for (i=0, num_entries = 0; i<count; i++) {
1918 if (!is_zero_addr((struct sockaddr *)&ss_list[i].ss) &&
1919 !is_broadcast_addr((struct sockaddr *)&ss_list[i].ss)) {
1920 (*return_ss_arr)[num_entries++] = ss_list[i].ss;
1924 status = NT_STATUS_OK;
1925 *p_num_entries = num_entries;
1928 return NT_STATUS_OK;
1931 /********************************************************
1932 Find the IP address of the master browser or DMB for a workgroup.
1933 *********************************************************/
1935 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
1937 struct ip_service *ip_list = NULL;
1941 if (lp_disable_netbios()) {
1942 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
1946 status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
1947 lp_name_resolve_order());
1948 if (NT_STATUS_IS_OK(status)) {
1949 *master_ss = ip_list[0].ss;
1954 status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
1955 lp_name_resolve_order());
1956 if (NT_STATUS_IS_OK(status)) {
1957 *master_ss = ip_list[0].ss;
1966 /********************************************************
1967 Get the IP address list of the primary domain controller
1969 *********************************************************/
1971 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
1973 struct ip_service *ip_list = NULL;
1975 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1977 /* Look up #1B name */
1979 if (lp_security() == SEC_ADS) {
1980 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1984 if (!NT_STATUS_IS_OK(status) || count == 0) {
1985 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1987 lp_name_resolve_order());
1988 if (!NT_STATUS_IS_OK(status)) {
1993 /* if we get more than 1 IP back we have to assume it is a
1994 multi-homed PDC and not a mess up */
1997 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
1998 sort_service_list(ip_list, count);
2001 *pss = ip_list[0].ss;
2006 /* Private enum type for lookups. */
2008 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
2010 /********************************************************
2011 Get the IP address list of the domain controllers for
2013 *********************************************************/
2015 static NTSTATUS get_dc_list(const char *domain,
2016 const char *sitename,
2017 struct ip_service **ip_list,
2019 enum dc_lookup_type lookup_type,
2022 char *resolve_order = NULL;
2023 char *saf_servername = NULL;
2024 char *pserver = NULL;
2026 char *port_str = NULL;
2029 int num_addresses = 0;
2030 int local_count, i, j;
2031 struct ip_service *return_iplist = NULL;
2032 struct ip_service *auto_ip_list = NULL;
2033 bool done_auto_lookup = false;
2036 TALLOC_CTX *ctx = talloc_init("get_dc_list");
2042 return NT_STATUS_NO_MEMORY;
2047 /* if we are restricted to solely using DNS for looking
2048 up a domain controller, make sure that host lookups
2049 are enabled for the 'name resolve order'. If host lookups
2050 are disabled and ads_only is True, then set the string to
2053 resolve_order = talloc_strdup(ctx, lp_name_resolve_order());
2054 if (!resolve_order) {
2055 status = NT_STATUS_NO_MEMORY;
2058 strlower_m(resolve_order);
2059 if (lookup_type == DC_ADS_ONLY) {
2060 if (strstr( resolve_order, "host")) {
2061 resolve_order = talloc_strdup(ctx, "ads");
2063 /* DNS SRV lookups used by the ads resolver
2064 are already sorted by priority and weight */
2067 resolve_order = talloc_strdup(ctx, "NULL");
2069 } else if (lookup_type == DC_KDC_ONLY) {
2070 /* DNS SRV lookups used by the ads/kdc resolver
2071 are already sorted by priority and weight */
2073 resolve_order = talloc_strdup(ctx, "kdc");
2075 if (!resolve_order) {
2076 status = NT_STATUS_NO_MEMORY;
2080 /* fetch the server we have affinity for. Add the
2081 'password server' list to a search for our domain controllers */
2083 saf_servername = saf_fetch( domain);
2085 if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
2086 pserver = talloc_asprintf(ctx, "%s, %s",
2087 saf_servername ? saf_servername : "",
2088 lp_passwordserver());
2090 pserver = talloc_asprintf(ctx, "%s, *",
2091 saf_servername ? saf_servername : "");
2094 SAFE_FREE(saf_servername);
2096 status = NT_STATUS_NO_MEMORY;
2100 /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
2103 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
2104 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2105 count, resolve_order);
2109 DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
2112 * if '*' appears in the "password server" list then add
2113 * an auto lookup to the list of manually configured
2114 * DC's. If any DC is listed by name, then the list should be
2115 * considered to be ordered
2119 while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2120 if (!done_auto_lookup && strequal(name, "*")) {
2121 status = internal_resolve_name(domain, 0x1C, sitename,
2125 if (NT_STATUS_IS_OK(status)) {
2126 num_addresses += auto_count;
2128 done_auto_lookup = true;
2129 DEBUG(8,("Adding %d DC's from auto lookup\n",
2136 /* if we have no addresses and haven't done the auto lookup, then
2137 just return the list of DC's. Or maybe we just failed. */
2139 if ((num_addresses == 0)) {
2140 if (done_auto_lookup) {
2141 DEBUG(4,("get_dc_list: no servers found\n"));
2142 status = NT_STATUS_NO_LOGON_SERVERS;
2145 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
2146 count, resolve_order);
2150 if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
2151 num_addresses)) == NULL) {
2152 DEBUG(3,("get_dc_list: malloc fail !\n"));
2153 status = NT_STATUS_NO_MEMORY;
2160 /* fill in the return list now with real IP's */
2162 while ((local_count<num_addresses) &&
2163 next_token_talloc(ctx, &p, &name, LIST_SEP)) {
2164 struct sockaddr_storage name_ss;
2166 /* copy any addersses from the auto lookup */
2168 if (strequal(name, "*")) {
2169 for (j=0; j<auto_count; j++) {
2170 char addr[INET6_ADDRSTRLEN];
2171 print_sockaddr(addr,
2173 &auto_ip_list[j].ss);
2174 /* Check for and don't copy any
2175 * known bad DC IP's. */
2176 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
2179 DEBUG(5,("get_dc_list: "
2180 "negative entry %s removed "
2185 return_iplist[local_count].ss =
2187 return_iplist[local_count].port =
2188 auto_ip_list[j].port;
2194 /* added support for address:port syntax for ads
2195 * (not that I think anyone will ever run the LDAP
2196 * server in an AD domain on something other than
2199 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
2200 if ((port_str=strchr(name, ':')) != NULL) {
2203 port = atoi(port_str);
2206 /* explicit lookup; resolve_name() will
2207 * handle names & IP addresses */
2208 if (resolve_name( name, &name_ss, 0x20, true )) {
2209 char addr[INET6_ADDRSTRLEN];
2210 print_sockaddr(addr,
2214 /* Check for and don't copy any known bad DC IP's. */
2215 if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
2217 DEBUG(5,("get_dc_list: negative entry %s "
2218 "removed from DC list\n",
2223 return_iplist[local_count].ss = name_ss;
2224 return_iplist[local_count].port = port;
2230 /* need to remove duplicates in the list if we have any
2231 explicit password servers */
2234 local_count = remove_duplicate_addrs2(return_iplist,
2238 /* For DC's we always prioritize IPv4 due to W2K3 not
2239 * supporting LDAP, KRB5 or CLDAP over IPv6. */
2241 if (local_count && return_iplist) {
2242 prioritize_ipv4_list(return_iplist, local_count);
2245 if ( DEBUGLEVEL >= 4 ) {
2246 DEBUG(4,("get_dc_list: returning %d ip addresses "
2247 "in an %sordered list\n",
2249 *ordered ? "":"un"));
2250 DEBUG(4,("get_dc_list: "));
2251 for ( i=0; i<local_count; i++ ) {
2252 char addr[INET6_ADDRSTRLEN];
2253 print_sockaddr(addr,
2255 &return_iplist[i].ss);
2256 DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
2261 *ip_list = return_iplist;
2262 *count = local_count;
2264 status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
2268 if (!NT_STATUS_IS_OK(status)) {
2269 SAFE_FREE(return_iplist);
2274 SAFE_FREE(auto_ip_list);
2279 /*********************************************************************
2280 Small wrapper function to get the DC list and sort it if neccessary.
2281 *********************************************************************/
2283 NTSTATUS get_sorted_dc_list( const char *domain,
2284 const char *sitename,
2285 struct ip_service **ip_list,
2289 bool ordered = false;
2291 enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
2296 DEBUG(8,("get_sorted_dc_list: attempting lookup "
2297 "for name %s (sitename %s) using [%s]\n",
2299 sitename ? sitename : "NULL",
2300 (ads_only ? "ads" : lp_name_resolve_order())));
2303 lookup_type = DC_ADS_ONLY;
2306 status = get_dc_list(domain, sitename, ip_list,
2307 count, lookup_type, &ordered);
2308 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_LOGON_SERVERS)
2310 DEBUG(3,("get_sorted_dc_list: no server for name %s available"
2311 " in site %s, fallback to all servers\n",
2313 status = get_dc_list(domain, NULL, ip_list,
2314 count, lookup_type, &ordered);
2317 if (!NT_STATUS_IS_OK(status)) {
2318 SAFE_FREE(*ip_list);
2323 /* only sort if we don't already have an ordered list */
2325 sort_service_list(*ip_list, *count);
2328 return NT_STATUS_OK;
2331 /*********************************************************************
2332 Get the KDC list - re-use all the logic in get_dc_list.
2333 *********************************************************************/
2335 NTSTATUS get_kdc_list( const char *realm,
2336 const char *sitename,
2337 struct ip_service **ip_list,
2346 status = get_dc_list(realm, sitename, ip_list,
2347 count, DC_KDC_ONLY, &ordered);
2349 if (!NT_STATUS_IS_OK(status)) {
2350 SAFE_FREE(*ip_list);
2355 /* only sort if we don't already have an ordered list */
2357 sort_service_list(*ip_list, *count);
2360 return NT_STATUS_OK;