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 ( !gencache_init() )
66 key = saf_key( domain );
67 expire = time( NULL ) + SAF_TTL;
70 DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
71 domain, servername, (unsigned int)expire ));
73 ret = gencache_set( key, servername, expire );
80 BOOL saf_delete( const char *domain, const char *servername )
85 if ( !domain || !servername ) {
86 DEBUG(2,("saf_delete: Refusing to store empty domain or servername!\n"));
90 if ( !gencache_init() )
93 key = saf_key(domain);
94 ret = gencache_del(key);
97 DEBUG(10,("saf_delete: domain = [%s], server = [%s]\n",
104 /****************************************************************************
105 ****************************************************************************/
107 char *saf_fetch( const char *domain )
115 DEBUG(2,("saf_fetch: Empty domain name!\n"));
119 if ( !gencache_init() )
122 key = saf_key( domain );
124 ret = gencache_get( key, &server, &timeout );
129 DEBUG(5,("saf_fetch: failed to find server for \"%s\" domain\n", domain ));
131 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
138 /****************************************************************************
139 Generate a random trn_id.
140 ****************************************************************************/
142 static int generate_trn_id(void)
147 sys_srandom(sys_getpid());
150 trn_id = sys_random();
152 return trn_id % (unsigned)0x7FFF;
155 /****************************************************************************
156 Parse a node status response into an array of structures.
157 ****************************************************************************/
159 static NODE_STATUS_STRUCT *parse_node_status(char *p, int *num_names, struct node_status_extra *extra)
161 NODE_STATUS_STRUCT *ret;
164 *num_names = CVAL(p,0);
169 ret = SMB_MALLOC_ARRAY(NODE_STATUS_STRUCT,*num_names);
174 for (i=0;i< *num_names;i++) {
175 StrnCpy(ret[i].name,p,15);
176 trim_char(ret[i].name,'\0',' ');
177 ret[i].type = CVAL(p,15);
178 ret[i].flags = p[16];
180 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
181 ret[i].type, ret[i].flags));
184 * Also, pick up the MAC address ...
187 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
193 /****************************************************************************
194 Do a NBT node status query on an open socket and return an array of
195 structures holding the returned names or NULL if the query failed.
196 **************************************************************************/
198 NODE_STATUS_STRUCT *node_status_query(int fd,struct nmb_name *name,
199 struct in_addr to_ip, int *num_names,
200 struct node_status_extra *extra)
204 int retry_time = 2000;
206 struct packet_struct p;
207 struct packet_struct *p2;
208 struct nmb_packet *nmb = &p.packet.nmb;
209 NODE_STATUS_STRUCT *ret;
213 nmb->header.name_trn_id = generate_trn_id();
214 nmb->header.opcode = 0;
215 nmb->header.response = False;
216 nmb->header.nm_flags.bcast = False;
217 nmb->header.nm_flags.recursion_available = False;
218 nmb->header.nm_flags.recursion_desired = False;
219 nmb->header.nm_flags.trunc = False;
220 nmb->header.nm_flags.authoritative = False;
221 nmb->header.rcode = 0;
222 nmb->header.qdcount = 1;
223 nmb->header.ancount = 0;
224 nmb->header.nscount = 0;
225 nmb->header.arcount = 0;
226 nmb->question.question_name = *name;
227 nmb->question.question_type = 0x21;
228 nmb->question.question_class = 0x1;
233 p.timestamp = time(NULL);
234 p.packet_type = NMB_PACKET;
238 if (!send_packet(&p))
244 struct timeval tval2;
245 GetTimeOfDay(&tval2);
246 if (TvalDiff(&tval,&tval2) > retry_time) {
249 if (!found && !send_packet(&p))
255 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
256 struct nmb_packet *nmb2 = &p2->packet.nmb;
257 debug_nmb_packet(p2);
259 if (nmb2->header.opcode != 0 ||
260 nmb2->header.nm_flags.bcast ||
261 nmb2->header.rcode ||
262 !nmb2->header.ancount ||
263 nmb2->answers->rr_type != 0x21) {
264 /* XXXX what do we do with this? could be a
265 redirect, but we'll discard it for the
271 ret = parse_node_status(&nmb2->answers->rdata[0], num_names, extra);
280 /****************************************************************************
281 Find the first type XX name in a node status reply - used for finding
282 a servers name given its IP. Return the matched name in *name.
283 **************************************************************************/
285 BOOL name_status_find(const char *q_name, int q_type, int type, struct in_addr to_ip, fstring name)
287 NODE_STATUS_STRUCT *status = NULL;
288 struct nmb_name nname;
293 if (lp_disable_netbios()) {
294 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n", q_name, q_type));
298 DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
299 q_type, inet_ntoa(to_ip)));
301 /* Check the cache first. */
303 if (namecache_status_fetch(q_name, q_type, type, to_ip, name))
306 sock = open_socket_in(SOCK_DGRAM, 0, 3, interpret_addr(lp_socket_address()), True);
310 /* W2K PDC's seem not to respond to '*'#0. JRA */
311 make_nmb_name(&nname, q_name, q_type);
312 status = node_status_query(sock, &nname, to_ip, &count, NULL);
317 for (i=0;i<count;i++) {
318 if (status[i].type == type)
324 pull_ascii_nstring(name, sizeof(fstring), status[i].name);
326 /* Store the result in the cache. */
327 /* but don't store an entry for 0x1c names here. Here we have
328 a single host and DOMAIN<0x1c> names should be a list of hosts */
330 if ( q_type != 0x1c )
331 namecache_status_store(q_name, q_type, type, to_ip, name);
338 DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
341 DEBUGADD(10, (", name %s ip address is %s", name, inet_ntoa(to_ip)));
349 comparison function used by sort_ip_list
352 static int ip_compare(struct in_addr *ip1, struct in_addr *ip2)
354 int max_bits1=0, max_bits2=0;
355 int num_interfaces = iface_count();
358 for (i=0;i<num_interfaces;i++) {
361 ip = *iface_n_bcast(i);
362 bits1 = matching_quad_bits((uchar *)&ip1->s_addr, (uchar *)&ip.s_addr);
363 bits2 = matching_quad_bits((uchar *)&ip2->s_addr, (uchar *)&ip.s_addr);
364 max_bits1 = MAX(bits1, max_bits1);
365 max_bits2 = MAX(bits2, max_bits2);
368 /* bias towards directly reachable IPs */
369 if (iface_local(*ip1)) {
372 if (iface_local(*ip2)) {
376 return max_bits2 - max_bits1;
379 /*******************************************************************
380 compare 2 ldap IPs by nearness to our interfaces - used in qsort
381 *******************************************************************/
383 static int ip_service_compare(struct ip_service *ip1, struct ip_service *ip2)
387 if ( (result = ip_compare(&ip1->ip, &ip2->ip)) != 0 )
390 if ( ip1->port > ip2->port )
393 if ( ip1->port < ip2->port )
400 sort an IP list so that names that are close to one of our interfaces
401 are at the top. This prevents the problem where a WINS server returns an IP that
402 is not reachable from our subnet as the first match
405 static void sort_ip_list(struct in_addr *iplist, int count)
411 qsort(iplist, count, sizeof(struct in_addr), QSORT_CAST ip_compare);
414 static void sort_ip_list2(struct ip_service *iplist, int count)
420 qsort(iplist, count, sizeof(struct ip_service), QSORT_CAST ip_service_compare);
423 /**********************************************************************
424 Remove any duplicate address/port pairs in the list
425 *********************************************************************/
427 static int remove_duplicate_addrs2( struct ip_service *iplist, int count )
431 DEBUG(10,("remove_duplicate_addrs2: looking for duplicate address/port pairs\n"));
433 /* one loop to remove duplicates */
434 for ( i=0; i<count; i++ ) {
435 if ( is_zero_ip(iplist[i].ip) )
438 for ( j=i+1; j<count; j++ ) {
439 if ( ip_service_equal(iplist[i], iplist[j]) )
440 zero_ip(&iplist[j].ip);
444 /* one loop to clean up any holes we left */
445 /* first ip should never be a zero_ip() */
446 for (i = 0; i<count; ) {
447 if ( is_zero_ip(iplist[i].ip) ) {
449 memmove(&iplist[i], &iplist[i+1], (count - i - 1)*sizeof(iplist[i]));
459 /****************************************************************************
460 Do a netbios name query to find someones IP.
461 Returns an array of IP addresses or NULL if none.
462 *count will be set to the number of addresses returned.
463 *timed_out is set if we failed by timing out
464 ****************************************************************************/
466 struct in_addr *name_query(int fd,const char *name,int name_type,
467 BOOL bcast,BOOL recurse,
468 struct in_addr to_ip, int *count, int *flags,
473 int retry_time = bcast?250:2000;
475 struct packet_struct p;
476 struct packet_struct *p2;
477 struct nmb_packet *nmb = &p.packet.nmb;
478 struct in_addr *ip_list = NULL;
480 if (lp_disable_netbios()) {
481 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n", name, name_type));
489 memset((char *)&p,'\0',sizeof(p));
493 nmb->header.name_trn_id = generate_trn_id();
494 nmb->header.opcode = 0;
495 nmb->header.response = False;
496 nmb->header.nm_flags.bcast = bcast;
497 nmb->header.nm_flags.recursion_available = False;
498 nmb->header.nm_flags.recursion_desired = recurse;
499 nmb->header.nm_flags.trunc = False;
500 nmb->header.nm_flags.authoritative = False;
501 nmb->header.rcode = 0;
502 nmb->header.qdcount = 1;
503 nmb->header.ancount = 0;
504 nmb->header.nscount = 0;
505 nmb->header.arcount = 0;
507 make_nmb_name(&nmb->question.question_name,name,name_type);
509 nmb->question.question_type = 0x20;
510 nmb->question.question_class = 0x1;
515 p.timestamp = time(NULL);
516 p.packet_type = NMB_PACKET;
520 if (!send_packet(&p))
526 struct timeval tval2;
528 GetTimeOfDay(&tval2);
529 if (TvalDiff(&tval,&tval2) > retry_time) {
532 if (!found && !send_packet(&p))
538 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
539 struct nmb_packet *nmb2 = &p2->packet.nmb;
540 debug_nmb_packet(p2);
542 /* If we get a Negative Name Query Response from a WINS
543 * server, we should report it and give up.
545 if( 0 == nmb2->header.opcode /* A query response */
546 && !(bcast) /* from a WINS server */
547 && nmb2->header.rcode /* Error returned */
550 if( DEBUGLVL( 3 ) ) {
551 /* Only executed if DEBUGLEVEL >= 3 */
552 dbgtext( "Negative name query response, rcode 0x%02x: ", nmb2->header.rcode );
553 switch( nmb2->header.rcode ) {
555 dbgtext( "Request was invalidly formatted.\n" );
558 dbgtext( "Problem with NBNS, cannot process name.\n");
561 dbgtext( "The name requested does not exist.\n" );
564 dbgtext( "Unsupported request error.\n" );
567 dbgtext( "Query refused error.\n" );
570 dbgtext( "Unrecognized error code.\n" );
578 if (nmb2->header.opcode != 0 ||
579 nmb2->header.nm_flags.bcast ||
580 nmb2->header.rcode ||
581 !nmb2->header.ancount) {
583 * XXXX what do we do with this? Could be a
584 * redirect, but we'll discard it for the
591 ip_list = SMB_REALLOC_ARRAY( ip_list, struct in_addr,
592 (*count) + nmb2->answers->rdlength/6 );
595 DEBUG(0,("name_query: Realloc failed.\n"));
600 DEBUG(2,("Got a positive name query response from %s ( ", inet_ntoa(p2->ip)));
601 for (i=0;i<nmb2->answers->rdlength/6;i++) {
602 putip((char *)&ip_list[(*count)],&nmb2->answers->rdata[2+i*6]);
603 DEBUGADD(2,("%s ",inet_ntoa(ip_list[(*count)])));
610 /* We add the flags back ... */
611 if (nmb2->header.response)
612 (*flags) |= NM_FLAGS_RS;
613 if (nmb2->header.nm_flags.authoritative)
614 (*flags) |= NM_FLAGS_AA;
615 if (nmb2->header.nm_flags.trunc)
616 (*flags) |= NM_FLAGS_TC;
617 if (nmb2->header.nm_flags.recursion_desired)
618 (*flags) |= NM_FLAGS_RD;
619 if (nmb2->header.nm_flags.recursion_available)
620 (*flags) |= NM_FLAGS_RA;
621 if (nmb2->header.nm_flags.bcast)
622 (*flags) |= NM_FLAGS_B;
625 * If we're doing a unicast lookup we only
626 * expect one reply. Don't wait the full 2
627 * seconds if we got one. JRA.
634 /* only set timed_out if we didn't fund what we where looking for*/
636 if ( !found && timed_out ) {
640 /* sort the ip list so we choose close servers first if possible */
641 sort_ip_list(ip_list, *count);
646 /********************************************************
647 Start parsing the lmhosts file.
648 *********************************************************/
650 XFILE *startlmhosts(char *fname)
652 XFILE *fp = x_fopen(fname,O_RDONLY, 0);
654 DEBUG(4,("startlmhosts: Can't open lmhosts file %s. Error was %s\n",
655 fname, strerror(errno)));
661 /********************************************************
662 Parse the next line in the lmhosts file.
663 *********************************************************/
665 BOOL getlmhostsent( XFILE *fp, pstring name, int *name_type, struct in_addr *ipaddr)
669 while(!x_feof(fp) && !x_ferror(fp)) {
670 pstring ip,flags,extra;
677 if (!fgets_slash(line,sizeof(pstring),fp)) {
691 if (next_token(&ptr,ip ,NULL,sizeof(ip)))
693 if (next_token(&ptr,name ,NULL, sizeof(pstring)))
695 if (next_token(&ptr,flags,NULL, sizeof(flags)))
697 if (next_token(&ptr,extra,NULL, sizeof(extra)))
703 if (count > 0 && count < 2) {
704 DEBUG(0,("getlmhostsent: Ill formed hosts line [%s]\n",line));
709 DEBUG(0,("getlmhostsent: too many columns in lmhosts file (obsolete syntax)\n"));
713 DEBUG(4, ("getlmhostsent: lmhost entry: %s %s %s\n", ip, name, flags));
715 if (strchr_m(flags,'G') || strchr_m(flags,'S')) {
716 DEBUG(0,("getlmhostsent: group flag in lmhosts ignored (obsolete)\n"));
720 *ipaddr = *interpret_addr2(ip);
722 /* Extra feature. If the name ends in '#XX', where XX is a hex number,
723 then only add that name type. */
724 if((ptr1 = strchr_m(name, '#')) != NULL) {
728 *name_type = (int)strtol(ptr1, &endptr, 16);
729 if(!*ptr1 || (endptr == ptr1)) {
730 DEBUG(0,("getlmhostsent: invalid name %s containing '#'.\n", name));
734 *(--ptr1) = '\0'; /* Truncate at the '#' */
743 /********************************************************
744 Finish parsing the lmhosts file.
745 *********************************************************/
747 void endlmhosts(XFILE *fp)
752 /********************************************************
753 convert an array if struct in_addrs to struct ip_service
754 return False on failure. Port is set to PORT_NONE;
755 *********************************************************/
757 static BOOL convert_ip2service( struct ip_service **return_iplist, struct in_addr *ip_list, int count )
761 if ( count==0 || !ip_list )
764 /* copy the ip address; port will be PORT_NONE */
765 if ( (*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
766 DEBUG(0,("convert_ip2service: malloc failed for %d enetries!\n", count ));
770 for ( i=0; i<count; i++ ) {
771 (*return_iplist)[i].ip = ip_list[i];
772 (*return_iplist)[i].port = PORT_NONE;
777 /********************************************************
778 Resolve via "bcast" method.
779 *********************************************************/
781 BOOL name_resolve_bcast(const char *name, int name_type,
782 struct ip_service **return_iplist, int *return_count)
785 int num_interfaces = iface_count();
786 struct in_addr *ip_list;
789 if (lp_disable_netbios()) {
790 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n", name, name_type));
794 *return_iplist = NULL;
798 * "bcast" means do a broadcast lookup on all the local interfaces.
801 DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup for name %s<0x%x>\n", name, name_type));
803 sock = open_socket_in( SOCK_DGRAM, 0, 3,
804 interpret_addr(lp_socket_address()), True );
806 if (sock == -1) return False;
808 set_socket_options(sock,"SO_BROADCAST");
810 * Lookup the name on all the interfaces, return on
811 * the first successful match.
813 for( i = num_interfaces-1; i >= 0; i--) {
814 struct in_addr sendto_ip;
816 /* Done this way to fix compiler error on IRIX 5.x */
817 sendto_ip = *iface_n_bcast(i);
818 ip_list = name_query(sock, name, name_type, True,
819 True, sendto_ip, return_count, &flags, NULL);
824 /* failed - no response */
831 if ( !convert_ip2service(return_iplist, ip_list, *return_count) )
834 SAFE_FREE( ip_list );
839 /********************************************************
840 Resolve via "wins" method.
841 *********************************************************/
843 BOOL resolve_wins(const char *name, int name_type,
844 struct ip_service **return_iplist, int *return_count)
848 struct in_addr src_ip, *ip_list = NULL;
851 if (lp_disable_netbios()) {
852 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n", name, name_type));
856 *return_iplist = NULL;
859 DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n", name, name_type));
861 if (wins_srv_count() < 1) {
862 DEBUG(3,("resolve_wins: WINS server resolution selected and no WINS servers listed.\n"));
866 /* we try a lookup on each of the WINS tags in turn */
867 wins_tags = wins_srv_tags();
870 /* huh? no tags?? give up in disgust */
874 /* the address we will be sending from */
875 src_ip = *interpret_addr2(lp_socket_address());
877 /* in the worst case we will try every wins server with every
879 for (t=0; wins_tags && wins_tags[t]; t++) {
880 int srv_count = wins_srv_count_tag(wins_tags[t]);
881 for (i=0; i<srv_count; i++) {
882 struct in_addr wins_ip;
886 wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
888 if (global_in_nmbd && ismyip(wins_ip)) {
889 /* yikes! we'll loop forever */
893 /* skip any that have been unresponsive lately */
894 if (wins_srv_is_dead(wins_ip, src_ip)) {
898 DEBUG(3,("resolve_wins: using WINS server %s and tag '%s'\n", inet_ntoa(wins_ip), wins_tags[t]));
900 sock = open_socket_in(SOCK_DGRAM, 0, 3, src_ip.s_addr, True);
905 ip_list = name_query(sock,name,name_type, False,
906 True, wins_ip, return_count, &flags,
909 /* exit loop if we got a list of addresses */
917 /* Timed out wating for WINS server to respond. Mark it dead. */
918 wins_srv_died(wins_ip, src_ip);
920 /* The name definately isn't in this
921 group of WINS servers. goto the next group */
927 wins_srv_tags_free(wins_tags);
932 if ( !convert_ip2service( return_iplist, ip_list, *return_count ) )
935 SAFE_FREE( ip_list );
936 wins_srv_tags_free(wins_tags);
942 /********************************************************
943 Resolve via "lmhosts" method.
944 *********************************************************/
946 static BOOL resolve_lmhosts(const char *name, int name_type,
947 struct ip_service **return_iplist, int *return_count)
950 * "lmhosts" means parse the local lmhosts file.
956 struct in_addr return_ip;
959 *return_iplist = NULL;
962 DEBUG(3,("resolve_lmhosts: Attempting lmhosts lookup for name %s<0x%x>\n", name, name_type));
964 fp = startlmhosts(dyn_LMHOSTSFILE);
969 while (getlmhostsent(fp, lmhost_name, &name_type2, &return_ip))
972 if (!strequal(name, lmhost_name))
975 if ((name_type2 != -1) && (name_type != name_type2))
978 *return_iplist = SMB_REALLOC_ARRAY((*return_iplist), struct ip_service,
981 if ((*return_iplist) == NULL) {
983 DEBUG(3,("resolve_lmhosts: malloc fail !\n"));
987 (*return_iplist)[*return_count].ip = return_ip;
988 (*return_iplist)[*return_count].port = PORT_NONE;
991 /* we found something */
994 /* Multiple names only for DC lookup */
995 if (name_type != 0x1c)
1005 /********************************************************
1006 Resolve via "hosts" method.
1007 *********************************************************/
1009 static BOOL resolve_hosts(const char *name, int name_type,
1010 struct ip_service **return_iplist, int *return_count)
1013 * "host" means do a localhost, or dns lookup.
1017 if ( name_type != 0x20 && name_type != 0x0) {
1018 DEBUG(5, ("resolve_hosts: not appropriate for name type <0x%x>\n", name_type));
1022 *return_iplist = NULL;
1025 DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n", name, name_type));
1027 if (((hp = sys_gethostbyname(name)) != NULL) && (hp->h_addr != NULL)) {
1028 struct in_addr return_ip;
1029 putip((char *)&return_ip,(char *)hp->h_addr);
1030 *return_iplist = SMB_MALLOC_P(struct ip_service);
1031 if(*return_iplist == NULL) {
1032 DEBUG(3,("resolve_hosts: malloc fail !\n"));
1035 (*return_iplist)->ip = return_ip;
1036 (*return_iplist)->port = PORT_NONE;
1043 /********************************************************
1044 Resolve via "ADS" method.
1045 *********************************************************/
1047 static BOOL resolve_ads(const char *name, int name_type,
1048 struct ip_service **return_iplist, int *return_count)
1053 struct dns_rr_srv *dcs = NULL;
1057 if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE))
1060 DEBUG(5,("resolve_hosts: Attempting to resolve DC's for %s using DNS\n",
1063 if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1064 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1068 if (name_type == KDC_NAME_TYPE) {
1069 status = ads_dns_query_kdcs(ctx, name, &dcs, &numdcs);
1071 status = ads_dns_query_dcs(ctx, name, &dcs, &numdcs);
1073 if ( !NT_STATUS_IS_OK( status ) ) {
1074 talloc_destroy(ctx);
1078 for (i=0;i<numdcs;i++) {
1079 numaddrs += MAX(dcs[i].num_ips,1);
1082 if ( (*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) == NULL ) {
1083 DEBUG(0,("resolve_ads: malloc failed for %d entries\n", numaddrs ));
1084 talloc_destroy(ctx);
1088 /* now unroll the list of IP addresses */
1093 while ( i < numdcs && (*return_count<numaddrs) ) {
1094 struct ip_service *r = &(*return_iplist)[*return_count];
1096 r->port = dcs[i].port;
1098 /* If we don't have an IP list for a name, lookup it up */
1100 if ( !dcs[i].ips ) {
1101 r->ip = *interpret_addr2(dcs[i].hostname);
1105 /* use the IP addresses from the SRV sresponse */
1107 if ( j >= dcs[i].num_ips ) {
1113 r->ip = dcs[i].ips[j];
1117 /* make sure it is a valid IP. I considered checking the negative
1118 connection cache, but this is the wrong place for it. Maybe only
1119 as a hac. After think about it, if all of the IP addresses retuend
1120 from DNS are dead, what hope does a netbios name lookup have?
1121 The standard reason for falling back to netbios lookups is that
1122 our DNS server doesn't know anything about the DC's -- jerry */
1124 if ( ! is_zero_ip(r->ip) )
1128 talloc_destroy(ctx);
1132 /*******************************************************************
1133 Internal interface to resolve a name into an IP address.
1134 Use this function if the string is either an IP address, DNS
1135 or host name or NetBIOS name. This uses the name switch in the
1136 smb.conf to determine the order of name resolution.
1138 Added support for ip addr/port to support ADS ldap servers.
1139 the only place we currently care about the port is in the
1140 resolve_hosts() when looking up DC's via SRV RR entries in DNS
1141 **********************************************************************/
1143 BOOL internal_resolve_name(const char *name, int name_type,
1144 struct ip_service **return_iplist,
1145 int *return_count, const char *resolve_order)
1147 pstring name_resolve_list;
1150 BOOL allones = (strcmp(name,"255.255.255.255") == 0);
1151 BOOL allzeros = (strcmp(name,"0.0.0.0") == 0);
1152 BOOL is_address = is_ipaddress(name);
1153 BOOL result = False;
1156 *return_iplist = NULL;
1159 DEBUG(10, ("internal_resolve_name: looking up %s#%x\n", name, name_type));
1161 if (allzeros || allones || is_address) {
1163 if ( (*return_iplist = SMB_MALLOC_P(struct ip_service)) == NULL ) {
1164 DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1169 /* ignore the port here */
1170 (*return_iplist)->port = PORT_NONE;
1172 /* if it's in the form of an IP address then get the lib to interpret it */
1173 if (((*return_iplist)->ip.s_addr = inet_addr(name)) == 0xFFFFFFFF ){
1174 DEBUG(1,("internal_resolve_name: inet_addr failed on %s\n", name));
1175 SAFE_FREE(*return_iplist);
1179 (*return_iplist)->ip.s_addr = allones ? 0xFFFFFFFF : 0;
1185 /* Check name cache */
1187 if (namecache_fetch(name, name_type, return_iplist, return_count)) {
1188 /* This could be a negative response */
1189 return (*return_count > 0);
1192 /* set the name resolution order */
1194 if ( strcmp( resolve_order, "NULL") == 0 ) {
1195 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
1199 if ( !resolve_order ) {
1200 pstrcpy(name_resolve_list, lp_name_resolve_order());
1202 pstrcpy(name_resolve_list, resolve_order);
1205 if ( !name_resolve_list[0] ) {
1208 ptr = name_resolve_list;
1211 /* iterate through the name resolution backends */
1213 while (next_token(&ptr, tok, LIST_SEP, sizeof(tok))) {
1214 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
1215 if (resolve_hosts(name, name_type, return_iplist, return_count)) {
1219 } else if(strequal( tok, "kdc")) {
1220 /* deal with KDC_NAME_TYPE names here. This will result in a
1221 SRV record lookup */
1222 if (resolve_ads(name, KDC_NAME_TYPE, return_iplist, return_count)) {
1224 /* Ensure we don't namecache this with the KDC port. */
1225 name_type = KDC_NAME_TYPE;
1228 } else if(strequal( tok, "ads")) {
1229 /* deal with 0x1c names here. This will result in a
1230 SRV record lookup */
1231 if (resolve_ads(name, name_type, return_iplist, return_count)) {
1235 } else if(strequal( tok, "lmhosts")) {
1236 if (resolve_lmhosts(name, name_type, return_iplist, return_count)) {
1240 } else if(strequal( tok, "wins")) {
1241 /* don't resolve 1D via WINS */
1242 if (name_type != 0x1D && resolve_wins(name, name_type, return_iplist, return_count)) {
1246 } else if(strequal( tok, "bcast")) {
1247 if (name_resolve_bcast(name, name_type, return_iplist, return_count)) {
1252 DEBUG(0,("resolve_name: unknown name switch type %s\n", tok));
1256 /* All of the resolve_* functions above have returned false. */
1258 SAFE_FREE(*return_iplist);
1265 /* Remove duplicate entries. Some queries, notably #1c (domain
1266 controllers) return the PDC in iplist[0] and then all domain
1267 controllers including the PDC in iplist[1..n]. Iterating over
1268 the iplist when the PDC is down will cause two sets of timeouts. */
1270 if ( *return_count ) {
1271 *return_count = remove_duplicate_addrs2( *return_iplist, *return_count );
1274 /* Save in name cache */
1275 if ( DEBUGLEVEL >= 100 ) {
1276 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++)
1277 DEBUG(100, ("Storing name %s of type %d (%s:%d)\n", name,
1278 name_type, inet_ntoa((*return_iplist)[i].ip), (*return_iplist)[i].port));
1281 namecache_store(name, name_type, *return_count, *return_iplist);
1283 /* Display some debugging info */
1285 if ( DEBUGLEVEL >= 10 ) {
1286 DEBUG(10, ("internal_resolve_name: returning %d addresses: ", *return_count));
1288 for (i = 0; i < *return_count; i++) {
1289 DEBUGADD(10, ("%s:%d ", inet_ntoa((*return_iplist)[i].ip), (*return_iplist)[i].port));
1297 /********************************************************
1298 Internal interface to resolve a name into one IP address.
1299 Use this function if the string is either an IP address, DNS
1300 or host name or NetBIOS name. This uses the name switch in the
1301 smb.conf to determine the order of name resolution.
1302 *********************************************************/
1304 BOOL resolve_name(const char *name, struct in_addr *return_ip, int name_type)
1306 struct ip_service *ip_list = NULL;
1309 if (is_ipaddress(name)) {
1310 *return_ip = *interpret_addr2(name);
1314 if (internal_resolve_name(name, name_type, &ip_list, &count, lp_name_resolve_order())) {
1317 /* only return valid addresses for TCP connections */
1318 for (i=0; i<count; i++) {
1319 char *ip_str = inet_ntoa(ip_list[i].ip);
1321 strcmp(ip_str, "255.255.255.255") != 0 &&
1322 strcmp(ip_str, "0.0.0.0") != 0)
1324 *return_ip = ip_list[i].ip;
1335 /********************************************************
1336 Find the IP address of the master browser or DMB for a workgroup.
1337 *********************************************************/
1339 BOOL find_master_ip(const char *group, struct in_addr *master_ip)
1341 struct ip_service *ip_list = NULL;
1344 if (lp_disable_netbios()) {
1345 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
1349 if (internal_resolve_name(group, 0x1D, &ip_list, &count, lp_name_resolve_order())) {
1350 *master_ip = ip_list[0].ip;
1354 if(internal_resolve_name(group, 0x1B, &ip_list, &count, lp_name_resolve_order())) {
1355 *master_ip = ip_list[0].ip;
1364 /********************************************************
1365 Get the IP address list of the primary domain controller
1367 *********************************************************/
1369 BOOL get_pdc_ip(const char *domain, struct in_addr *ip)
1371 struct ip_service *ip_list;
1374 /* Look up #1B name */
1376 if (!internal_resolve_name(domain, 0x1b, &ip_list, &count, lp_name_resolve_order())) {
1380 /* if we get more than 1 IP back we have to assume it is a
1381 multi-homed PDC and not a mess up */
1384 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
1385 sort_ip_list2( ip_list, count );
1388 *ip = ip_list[0].ip;
1395 /* Private enum type for lookups. */
1397 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
1399 /********************************************************
1400 Get the IP address list of the domain controllers for
1402 *********************************************************/
1404 static NTSTATUS get_dc_list(const char *domain, struct ip_service **ip_list,
1405 int *count, enum dc_lookup_type lookup_type, int *ordered)
1407 fstring resolve_order;
1408 char *saf_servername;
1414 int num_addresses = 0;
1415 int local_count, i, j;
1416 struct ip_service *return_iplist = NULL;
1417 struct ip_service *auto_ip_list = NULL;
1418 BOOL done_auto_lookup = False;
1423 /* if we are restricted to solely using DNS for looking
1424 up a domain controller, make sure that host lookups
1425 are enabled for the 'name resolve order'. If host lookups
1426 are disabled and ads_only is True, then set the string to
1429 fstrcpy( resolve_order, lp_name_resolve_order() );
1430 strlower_m( resolve_order );
1431 if ( lookup_type == DC_ADS_ONLY) {
1432 if ( strstr( resolve_order, "host" ) ) {
1433 fstrcpy( resolve_order, "ads" );
1435 /* DNS SRV lookups used by the ads resolver
1436 are already sorted by priority and weight */
1439 fstrcpy( resolve_order, "NULL" );
1441 } else if (lookup_type == DC_KDC_ONLY) {
1442 /* DNS SRV lookups used by the ads/kdc resolver
1443 are already sorted by priority and weight */
1445 fstrcpy( resolve_order, "kdc" );
1448 /* fetch the server we have affinity for. Add the
1449 'password server' list to a search for our domain controllers */
1451 saf_servername = saf_fetch( domain );
1453 if ( strequal(domain, lp_workgroup()) || strequal(domain, lp_realm()) ) {
1454 pstr_sprintf( pserver, "%s, %s",
1455 saf_servername ? saf_servername : "",
1456 lp_passwordserver() );
1458 pstr_sprintf( pserver, "%s, *",
1459 saf_servername ? saf_servername : "" );
1462 SAFE_FREE( saf_servername );
1464 /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
1467 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
1468 /* TODO: change return type of internal_resolve_name to
1470 if (internal_resolve_name(domain, 0x1C, ip_list, count,
1472 return NT_STATUS_OK;
1474 return NT_STATUS_NO_LOGON_SERVERS;
1478 DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
1481 * if '*' appears in the "password server" list then add
1482 * an auto lookup to the list of manually configured
1483 * DC's. If any DC is listed by name, then the list should be
1484 * considered to be ordered
1488 while (next_token(&p,name,LIST_SEP,sizeof(name))) {
1489 if (strequal(name, "*")) {
1490 if (internal_resolve_name(domain, 0x1C, &auto_ip_list,
1491 &auto_count, resolve_order))
1492 num_addresses += auto_count;
1493 done_auto_lookup = True;
1494 DEBUG(8,("Adding %d DC's from auto lookup\n", auto_count));
1500 /* if we have no addresses and haven't done the auto lookup, then
1501 just return the list of DC's. Or maybe we just failed. */
1503 if ( (num_addresses == 0) ) {
1504 if ( !done_auto_lookup ) {
1505 if (internal_resolve_name(domain, 0x1C, ip_list, count, resolve_order)) {
1506 return NT_STATUS_OK;
1508 return NT_STATUS_NO_LOGON_SERVERS;
1511 DEBUG(4,("get_dc_list: no servers found\n"));
1512 return NT_STATUS_NO_LOGON_SERVERS;
1516 if ( (return_iplist = SMB_MALLOC_ARRAY(struct ip_service, num_addresses)) == NULL ) {
1517 DEBUG(3,("get_dc_list: malloc fail !\n"));
1518 return NT_STATUS_NO_MEMORY;
1524 /* fill in the return list now with real IP's */
1526 while ( (local_count<num_addresses) && next_token(&p,name,LIST_SEP,sizeof(name)) ) {
1527 struct in_addr name_ip;
1529 /* copy any addersses from the auto lookup */
1531 if ( strequal(name, "*") ) {
1532 for ( j=0; j<auto_count; j++ ) {
1533 /* Check for and don't copy any known bad DC IP's. */
1534 if(!NT_STATUS_IS_OK(check_negative_conn_cache(domain,
1535 inet_ntoa(auto_ip_list[j].ip)))) {
1536 DEBUG(5,("get_dc_list: negative entry %s removed from DC list\n",
1537 inet_ntoa(auto_ip_list[j].ip) ));
1540 return_iplist[local_count].ip = auto_ip_list[j].ip;
1541 return_iplist[local_count].port = auto_ip_list[j].port;
1548 /* added support for address:port syntax for ads (not that I think
1549 anyone will ever run the LDAP server in an AD domain on something
1550 other than port 389 */
1552 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
1553 if ( (port_str=strchr(name, ':')) != NULL ) {
1556 port = atoi( port_str );
1559 /* explicit lookup; resolve_name() will handle names & IP addresses */
1560 if ( resolve_name( name, &name_ip, 0x20 ) ) {
1562 /* Check for and don't copy any known bad DC IP's. */
1563 if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain, inet_ntoa(name_ip))) ) {
1564 DEBUG(5,("get_dc_list: negative entry %s removed from DC list\n",name ));
1568 return_iplist[local_count].ip = name_ip;
1569 return_iplist[local_count].port = port;
1575 SAFE_FREE(auto_ip_list);
1577 /* need to remove duplicates in the list if we have any
1578 explicit password servers */
1580 if ( local_count ) {
1581 local_count = remove_duplicate_addrs2( return_iplist, local_count );
1584 if ( DEBUGLEVEL >= 4 ) {
1585 DEBUG(4,("get_dc_list: returning %d ip addresses in an %sordered list\n", local_count,
1586 *ordered ? "":"un"));
1587 DEBUG(4,("get_dc_list: "));
1588 for ( i=0; i<local_count; i++ )
1589 DEBUGADD(4,("%s:%d ", inet_ntoa(return_iplist[i].ip), return_iplist[i].port ));
1593 *ip_list = return_iplist;
1594 *count = local_count;
1596 return ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
1599 /*********************************************************************
1600 Small wrapper function to get the DC list and sort it if neccessary.
1601 *********************************************************************/
1603 NTSTATUS get_sorted_dc_list( const char *domain, struct ip_service **ip_list, int *count, BOOL ads_only )
1607 enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
1609 DEBUG(8,("get_sorted_dc_list: attempting lookup using [%s]\n",
1610 (ads_only ? "ads" : lp_name_resolve_order())));
1613 lookup_type = DC_ADS_ONLY;
1616 status = get_dc_list(domain, ip_list, count, lookup_type, &ordered);
1617 if (!NT_STATUS_IS_OK(status)) {
1621 /* only sort if we don't already have an ordered list */
1623 sort_ip_list2( *ip_list, *count );
1626 return NT_STATUS_OK;
1629 /*********************************************************************
1630 Get the KDC list - re-use all the logic in get_dc_list.
1631 *********************************************************************/
1633 NTSTATUS get_kdc_list( const char *realm, struct ip_service **ip_list, int *count)
1641 status = get_dc_list(realm, ip_list, count, DC_KDC_ONLY, &ordered);
1643 if (!NT_STATUS_IS_OK(status)) {
1647 /* only sort if we don't already have an ordered list */
1649 sort_ip_list2( *ip_list, *count );
1652 return NT_STATUS_OK;