2 Unix SMB/CIFS implementation.
4 Copyright (C) Andrew Tridgell 1994-1998
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 /* nmbd.c sets this to True. */
25 BOOL global_in_nmbd = False;
28 /****************************
29 * SERVER AFFINITY ROUTINES *
30 ****************************/
32 /* Server affinity is the concept of preferring the last domain
33 controller with whom you had a successful conversation */
35 /****************************************************************************
36 ****************************************************************************/
37 #define SAFKEY_FMT "SAF/DOMAIN/%s"
40 static char *saf_key(const char *domain)
44 asprintf( &keystr, SAFKEY_FMT, strupper_static(domain) );
49 /****************************************************************************
50 ****************************************************************************/
52 BOOL saf_store( const char *domain, const char *servername )
58 if ( !domain || !servername ) {
59 DEBUG(2,("saf_store: Refusing to store empty domain or servername!\n"));
63 if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
64 DEBUG(0,("saf_store: refusing to store 0 length domain or servername!\n"));
68 if ( !gencache_init() )
71 key = saf_key( domain );
72 expire = time( NULL ) + SAF_TTL;
75 DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
76 domain, servername, (unsigned int)expire ));
78 ret = gencache_set( key, servername, expire );
85 BOOL saf_delete( const char *domain, const char *servername )
90 if ( !domain || !servername ) {
91 DEBUG(2,("saf_delete: Refusing to store empty domain or servername!\n"));
95 if ( !gencache_init() )
98 key = saf_key(domain);
99 ret = gencache_del(key);
102 DEBUG(10,("saf_delete: domain = [%s], server = [%s]\n",
103 domain, servername));
109 /****************************************************************************
110 ****************************************************************************/
112 char *saf_fetch( const char *domain )
119 if ( !domain || strlen(domain) == 0) {
120 DEBUG(2,("saf_fetch: Empty domain name!\n"));
124 if ( !gencache_init() )
127 key = saf_key( domain );
129 ret = gencache_get( key, &server, &timeout );
134 DEBUG(5,("saf_fetch: failed to find server for \"%s\" domain\n", domain ));
136 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
143 /****************************************************************************
144 Generate a random trn_id.
145 ****************************************************************************/
147 static int generate_trn_id(void)
152 sys_srandom(sys_getpid());
155 trn_id = sys_random();
157 return trn_id % (unsigned)0x7FFF;
160 /****************************************************************************
161 Parse a node status response into an array of structures.
162 ****************************************************************************/
164 static NODE_STATUS_STRUCT *parse_node_status(char *p, int *num_names, struct node_status_extra *extra)
166 NODE_STATUS_STRUCT *ret;
169 *num_names = CVAL(p,0);
174 ret = SMB_MALLOC_ARRAY(NODE_STATUS_STRUCT,*num_names);
179 for (i=0;i< *num_names;i++) {
180 StrnCpy(ret[i].name,p,15);
181 trim_char(ret[i].name,'\0',' ');
182 ret[i].type = CVAL(p,15);
183 ret[i].flags = p[16];
185 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
186 ret[i].type, ret[i].flags));
189 * Also, pick up the MAC address ...
192 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
198 /****************************************************************************
199 Do a NBT node status query on an open socket and return an array of
200 structures holding the returned names or NULL if the query failed.
201 **************************************************************************/
203 NODE_STATUS_STRUCT *node_status_query(int fd,struct nmb_name *name,
204 struct in_addr to_ip, int *num_names,
205 struct node_status_extra *extra)
209 int retry_time = 2000;
211 struct packet_struct p;
212 struct packet_struct *p2;
213 struct nmb_packet *nmb = &p.packet.nmb;
214 NODE_STATUS_STRUCT *ret;
218 nmb->header.name_trn_id = generate_trn_id();
219 nmb->header.opcode = 0;
220 nmb->header.response = False;
221 nmb->header.nm_flags.bcast = False;
222 nmb->header.nm_flags.recursion_available = False;
223 nmb->header.nm_flags.recursion_desired = False;
224 nmb->header.nm_flags.trunc = False;
225 nmb->header.nm_flags.authoritative = False;
226 nmb->header.rcode = 0;
227 nmb->header.qdcount = 1;
228 nmb->header.ancount = 0;
229 nmb->header.nscount = 0;
230 nmb->header.arcount = 0;
231 nmb->question.question_name = *name;
232 nmb->question.question_type = 0x21;
233 nmb->question.question_class = 0x1;
238 p.timestamp = time(NULL);
239 p.packet_type = NMB_PACKET;
243 if (!send_packet(&p))
249 struct timeval tval2;
250 GetTimeOfDay(&tval2);
251 if (TvalDiff(&tval,&tval2) > retry_time) {
254 if (!found && !send_packet(&p))
260 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
261 struct nmb_packet *nmb2 = &p2->packet.nmb;
262 debug_nmb_packet(p2);
264 if (nmb2->header.opcode != 0 ||
265 nmb2->header.nm_flags.bcast ||
266 nmb2->header.rcode ||
267 !nmb2->header.ancount ||
268 nmb2->answers->rr_type != 0x21) {
269 /* XXXX what do we do with this? could be a
270 redirect, but we'll discard it for the
276 ret = parse_node_status(&nmb2->answers->rdata[0], num_names, extra);
285 /****************************************************************************
286 Find the first type XX name in a node status reply - used for finding
287 a servers name given its IP. Return the matched name in *name.
288 **************************************************************************/
290 BOOL name_status_find(const char *q_name, int q_type, int type, struct in_addr to_ip, fstring name)
292 NODE_STATUS_STRUCT *status = NULL;
293 struct nmb_name nname;
298 if (lp_disable_netbios()) {
299 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n", q_name, q_type));
303 DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
304 q_type, inet_ntoa(to_ip)));
306 /* Check the cache first. */
308 if (namecache_status_fetch(q_name, q_type, type, to_ip, name))
311 sock = open_socket_in(SOCK_DGRAM, 0, 3, interpret_addr(lp_socket_address()), True);
315 /* W2K PDC's seem not to respond to '*'#0. JRA */
316 make_nmb_name(&nname, q_name, q_type);
317 status = node_status_query(sock, &nname, to_ip, &count, NULL);
322 for (i=0;i<count;i++) {
323 if (status[i].type == type)
329 pull_ascii_nstring(name, sizeof(fstring), status[i].name);
331 /* Store the result in the cache. */
332 /* but don't store an entry for 0x1c names here. Here we have
333 a single host and DOMAIN<0x1c> names should be a list of hosts */
335 if ( q_type != 0x1c )
336 namecache_status_store(q_name, q_type, type, to_ip, name);
343 DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
346 DEBUGADD(10, (", name %s ip address is %s", name, inet_ntoa(to_ip)));
354 comparison function used by sort_ip_list
357 static int ip_compare(struct in_addr *ip1, struct in_addr *ip2)
359 int max_bits1=0, max_bits2=0;
360 int num_interfaces = iface_count();
363 for (i=0;i<num_interfaces;i++) {
366 ip = *iface_n_bcast(i);
367 bits1 = matching_quad_bits((uchar *)&ip1->s_addr, (uchar *)&ip.s_addr);
368 bits2 = matching_quad_bits((uchar *)&ip2->s_addr, (uchar *)&ip.s_addr);
369 max_bits1 = MAX(bits1, max_bits1);
370 max_bits2 = MAX(bits2, max_bits2);
373 /* bias towards directly reachable IPs */
374 if (iface_local(*ip1)) {
377 if (iface_local(*ip2)) {
381 return max_bits2 - max_bits1;
384 /*******************************************************************
385 compare 2 ldap IPs by nearness to our interfaces - used in qsort
386 *******************************************************************/
388 static int ip_service_compare(struct ip_service *ip1, struct ip_service *ip2)
392 if ( (result = ip_compare(&ip1->ip, &ip2->ip)) != 0 )
395 if ( ip1->port > ip2->port )
398 if ( ip1->port < ip2->port )
405 sort an IP list so that names that are close to one of our interfaces
406 are at the top. This prevents the problem where a WINS server returns an IP that
407 is not reachable from our subnet as the first match
410 static void sort_ip_list(struct in_addr *iplist, int count)
416 qsort(iplist, count, sizeof(struct in_addr), QSORT_CAST ip_compare);
419 static void sort_ip_list2(struct ip_service *iplist, int count)
425 qsort(iplist, count, sizeof(struct ip_service), QSORT_CAST ip_service_compare);
428 /**********************************************************************
429 Remove any duplicate address/port pairs in the list
430 *********************************************************************/
432 static int remove_duplicate_addrs2( struct ip_service *iplist, int count )
436 DEBUG(10,("remove_duplicate_addrs2: looking for duplicate address/port pairs\n"));
438 /* one loop to remove duplicates */
439 for ( i=0; i<count; i++ ) {
440 if ( is_zero_ip(iplist[i].ip) )
443 for ( j=i+1; j<count; j++ ) {
444 if ( ip_service_equal(iplist[i], iplist[j]) )
445 zero_ip(&iplist[j].ip);
449 /* one loop to clean up any holes we left */
450 /* first ip should never be a zero_ip() */
451 for (i = 0; i<count; ) {
452 if ( is_zero_ip(iplist[i].ip) ) {
454 memmove(&iplist[i], &iplist[i+1], (count - i - 1)*sizeof(iplist[i]));
464 /****************************************************************************
465 Do a netbios name query to find someones IP.
466 Returns an array of IP addresses or NULL if none.
467 *count will be set to the number of addresses returned.
468 *timed_out is set if we failed by timing out
469 ****************************************************************************/
471 struct in_addr *name_query(int fd,const char *name,int name_type,
472 BOOL bcast,BOOL recurse,
473 struct in_addr to_ip, int *count, int *flags,
478 int retry_time = bcast?250:2000;
480 struct packet_struct p;
481 struct packet_struct *p2;
482 struct nmb_packet *nmb = &p.packet.nmb;
483 struct in_addr *ip_list = NULL;
485 if (lp_disable_netbios()) {
486 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n", name, name_type));
494 memset((char *)&p,'\0',sizeof(p));
498 nmb->header.name_trn_id = generate_trn_id();
499 nmb->header.opcode = 0;
500 nmb->header.response = False;
501 nmb->header.nm_flags.bcast = bcast;
502 nmb->header.nm_flags.recursion_available = False;
503 nmb->header.nm_flags.recursion_desired = recurse;
504 nmb->header.nm_flags.trunc = False;
505 nmb->header.nm_flags.authoritative = False;
506 nmb->header.rcode = 0;
507 nmb->header.qdcount = 1;
508 nmb->header.ancount = 0;
509 nmb->header.nscount = 0;
510 nmb->header.arcount = 0;
512 make_nmb_name(&nmb->question.question_name,name,name_type);
514 nmb->question.question_type = 0x20;
515 nmb->question.question_class = 0x1;
520 p.timestamp = time(NULL);
521 p.packet_type = NMB_PACKET;
525 if (!send_packet(&p))
531 struct timeval tval2;
533 GetTimeOfDay(&tval2);
534 if (TvalDiff(&tval,&tval2) > retry_time) {
537 if (!found && !send_packet(&p))
543 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
544 struct nmb_packet *nmb2 = &p2->packet.nmb;
545 debug_nmb_packet(p2);
547 /* If we get a Negative Name Query Response from a WINS
548 * server, we should report it and give up.
550 if( 0 == nmb2->header.opcode /* A query response */
551 && !(bcast) /* from a WINS server */
552 && nmb2->header.rcode /* Error returned */
555 if( DEBUGLVL( 3 ) ) {
556 /* Only executed if DEBUGLEVEL >= 3 */
557 dbgtext( "Negative name query response, rcode 0x%02x: ", nmb2->header.rcode );
558 switch( nmb2->header.rcode ) {
560 dbgtext( "Request was invalidly formatted.\n" );
563 dbgtext( "Problem with NBNS, cannot process name.\n");
566 dbgtext( "The name requested does not exist.\n" );
569 dbgtext( "Unsupported request error.\n" );
572 dbgtext( "Query refused error.\n" );
575 dbgtext( "Unrecognized error code.\n" );
583 if (nmb2->header.opcode != 0 ||
584 nmb2->header.nm_flags.bcast ||
585 nmb2->header.rcode ||
586 !nmb2->header.ancount) {
588 * XXXX what do we do with this? Could be a
589 * redirect, but we'll discard it for the
596 ip_list = SMB_REALLOC_ARRAY( ip_list, struct in_addr,
597 (*count) + nmb2->answers->rdlength/6 );
600 DEBUG(0,("name_query: Realloc failed.\n"));
605 DEBUG(2,("Got a positive name query response from %s ( ", inet_ntoa(p2->ip)));
606 for (i=0;i<nmb2->answers->rdlength/6;i++) {
607 putip((char *)&ip_list[(*count)],&nmb2->answers->rdata[2+i*6]);
608 DEBUGADD(2,("%s ",inet_ntoa(ip_list[(*count)])));
615 /* We add the flags back ... */
616 if (nmb2->header.response)
617 (*flags) |= NM_FLAGS_RS;
618 if (nmb2->header.nm_flags.authoritative)
619 (*flags) |= NM_FLAGS_AA;
620 if (nmb2->header.nm_flags.trunc)
621 (*flags) |= NM_FLAGS_TC;
622 if (nmb2->header.nm_flags.recursion_desired)
623 (*flags) |= NM_FLAGS_RD;
624 if (nmb2->header.nm_flags.recursion_available)
625 (*flags) |= NM_FLAGS_RA;
626 if (nmb2->header.nm_flags.bcast)
627 (*flags) |= NM_FLAGS_B;
630 * If we're doing a unicast lookup we only
631 * expect one reply. Don't wait the full 2
632 * seconds if we got one. JRA.
639 /* only set timed_out if we didn't fund what we where looking for*/
641 if ( !found && timed_out ) {
645 /* sort the ip list so we choose close servers first if possible */
646 sort_ip_list(ip_list, *count);
651 /********************************************************
652 Start parsing the lmhosts file.
653 *********************************************************/
655 XFILE *startlmhosts(char *fname)
657 XFILE *fp = x_fopen(fname,O_RDONLY, 0);
659 DEBUG(4,("startlmhosts: Can't open lmhosts file %s. Error was %s\n",
660 fname, strerror(errno)));
666 /********************************************************
667 Parse the next line in the lmhosts file.
668 *********************************************************/
670 BOOL getlmhostsent( XFILE *fp, pstring name, int *name_type, struct in_addr *ipaddr)
674 while(!x_feof(fp) && !x_ferror(fp)) {
675 pstring ip,flags,extra;
682 if (!fgets_slash(line,sizeof(pstring),fp)) {
696 if (next_token(&ptr,ip ,NULL,sizeof(ip)))
698 if (next_token(&ptr,name ,NULL, sizeof(pstring)))
700 if (next_token(&ptr,flags,NULL, sizeof(flags)))
702 if (next_token(&ptr,extra,NULL, sizeof(extra)))
708 if (count > 0 && count < 2) {
709 DEBUG(0,("getlmhostsent: Ill formed hosts line [%s]\n",line));
714 DEBUG(0,("getlmhostsent: too many columns in lmhosts file (obsolete syntax)\n"));
718 DEBUG(4, ("getlmhostsent: lmhost entry: %s %s %s\n", ip, name, flags));
720 if (strchr_m(flags,'G') || strchr_m(flags,'S')) {
721 DEBUG(0,("getlmhostsent: group flag in lmhosts ignored (obsolete)\n"));
725 *ipaddr = *interpret_addr2(ip);
727 /* Extra feature. If the name ends in '#XX', where XX is a hex number,
728 then only add that name type. */
729 if((ptr1 = strchr_m(name, '#')) != NULL) {
733 *name_type = (int)strtol(ptr1, &endptr, 16);
734 if(!*ptr1 || (endptr == ptr1)) {
735 DEBUG(0,("getlmhostsent: invalid name %s containing '#'.\n", name));
739 *(--ptr1) = '\0'; /* Truncate at the '#' */
748 /********************************************************
749 Finish parsing the lmhosts file.
750 *********************************************************/
752 void endlmhosts(XFILE *fp)
757 /********************************************************
758 convert an array if struct in_addrs to struct ip_service
759 return False on failure. Port is set to PORT_NONE;
760 *********************************************************/
762 static BOOL convert_ip2service( struct ip_service **return_iplist, struct in_addr *ip_list, int count )
766 if ( count==0 || !ip_list )
769 /* copy the ip address; port will be PORT_NONE */
770 if ( (*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
771 DEBUG(0,("convert_ip2service: malloc failed for %d enetries!\n", count ));
775 for ( i=0; i<count; i++ ) {
776 (*return_iplist)[i].ip = ip_list[i];
777 (*return_iplist)[i].port = PORT_NONE;
782 /********************************************************
783 Resolve via "bcast" method.
784 *********************************************************/
786 BOOL name_resolve_bcast(const char *name, int name_type,
787 struct ip_service **return_iplist, int *return_count)
790 int num_interfaces = iface_count();
791 struct in_addr *ip_list;
794 if (lp_disable_netbios()) {
795 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n", name, name_type));
799 *return_iplist = NULL;
803 * "bcast" means do a broadcast lookup on all the local interfaces.
806 DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup for name %s<0x%x>\n", name, name_type));
808 sock = open_socket_in( SOCK_DGRAM, 0, 3,
809 interpret_addr(lp_socket_address()), True );
811 if (sock == -1) return False;
813 set_socket_options(sock,"SO_BROADCAST");
815 * Lookup the name on all the interfaces, return on
816 * the first successful match.
818 for( i = num_interfaces-1; i >= 0; i--) {
819 struct in_addr sendto_ip;
821 /* Done this way to fix compiler error on IRIX 5.x */
822 sendto_ip = *iface_n_bcast(i);
823 ip_list = name_query(sock, name, name_type, True,
824 True, sendto_ip, return_count, &flags, NULL);
829 /* failed - no response */
836 if ( !convert_ip2service(return_iplist, ip_list, *return_count) )
839 SAFE_FREE( ip_list );
844 /********************************************************
845 Resolve via "wins" method.
846 *********************************************************/
848 BOOL resolve_wins(const char *name, int name_type,
849 struct ip_service **return_iplist, int *return_count)
853 struct in_addr src_ip, *ip_list = NULL;
856 if (lp_disable_netbios()) {
857 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n", name, name_type));
861 *return_iplist = NULL;
864 DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n", name, name_type));
866 if (wins_srv_count() < 1) {
867 DEBUG(3,("resolve_wins: WINS server resolution selected and no WINS servers listed.\n"));
871 /* we try a lookup on each of the WINS tags in turn */
872 wins_tags = wins_srv_tags();
875 /* huh? no tags?? give up in disgust */
879 /* the address we will be sending from */
880 src_ip = *interpret_addr2(lp_socket_address());
882 /* in the worst case we will try every wins server with every
884 for (t=0; wins_tags && wins_tags[t]; t++) {
885 int srv_count = wins_srv_count_tag(wins_tags[t]);
886 for (i=0; i<srv_count; i++) {
887 struct in_addr wins_ip;
891 wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
893 if (global_in_nmbd && ismyip(wins_ip)) {
894 /* yikes! we'll loop forever */
898 /* skip any that have been unresponsive lately */
899 if (wins_srv_is_dead(wins_ip, src_ip)) {
903 DEBUG(3,("resolve_wins: using WINS server %s and tag '%s'\n", inet_ntoa(wins_ip), wins_tags[t]));
905 sock = open_socket_in(SOCK_DGRAM, 0, 3, src_ip.s_addr, True);
910 ip_list = name_query(sock,name,name_type, False,
911 True, wins_ip, return_count, &flags,
914 /* exit loop if we got a list of addresses */
922 /* Timed out wating for WINS server to respond. Mark it dead. */
923 wins_srv_died(wins_ip, src_ip);
925 /* The name definately isn't in this
926 group of WINS servers. goto the next group */
932 wins_srv_tags_free(wins_tags);
937 if ( !convert_ip2service( return_iplist, ip_list, *return_count ) )
940 SAFE_FREE( ip_list );
941 wins_srv_tags_free(wins_tags);
947 /********************************************************
948 Resolve via "lmhosts" method.
949 *********************************************************/
951 static BOOL resolve_lmhosts(const char *name, int name_type,
952 struct ip_service **return_iplist, int *return_count)
955 * "lmhosts" means parse the local lmhosts file.
961 struct in_addr return_ip;
964 *return_iplist = NULL;
967 DEBUG(3,("resolve_lmhosts: Attempting lmhosts lookup for name %s<0x%x>\n", name, name_type));
969 fp = startlmhosts(dyn_LMHOSTSFILE);
974 while (getlmhostsent(fp, lmhost_name, &name_type2, &return_ip))
977 if (!strequal(name, lmhost_name))
980 if ((name_type2 != -1) && (name_type != name_type2))
983 *return_iplist = SMB_REALLOC_ARRAY((*return_iplist), struct ip_service,
986 if ((*return_iplist) == NULL) {
988 DEBUG(3,("resolve_lmhosts: malloc fail !\n"));
992 (*return_iplist)[*return_count].ip = return_ip;
993 (*return_iplist)[*return_count].port = PORT_NONE;
996 /* we found something */
999 /* Multiple names only for DC lookup */
1000 if (name_type != 0x1c)
1010 /********************************************************
1011 Resolve via "hosts" method.
1012 *********************************************************/
1014 static BOOL resolve_hosts(const char *name, int name_type,
1015 struct ip_service **return_iplist, int *return_count)
1018 * "host" means do a localhost, or dns lookup.
1022 if ( name_type != 0x20 && name_type != 0x0) {
1023 DEBUG(5, ("resolve_hosts: not appropriate for name type <0x%x>\n", name_type));
1027 *return_iplist = NULL;
1030 DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n", name, name_type));
1032 if (((hp = sys_gethostbyname(name)) != NULL) && (hp->h_addr != NULL)) {
1033 struct in_addr return_ip;
1034 putip((char *)&return_ip,(char *)hp->h_addr);
1035 *return_iplist = SMB_MALLOC_P(struct ip_service);
1036 if(*return_iplist == NULL) {
1037 DEBUG(3,("resolve_hosts: malloc fail !\n"));
1040 (*return_iplist)->ip = return_ip;
1041 (*return_iplist)->port = PORT_NONE;
1048 /********************************************************
1049 Resolve via "ADS" method.
1050 *********************************************************/
1052 static BOOL resolve_ads(const char *name, int name_type,
1053 struct ip_service **return_iplist, int *return_count)
1058 struct dns_rr_srv *dcs = NULL;
1062 if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE))
1065 DEBUG(5,("resolve_ads: Attempting to resolve DC's for %s using DNS\n",
1068 if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1069 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1073 if (name_type == KDC_NAME_TYPE) {
1074 status = ads_dns_query_kdcs(ctx, name, &dcs, &numdcs);
1076 status = ads_dns_query_dcs(ctx, name, &dcs, &numdcs);
1078 if ( !NT_STATUS_IS_OK( status ) ) {
1079 talloc_destroy(ctx);
1083 for (i=0;i<numdcs;i++) {
1084 numaddrs += MAX(dcs[i].num_ips,1);
1087 if ( (*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) == NULL ) {
1088 DEBUG(0,("resolve_ads: malloc failed for %d entries\n", numaddrs ));
1089 talloc_destroy(ctx);
1093 /* now unroll the list of IP addresses */
1098 while ( i < numdcs && (*return_count<numaddrs) ) {
1099 struct ip_service *r = &(*return_iplist)[*return_count];
1101 r->port = dcs[i].port;
1103 /* If we don't have an IP list for a name, lookup it up */
1105 if ( !dcs[i].ips ) {
1106 r->ip = *interpret_addr2(dcs[i].hostname);
1110 /* use the IP addresses from the SRV sresponse */
1112 if ( j >= dcs[i].num_ips ) {
1118 r->ip = dcs[i].ips[j];
1122 /* make sure it is a valid IP. I considered checking the negative
1123 connection cache, but this is the wrong place for it. Maybe only
1124 as a hac. After think about it, if all of the IP addresses retuend
1125 from DNS are dead, what hope does a netbios name lookup have?
1126 The standard reason for falling back to netbios lookups is that
1127 our DNS server doesn't know anything about the DC's -- jerry */
1129 if ( ! is_zero_ip(r->ip) )
1133 talloc_destroy(ctx);
1137 /*******************************************************************
1138 Internal interface to resolve a name into an IP address.
1139 Use this function if the string is either an IP address, DNS
1140 or host name or NetBIOS name. This uses the name switch in the
1141 smb.conf to determine the order of name resolution.
1143 Added support for ip addr/port to support ADS ldap servers.
1144 the only place we currently care about the port is in the
1145 resolve_hosts() when looking up DC's via SRV RR entries in DNS
1146 **********************************************************************/
1148 BOOL internal_resolve_name(const char *name, int name_type,
1149 struct ip_service **return_iplist,
1150 int *return_count, const char *resolve_order)
1152 pstring name_resolve_list;
1155 BOOL allones = (strcmp(name,"255.255.255.255") == 0);
1156 BOOL allzeros = (strcmp(name,"0.0.0.0") == 0);
1157 BOOL is_address = is_ipaddress(name);
1158 BOOL result = False;
1161 *return_iplist = NULL;
1164 DEBUG(10, ("internal_resolve_name: looking up %s#%x\n", name, name_type));
1166 if (allzeros || allones || is_address) {
1168 if ( (*return_iplist = SMB_MALLOC_P(struct ip_service)) == NULL ) {
1169 DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1174 /* ignore the port here */
1175 (*return_iplist)->port = PORT_NONE;
1177 /* if it's in the form of an IP address then get the lib to interpret it */
1178 if (((*return_iplist)->ip.s_addr = inet_addr(name)) == 0xFFFFFFFF ){
1179 DEBUG(1,("internal_resolve_name: inet_addr failed on %s\n", name));
1180 SAFE_FREE(*return_iplist);
1184 (*return_iplist)->ip.s_addr = allones ? 0xFFFFFFFF : 0;
1190 /* Check name cache */
1192 if (namecache_fetch(name, name_type, return_iplist, return_count)) {
1193 /* This could be a negative response */
1194 return (*return_count > 0);
1197 /* set the name resolution order */
1199 if ( strcmp( resolve_order, "NULL") == 0 ) {
1200 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
1204 if ( !resolve_order ) {
1205 pstrcpy(name_resolve_list, lp_name_resolve_order());
1207 pstrcpy(name_resolve_list, resolve_order);
1210 if ( !name_resolve_list[0] ) {
1213 ptr = name_resolve_list;
1216 /* iterate through the name resolution backends */
1218 while (next_token(&ptr, tok, LIST_SEP, sizeof(tok))) {
1219 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
1220 if (resolve_hosts(name, name_type, return_iplist, return_count)) {
1224 } else if(strequal( tok, "kdc")) {
1225 /* deal with KDC_NAME_TYPE names here. This will result in a
1226 SRV record lookup */
1227 if (resolve_ads(name, KDC_NAME_TYPE, return_iplist, return_count)) {
1229 /* Ensure we don't namecache this with the KDC port. */
1230 name_type = KDC_NAME_TYPE;
1233 } else if(strequal( tok, "ads")) {
1234 /* deal with 0x1c names here. This will result in a
1235 SRV record lookup */
1236 if (resolve_ads(name, name_type, return_iplist, return_count)) {
1240 } else if(strequal( tok, "lmhosts")) {
1241 if (resolve_lmhosts(name, name_type, return_iplist, return_count)) {
1245 } else if(strequal( tok, "wins")) {
1246 /* don't resolve 1D via WINS */
1247 if (name_type != 0x1D && resolve_wins(name, name_type, return_iplist, return_count)) {
1251 } else if(strequal( tok, "bcast")) {
1252 if (name_resolve_bcast(name, name_type, return_iplist, return_count)) {
1257 DEBUG(0,("resolve_name: unknown name switch type %s\n", tok));
1261 /* All of the resolve_* functions above have returned false. */
1263 SAFE_FREE(*return_iplist);
1270 /* Remove duplicate entries. Some queries, notably #1c (domain
1271 controllers) return the PDC in iplist[0] and then all domain
1272 controllers including the PDC in iplist[1..n]. Iterating over
1273 the iplist when the PDC is down will cause two sets of timeouts. */
1275 if ( *return_count ) {
1276 *return_count = remove_duplicate_addrs2( *return_iplist, *return_count );
1279 /* Save in name cache */
1280 if ( DEBUGLEVEL >= 100 ) {
1281 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++)
1282 DEBUG(100, ("Storing name %s of type %d (%s:%d)\n", name,
1283 name_type, inet_ntoa((*return_iplist)[i].ip), (*return_iplist)[i].port));
1286 namecache_store(name, name_type, *return_count, *return_iplist);
1288 /* Display some debugging info */
1290 if ( DEBUGLEVEL >= 10 ) {
1291 DEBUG(10, ("internal_resolve_name: returning %d addresses: ", *return_count));
1293 for (i = 0; i < *return_count; i++) {
1294 DEBUGADD(10, ("%s:%d ", inet_ntoa((*return_iplist)[i].ip), (*return_iplist)[i].port));
1302 /********************************************************
1303 Internal interface to resolve a name into one IP address.
1304 Use this function if the string is either an IP address, DNS
1305 or host name or NetBIOS name. This uses the name switch in the
1306 smb.conf to determine the order of name resolution.
1307 *********************************************************/
1309 BOOL resolve_name(const char *name, struct in_addr *return_ip, int name_type)
1311 struct ip_service *ip_list = NULL;
1314 if (is_ipaddress(name)) {
1315 *return_ip = *interpret_addr2(name);
1319 if (internal_resolve_name(name, name_type, &ip_list, &count, lp_name_resolve_order())) {
1322 /* only return valid addresses for TCP connections */
1323 for (i=0; i<count; i++) {
1324 char *ip_str = inet_ntoa(ip_list[i].ip);
1326 strcmp(ip_str, "255.255.255.255") != 0 &&
1327 strcmp(ip_str, "0.0.0.0") != 0)
1329 *return_ip = ip_list[i].ip;
1340 /********************************************************
1341 Find the IP address of the master browser or DMB for a workgroup.
1342 *********************************************************/
1344 BOOL find_master_ip(const char *group, struct in_addr *master_ip)
1346 struct ip_service *ip_list = NULL;
1349 if (lp_disable_netbios()) {
1350 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
1354 if (internal_resolve_name(group, 0x1D, &ip_list, &count, lp_name_resolve_order())) {
1355 *master_ip = ip_list[0].ip;
1359 if(internal_resolve_name(group, 0x1B, &ip_list, &count, lp_name_resolve_order())) {
1360 *master_ip = ip_list[0].ip;
1369 /********************************************************
1370 Get the IP address list of the primary domain controller
1372 *********************************************************/
1374 BOOL get_pdc_ip(const char *domain, struct in_addr *ip)
1376 struct ip_service *ip_list;
1379 /* Look up #1B name */
1381 if (!internal_resolve_name(domain, 0x1b, &ip_list, &count, lp_name_resolve_order())) {
1385 /* if we get more than 1 IP back we have to assume it is a
1386 multi-homed PDC and not a mess up */
1389 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
1390 sort_ip_list2( ip_list, count );
1393 *ip = ip_list[0].ip;
1400 /* Private enum type for lookups. */
1402 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
1404 /********************************************************
1405 Get the IP address list of the domain controllers for
1407 *********************************************************/
1409 static NTSTATUS get_dc_list(const char *domain, struct ip_service **ip_list,
1410 int *count, enum dc_lookup_type lookup_type, int *ordered)
1412 fstring resolve_order;
1413 char *saf_servername;
1419 int num_addresses = 0;
1420 int local_count, i, j;
1421 struct ip_service *return_iplist = NULL;
1422 struct ip_service *auto_ip_list = NULL;
1423 BOOL done_auto_lookup = False;
1428 /* if we are restricted to solely using DNS for looking
1429 up a domain controller, make sure that host lookups
1430 are enabled for the 'name resolve order'. If host lookups
1431 are disabled and ads_only is True, then set the string to
1434 fstrcpy( resolve_order, lp_name_resolve_order() );
1435 strlower_m( resolve_order );
1436 if ( lookup_type == DC_ADS_ONLY) {
1437 if ( strstr( resolve_order, "host" ) ) {
1438 fstrcpy( resolve_order, "ads" );
1440 /* DNS SRV lookups used by the ads resolver
1441 are already sorted by priority and weight */
1444 fstrcpy( resolve_order, "NULL" );
1446 } else if (lookup_type == DC_KDC_ONLY) {
1447 /* DNS SRV lookups used by the ads/kdc resolver
1448 are already sorted by priority and weight */
1450 fstrcpy( resolve_order, "kdc" );
1453 /* fetch the server we have affinity for. Add the
1454 'password server' list to a search for our domain controllers */
1456 saf_servername = saf_fetch( domain );
1458 if ( strequal(domain, lp_workgroup()) || strequal(domain, lp_realm()) ) {
1459 pstr_sprintf( pserver, "%s, %s",
1460 saf_servername ? saf_servername : "",
1461 lp_passwordserver() );
1463 pstr_sprintf( pserver, "%s, *",
1464 saf_servername ? saf_servername : "" );
1467 SAFE_FREE( saf_servername );
1469 /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
1472 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
1473 /* TODO: change return type of internal_resolve_name to
1475 if (internal_resolve_name(domain, 0x1C, ip_list, count,
1477 return NT_STATUS_OK;
1479 return NT_STATUS_NO_LOGON_SERVERS;
1483 DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
1486 * if '*' appears in the "password server" list then add
1487 * an auto lookup to the list of manually configured
1488 * DC's. If any DC is listed by name, then the list should be
1489 * considered to be ordered
1493 while (next_token(&p,name,LIST_SEP,sizeof(name))) {
1494 if (strequal(name, "*")) {
1495 if (internal_resolve_name(domain, 0x1C, &auto_ip_list,
1496 &auto_count, resolve_order))
1497 num_addresses += auto_count;
1498 done_auto_lookup = True;
1499 DEBUG(8,("Adding %d DC's from auto lookup\n", auto_count));
1505 /* if we have no addresses and haven't done the auto lookup, then
1506 just return the list of DC's. Or maybe we just failed. */
1508 if ( (num_addresses == 0) ) {
1509 if ( !done_auto_lookup ) {
1510 if (internal_resolve_name(domain, 0x1C, ip_list, count, resolve_order)) {
1511 return NT_STATUS_OK;
1513 return NT_STATUS_NO_LOGON_SERVERS;
1516 DEBUG(4,("get_dc_list: no servers found\n"));
1517 return NT_STATUS_NO_LOGON_SERVERS;
1521 if ( (return_iplist = SMB_MALLOC_ARRAY(struct ip_service, num_addresses)) == NULL ) {
1522 DEBUG(3,("get_dc_list: malloc fail !\n"));
1523 return NT_STATUS_NO_MEMORY;
1529 /* fill in the return list now with real IP's */
1531 while ( (local_count<num_addresses) && next_token(&p,name,LIST_SEP,sizeof(name)) ) {
1532 struct in_addr name_ip;
1534 /* copy any addersses from the auto lookup */
1536 if ( strequal(name, "*") ) {
1537 for ( j=0; j<auto_count; j++ ) {
1538 /* Check for and don't copy any known bad DC IP's. */
1539 if(!NT_STATUS_IS_OK(check_negative_conn_cache(domain,
1540 inet_ntoa(auto_ip_list[j].ip)))) {
1541 DEBUG(5,("get_dc_list: negative entry %s removed from DC list\n",
1542 inet_ntoa(auto_ip_list[j].ip) ));
1545 return_iplist[local_count].ip = auto_ip_list[j].ip;
1546 return_iplist[local_count].port = auto_ip_list[j].port;
1553 /* added support for address:port syntax for ads (not that I think
1554 anyone will ever run the LDAP server in an AD domain on something
1555 other than port 389 */
1557 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
1558 if ( (port_str=strchr(name, ':')) != NULL ) {
1561 port = atoi( port_str );
1564 /* explicit lookup; resolve_name() will handle names & IP addresses */
1565 if ( resolve_name( name, &name_ip, 0x20 ) ) {
1567 /* Check for and don't copy any known bad DC IP's. */
1568 if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain, inet_ntoa(name_ip))) ) {
1569 DEBUG(5,("get_dc_list: negative entry %s removed from DC list\n",name ));
1573 return_iplist[local_count].ip = name_ip;
1574 return_iplist[local_count].port = port;
1580 SAFE_FREE(auto_ip_list);
1582 /* need to remove duplicates in the list if we have any
1583 explicit password servers */
1585 if ( local_count ) {
1586 local_count = remove_duplicate_addrs2( return_iplist, local_count );
1589 if ( DEBUGLEVEL >= 4 ) {
1590 DEBUG(4,("get_dc_list: returning %d ip addresses in an %sordered list\n", local_count,
1591 *ordered ? "":"un"));
1592 DEBUG(4,("get_dc_list: "));
1593 for ( i=0; i<local_count; i++ )
1594 DEBUGADD(4,("%s:%d ", inet_ntoa(return_iplist[i].ip), return_iplist[i].port ));
1598 *ip_list = return_iplist;
1599 *count = local_count;
1601 return ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
1604 /*********************************************************************
1605 Small wrapper function to get the DC list and sort it if neccessary.
1606 *********************************************************************/
1608 NTSTATUS get_sorted_dc_list( const char *domain, struct ip_service **ip_list, int *count, BOOL ads_only )
1612 enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
1614 DEBUG(8,("get_sorted_dc_list: attempting lookup using [%s]\n",
1615 (ads_only ? "ads" : lp_name_resolve_order())));
1618 lookup_type = DC_ADS_ONLY;
1621 status = get_dc_list(domain, ip_list, count, lookup_type, &ordered);
1622 if (!NT_STATUS_IS_OK(status)) {
1626 /* only sort if we don't already have an ordered list */
1628 sort_ip_list2( *ip_list, *count );
1631 return NT_STATUS_OK;
1634 /*********************************************************************
1635 Get the KDC list - re-use all the logic in get_dc_list.
1636 *********************************************************************/
1638 NTSTATUS get_kdc_list( const char *realm, struct ip_service **ip_list, int *count)
1646 status = get_dc_list(realm, ip_list, count, DC_KDC_ONLY, &ordered);
1648 if (!NT_STATUS_IS_OK(status)) {
1652 /* only sort if we don't already have an ordered list */
1654 sort_ip_list2( *ip_list, *count );
1657 return NT_STATUS_OK;