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 3 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, see <http://www.gnu.org/licenses/>.
22 /* nmbd.c sets this to True. */
23 bool global_in_nmbd = False;
25 /****************************
26 * SERVER AFFINITY ROUTINES *
27 ****************************/
29 /* Server affinity is the concept of preferring the last domain
30 controller with whom you had a successful conversation */
32 /****************************************************************************
33 ****************************************************************************/
34 #define SAFKEY_FMT "SAF/DOMAIN/%s"
37 static char *saf_key(const char *domain)
41 asprintf( &keystr, SAFKEY_FMT, strupper_static(domain) );
46 /****************************************************************************
47 ****************************************************************************/
49 bool saf_store( const char *domain, const char *servername )
55 if ( !domain || !servername ) {
56 DEBUG(2,("saf_store: Refusing to store empty domain or servername!\n"));
60 if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
61 DEBUG(0,("saf_store: refusing to store 0 length domain or servername!\n"));
65 if ( !gencache_init() )
68 key = saf_key( domain );
69 expire = time( NULL ) + SAF_TTL;
72 DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
73 domain, servername, (unsigned int)expire ));
75 ret = gencache_set( key, servername, expire );
82 bool saf_delete( const char *domain )
88 DEBUG(2,("saf_delete: Refusing to delete empty domain\n"));
92 if ( !gencache_init() )
95 key = saf_key(domain);
96 ret = gencache_del(key);
99 DEBUG(10,("saf_delete: domain = [%s]\n", domain ));
107 /****************************************************************************
108 ****************************************************************************/
110 char *saf_fetch( const char *domain )
117 if ( !domain || strlen(domain) == 0) {
118 DEBUG(2,("saf_fetch: Empty domain name!\n"));
122 if ( !gencache_init() )
125 key = saf_key( domain );
127 ret = gencache_get( key, &server, &timeout );
132 DEBUG(5,("saf_fetch: failed to find server for \"%s\" domain\n", domain ));
134 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
141 /****************************************************************************
142 Generate a random trn_id.
143 ****************************************************************************/
145 static int generate_trn_id(void)
149 generate_random_buffer((uint8 *)&id, sizeof(id));
151 return id % (unsigned)0x7FFF;
154 /****************************************************************************
155 Parse a node status response into an array of structures.
156 ****************************************************************************/
158 static NODE_STATUS_STRUCT *parse_node_status(char *p, int *num_names, struct node_status_extra *extra)
160 NODE_STATUS_STRUCT *ret;
163 *num_names = CVAL(p,0);
168 ret = SMB_MALLOC_ARRAY(NODE_STATUS_STRUCT,*num_names);
173 for (i=0;i< *num_names;i++) {
174 StrnCpy(ret[i].name,p,15);
175 trim_char(ret[i].name,'\0',' ');
176 ret[i].type = CVAL(p,15);
177 ret[i].flags = p[16];
179 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
180 ret[i].type, ret[i].flags));
183 * Also, pick up the MAC address ...
186 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
192 /****************************************************************************
193 Do a NBT node status query on an open socket and return an array of
194 structures holding the returned names or NULL if the query failed.
195 **************************************************************************/
197 NODE_STATUS_STRUCT *node_status_query(int fd,struct nmb_name *name,
198 struct in_addr to_ip, int *num_names,
199 struct node_status_extra *extra)
203 int retry_time = 2000;
205 struct packet_struct p;
206 struct packet_struct *p2;
207 struct nmb_packet *nmb = &p.packet.nmb;
208 NODE_STATUS_STRUCT *ret;
212 nmb->header.name_trn_id = generate_trn_id();
213 nmb->header.opcode = 0;
214 nmb->header.response = False;
215 nmb->header.nm_flags.bcast = False;
216 nmb->header.nm_flags.recursion_available = False;
217 nmb->header.nm_flags.recursion_desired = False;
218 nmb->header.nm_flags.trunc = False;
219 nmb->header.nm_flags.authoritative = False;
220 nmb->header.rcode = 0;
221 nmb->header.qdcount = 1;
222 nmb->header.ancount = 0;
223 nmb->header.nscount = 0;
224 nmb->header.arcount = 0;
225 nmb->question.question_name = *name;
226 nmb->question.question_type = 0x21;
227 nmb->question.question_class = 0x1;
232 p.timestamp = time(NULL);
233 p.packet_type = NMB_PACKET;
237 if (!send_packet(&p))
243 struct timeval tval2;
244 GetTimeOfDay(&tval2);
245 if (TvalDiff(&tval,&tval2) > retry_time) {
248 if (!found && !send_packet(&p))
254 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
255 struct nmb_packet *nmb2 = &p2->packet.nmb;
256 debug_nmb_packet(p2);
258 if (nmb2->header.opcode != 0 ||
259 nmb2->header.nm_flags.bcast ||
260 nmb2->header.rcode ||
261 !nmb2->header.ancount ||
262 nmb2->answers->rr_type != 0x21) {
263 /* XXXX what do we do with this? could be a
264 redirect, but we'll discard it for the
270 ret = parse_node_status(&nmb2->answers->rdata[0], num_names, extra);
279 /****************************************************************************
280 Find the first type XX name in a node status reply - used for finding
281 a servers name given its IP. Return the matched name in *name.
282 **************************************************************************/
284 bool name_status_find(const char *q_name, int q_type, int type, struct in_addr to_ip, fstring name)
286 NODE_STATUS_STRUCT *status = NULL;
287 struct nmb_name nname;
292 if (lp_disable_netbios()) {
293 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n", q_name, q_type));
297 DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
298 q_type, inet_ntoa(to_ip)));
300 /* Check the cache first. */
302 if (namecache_status_fetch(q_name, q_type, type, to_ip, name))
305 sock = open_socket_in(SOCK_DGRAM, 0, 3, interpret_addr(lp_socket_address()), True);
309 /* W2K PDC's seem not to respond to '*'#0. JRA */
310 make_nmb_name(&nname, q_name, q_type);
311 status = node_status_query(sock, &nname, to_ip, &count, NULL);
316 for (i=0;i<count;i++) {
317 if (status[i].type == type)
323 pull_ascii_nstring(name, sizeof(fstring), status[i].name);
325 /* Store the result in the cache. */
326 /* but don't store an entry for 0x1c names here. Here we have
327 a single host and DOMAIN<0x1c> names should be a list of hosts */
329 if ( q_type != 0x1c )
330 namecache_status_store(q_name, q_type, type, to_ip, name);
337 DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
340 DEBUGADD(10, (", name %s ip address is %s", name, inet_ntoa(to_ip)));
348 comparison function used by sort_ip_list
351 static int ip_compare(struct in_addr *ip1, struct in_addr *ip2)
353 int max_bits1=0, max_bits2=0;
354 int num_interfaces = iface_count();
355 struct sockaddr_storage ss;
358 for (i=0;i<num_interfaces;i++) {
359 const struct sockaddr_storage *pss = iface_n_bcast(i);
363 if (pss->ss_family != AF_INET) {
366 ip = ((const struct sockaddr_in *)pss)->sin_addr;
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 in_addr_to_sockaddr_storage(&ss, *ip1);
375 if (iface_local(&ss)) {
378 in_addr_to_sockaddr_storage(&ss, *ip1);
379 if (iface_local(&ss)) {
383 return max_bits2 - max_bits1;
386 /*******************************************************************
387 compare 2 ldap IPs by nearness to our interfaces - used in qsort
388 *******************************************************************/
390 int ip_service_compare(struct ip_service *ip1, struct ip_service *ip2)
394 if ( (result = ip_compare(&ip1->ip, &ip2->ip)) != 0 )
397 if ( ip1->port > ip2->port )
400 if ( ip1->port < ip2->port )
407 sort an IP list so that names that are close to one of our interfaces
408 are at the top. This prevents the problem where a WINS server returns an IP that
409 is not reachable from our subnet as the first match
412 static void sort_ip_list(struct in_addr *iplist, int count)
418 qsort(iplist, count, sizeof(struct in_addr), QSORT_CAST ip_compare);
421 static void sort_ip_list2(struct ip_service *iplist, int count)
427 qsort(iplist, count, sizeof(struct ip_service), QSORT_CAST ip_service_compare);
430 /**********************************************************************
431 Remove any duplicate address/port pairs in the list
432 *********************************************************************/
434 static int remove_duplicate_addrs2( struct ip_service *iplist, int count )
438 DEBUG(10,("remove_duplicate_addrs2: looking for duplicate address/port pairs\n"));
440 /* one loop to remove duplicates */
441 for ( i=0; i<count; i++ ) {
442 if ( is_zero_ip_v4(iplist[i].ip) )
445 for ( j=i+1; j<count; j++ ) {
446 if ( ip_service_equal(iplist[i], iplist[j]) )
447 zero_ip_v4(&iplist[j].ip);
451 /* one loop to clean up any holes we left */
452 /* first ip should never be a zero_ip() */
453 for (i = 0; i<count; ) {
454 if ( is_zero_ip_v4(iplist[i].ip) ) {
456 memmove(&iplist[i], &iplist[i+1], (count - i - 1)*sizeof(iplist[i]));
466 /****************************************************************************
467 Do a netbios name query to find someones IP.
468 Returns an array of IP addresses or NULL if none.
469 *count will be set to the number of addresses returned.
470 *timed_out is set if we failed by timing out
471 ****************************************************************************/
473 struct in_addr *name_query(int fd,const char *name,int name_type,
474 bool bcast,bool recurse,
475 struct in_addr to_ip, int *count, int *flags,
480 int retry_time = bcast?250:2000;
482 struct packet_struct p;
483 struct packet_struct *p2;
484 struct nmb_packet *nmb = &p.packet.nmb;
485 struct in_addr *ip_list = NULL;
487 if (lp_disable_netbios()) {
488 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n", name, name_type));
496 memset((char *)&p,'\0',sizeof(p));
500 nmb->header.name_trn_id = generate_trn_id();
501 nmb->header.opcode = 0;
502 nmb->header.response = False;
503 nmb->header.nm_flags.bcast = bcast;
504 nmb->header.nm_flags.recursion_available = False;
505 nmb->header.nm_flags.recursion_desired = recurse;
506 nmb->header.nm_flags.trunc = False;
507 nmb->header.nm_flags.authoritative = False;
508 nmb->header.rcode = 0;
509 nmb->header.qdcount = 1;
510 nmb->header.ancount = 0;
511 nmb->header.nscount = 0;
512 nmb->header.arcount = 0;
514 make_nmb_name(&nmb->question.question_name,name,name_type);
516 nmb->question.question_type = 0x20;
517 nmb->question.question_class = 0x1;
522 p.timestamp = time(NULL);
523 p.packet_type = NMB_PACKET;
527 if (!send_packet(&p))
533 struct timeval tval2;
535 GetTimeOfDay(&tval2);
536 if (TvalDiff(&tval,&tval2) > retry_time) {
539 if (!found && !send_packet(&p))
545 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
546 struct nmb_packet *nmb2 = &p2->packet.nmb;
547 debug_nmb_packet(p2);
549 /* If we get a Negative Name Query Response from a WINS
550 * server, we should report it and give up.
552 if( 0 == nmb2->header.opcode /* A query response */
553 && !(bcast) /* from a WINS server */
554 && nmb2->header.rcode /* Error returned */
557 if( DEBUGLVL( 3 ) ) {
558 /* Only executed if DEBUGLEVEL >= 3 */
559 dbgtext( "Negative name query response, rcode 0x%02x: ", nmb2->header.rcode );
560 switch( nmb2->header.rcode ) {
562 dbgtext( "Request was invalidly formatted.\n" );
565 dbgtext( "Problem with NBNS, cannot process name.\n");
568 dbgtext( "The name requested does not exist.\n" );
571 dbgtext( "Unsupported request error.\n" );
574 dbgtext( "Query refused error.\n" );
577 dbgtext( "Unrecognized error code.\n" );
585 if (nmb2->header.opcode != 0 ||
586 nmb2->header.nm_flags.bcast ||
587 nmb2->header.rcode ||
588 !nmb2->header.ancount) {
590 * XXXX what do we do with this? Could be a
591 * redirect, but we'll discard it for the
598 ip_list = SMB_REALLOC_ARRAY( ip_list, struct in_addr,
599 (*count) + nmb2->answers->rdlength/6 );
602 DEBUG(0,("name_query: Realloc failed.\n"));
607 DEBUG(2,("Got a positive name query response from %s ( ", inet_ntoa(p2->ip)));
608 for (i=0;i<nmb2->answers->rdlength/6;i++) {
609 putip((char *)&ip_list[(*count)],&nmb2->answers->rdata[2+i*6]);
610 DEBUGADD(2,("%s ",inet_ntoa(ip_list[(*count)])));
617 /* We add the flags back ... */
618 if (nmb2->header.response)
619 (*flags) |= NM_FLAGS_RS;
620 if (nmb2->header.nm_flags.authoritative)
621 (*flags) |= NM_FLAGS_AA;
622 if (nmb2->header.nm_flags.trunc)
623 (*flags) |= NM_FLAGS_TC;
624 if (nmb2->header.nm_flags.recursion_desired)
625 (*flags) |= NM_FLAGS_RD;
626 if (nmb2->header.nm_flags.recursion_available)
627 (*flags) |= NM_FLAGS_RA;
628 if (nmb2->header.nm_flags.bcast)
629 (*flags) |= NM_FLAGS_B;
632 * If we're doing a unicast lookup we only
633 * expect one reply. Don't wait the full 2
634 * seconds if we got one. JRA.
641 /* only set timed_out if we didn't fund what we where looking for*/
643 if ( !found && timed_out ) {
647 /* sort the ip list so we choose close servers first if possible */
648 sort_ip_list(ip_list, *count);
653 /********************************************************
654 Start parsing the lmhosts file.
655 *********************************************************/
657 XFILE *startlmhosts(const char *fname)
659 XFILE *fp = x_fopen(fname,O_RDONLY, 0);
661 DEBUG(4,("startlmhosts: Can't open lmhosts file %s. Error was %s\n",
662 fname, strerror(errno)));
668 /********************************************************
669 Parse the next line in the lmhosts file.
670 *********************************************************/
672 bool getlmhostsent( XFILE *fp, pstring name, int *name_type, struct in_addr *ipaddr)
676 while(!x_feof(fp) && !x_ferror(fp)) {
677 pstring ip,flags,extra;
684 if (!fgets_slash(line,sizeof(pstring),fp)) {
698 if (next_token(&ptr,ip ,NULL,sizeof(ip)))
700 if (next_token(&ptr,name ,NULL, sizeof(pstring)))
702 if (next_token(&ptr,flags,NULL, sizeof(flags)))
704 if (next_token(&ptr,extra,NULL, sizeof(extra)))
710 if (count > 0 && count < 2) {
711 DEBUG(0,("getlmhostsent: Ill formed hosts line [%s]\n",line));
716 DEBUG(0,("getlmhostsent: too many columns in lmhosts file (obsolete syntax)\n"));
720 DEBUG(4, ("getlmhostsent: lmhost entry: %s %s %s\n", ip, name, flags));
722 if (strchr_m(flags,'G') || strchr_m(flags,'S')) {
723 DEBUG(0,("getlmhostsent: group flag in lmhosts ignored (obsolete)\n"));
727 *ipaddr = *interpret_addr2(ip);
729 /* Extra feature. If the name ends in '#XX', where XX is a hex number,
730 then only add that name type. */
731 if((ptr1 = strchr_m(name, '#')) != NULL) {
735 *name_type = (int)strtol(ptr1, &endptr, 16);
736 if(!*ptr1 || (endptr == ptr1)) {
737 DEBUG(0,("getlmhostsent: invalid name %s containing '#'.\n", name));
741 *(--ptr1) = '\0'; /* Truncate at the '#' */
750 /********************************************************
751 Finish parsing the lmhosts file.
752 *********************************************************/
754 void endlmhosts(XFILE *fp)
759 /********************************************************
760 convert an array if struct in_addrs to struct ip_service
761 return False on failure. Port is set to PORT_NONE;
762 *********************************************************/
764 static bool convert_ip2service( struct ip_service **return_iplist, struct in_addr *ip_list, int count )
768 if ( count==0 || !ip_list )
771 /* copy the ip address; port will be PORT_NONE */
772 if ( (*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) == NULL ) {
773 DEBUG(0,("convert_ip2service: malloc failed for %d enetries!\n", count ));
777 for ( i=0; i<count; i++ ) {
778 (*return_iplist)[i].ip = ip_list[i];
779 (*return_iplist)[i].port = PORT_NONE;
784 /********************************************************
785 Resolve via "bcast" method.
786 *********************************************************/
788 NTSTATUS name_resolve_bcast(const char *name, int name_type,
789 struct ip_service **return_iplist,
793 int num_interfaces = iface_count();
794 struct in_addr *ip_list;
797 if (lp_disable_netbios()) {
798 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n", name, name_type));
799 return NT_STATUS_INVALID_PARAMETER;
802 *return_iplist = NULL;
806 * "bcast" means do a broadcast lookup on all the local interfaces.
809 DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup for name %s<0x%x>\n", name, name_type));
811 sock = open_socket_in( SOCK_DGRAM, 0, 3,
812 interpret_addr(lp_socket_address()), True );
814 if (sock == -1) return NT_STATUS_UNSUCCESSFUL;
816 set_socket_options(sock,"SO_BROADCAST");
818 * Lookup the name on all the interfaces, return on
819 * the first successful match.
821 for( i = num_interfaces-1; i >= 0; i--) {
822 struct in_addr sendto_ip;
823 const struct sockaddr_storage *ss = iface_n_bcast(i);
826 /* Done this way to fix compiler error on IRIX 5.x */
827 if (!ss || ss->ss_family != AF_INET) {
830 sendto_ip = ((const struct sockaddr_in *)ss)->sin_addr;
831 ip_list = name_query(sock, name, name_type, True,
832 True, sendto_ip, return_count, &flags, NULL);
837 /* failed - no response */
840 return NT_STATUS_UNSUCCESSFUL;
843 status = NT_STATUS_OK;
844 if ( !convert_ip2service(return_iplist, ip_list, *return_count) )
845 status = NT_STATUS_INVALID_PARAMETER;
847 SAFE_FREE( ip_list );
852 /********************************************************
853 Resolve via "wins" method.
854 *********************************************************/
856 NTSTATUS resolve_wins(const char *name, int name_type,
857 struct ip_service **return_iplist,
862 struct in_addr src_ip, *ip_list = NULL;
865 if (lp_disable_netbios()) {
866 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n", name, name_type));
867 return NT_STATUS_INVALID_PARAMETER;
870 *return_iplist = NULL;
873 DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n", name, name_type));
875 if (wins_srv_count() < 1) {
876 DEBUG(3,("resolve_wins: WINS server resolution selected and no WINS servers listed.\n"));
877 return NT_STATUS_INVALID_PARAMETER;
880 /* we try a lookup on each of the WINS tags in turn */
881 wins_tags = wins_srv_tags();
884 /* huh? no tags?? give up in disgust */
885 return NT_STATUS_INVALID_PARAMETER;
888 /* the address we will be sending from */
889 src_ip = *interpret_addr2(lp_socket_address());
891 /* in the worst case we will try every wins server with every
893 for (t=0; wins_tags && wins_tags[t]; t++) {
894 int srv_count = wins_srv_count_tag(wins_tags[t]);
895 for (i=0; i<srv_count; i++) {
896 struct in_addr wins_ip;
900 wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
902 if (global_in_nmbd && ismyip_v4(wins_ip)) {
903 /* yikes! we'll loop forever */
907 /* skip any that have been unresponsive lately */
908 if (wins_srv_is_dead(wins_ip, src_ip)) {
912 DEBUG(3,("resolve_wins: using WINS server %s and tag '%s'\n", inet_ntoa(wins_ip), wins_tags[t]));
914 sock = open_socket_in(SOCK_DGRAM, 0, 3, src_ip.s_addr, True);
919 ip_list = name_query(sock,name,name_type, False,
920 True, wins_ip, return_count, &flags,
923 /* exit loop if we got a list of addresses */
931 /* Timed out wating for WINS server to respond. Mark it dead. */
932 wins_srv_died(wins_ip, src_ip);
934 /* The name definately isn't in this
935 group of WINS servers. goto the next group */
941 wins_srv_tags_free(wins_tags);
942 return NT_STATUS_NO_LOGON_SERVERS;
945 status = NT_STATUS_OK;
946 if ( !convert_ip2service( return_iplist, ip_list, *return_count ) )
947 status = NT_STATUS_INVALID_PARAMETER;
949 SAFE_FREE( ip_list );
950 wins_srv_tags_free(wins_tags);
956 /********************************************************
957 Resolve via "lmhosts" method.
958 *********************************************************/
960 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
961 struct ip_service **return_iplist,
965 * "lmhosts" means parse the local lmhosts file.
971 struct in_addr return_ip;
972 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
974 *return_iplist = NULL;
977 DEBUG(3,("resolve_lmhosts: Attempting lmhosts lookup for name %s<0x%x>\n", name, name_type));
979 fp = startlmhosts(dyn_LMHOSTSFILE);
982 return NT_STATUS_NO_SUCH_FILE;
984 while (getlmhostsent(fp, lmhost_name, &name_type2, &return_ip))
987 if (!strequal(name, lmhost_name))
990 if ((name_type2 != -1) && (name_type != name_type2))
993 *return_iplist = SMB_REALLOC_ARRAY((*return_iplist), struct ip_service,
996 if ((*return_iplist) == NULL) {
998 DEBUG(3,("resolve_lmhosts: malloc fail !\n"));
999 return NT_STATUS_NO_MEMORY;
1002 (*return_iplist)[*return_count].ip = return_ip;
1003 (*return_iplist)[*return_count].port = PORT_NONE;
1006 /* we found something */
1007 status = NT_STATUS_OK;
1009 /* Multiple names only for DC lookup */
1010 if (name_type != 0x1c)
1020 /********************************************************
1021 Resolve via "hosts" method.
1022 *********************************************************/
1024 static NTSTATUS resolve_hosts(const char *name, int name_type,
1025 struct ip_service **return_iplist,
1029 * "host" means do a localhost, or dns lookup.
1031 struct addrinfo hints;
1032 struct addrinfo *ailist = NULL;
1033 struct addrinfo *res = NULL;
1037 if ( name_type != 0x20 && name_type != 0x0) {
1038 DEBUG(5, ("resolve_hosts: not appropriate for name type <0x%x>\n", name_type));
1039 return NT_STATUS_INVALID_PARAMETER;
1042 *return_iplist = NULL;
1045 DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n", name, name_type));
1048 /* By default make sure it supports TCP. */
1049 hints.ai_socktype = SOCK_STREAM;
1050 hints.ai_flags = AI_ADDRCONFIG;
1052 ret = getaddrinfo(name,
1057 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1059 gai_strerror(ret) ));
1062 for (res = ailist; res; res = res->ai_next) {
1063 struct in_addr return_ip;
1065 /* IPv4 only for now until I convert ip_service */
1066 if (res->ai_family != AF_INET) {
1069 if (!res->ai_addr) {
1073 putip((char *)&return_ip,
1074 &((struct sockaddr_in *)res->ai_addr)->sin_addr);
1079 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1082 if (!*return_iplist) {
1083 DEBUG(3,("resolve_hosts: malloc fail !\n"));
1084 freeaddrinfo(ailist);
1085 return NT_STATUS_NO_MEMORY;
1087 (*return_iplist)[i].ip = return_ip;
1088 (*return_iplist)[i].port = PORT_NONE;
1091 freeaddrinfo(ailist);
1093 if (*return_count) {
1094 return NT_STATUS_OK;
1096 return NT_STATUS_UNSUCCESSFUL;
1099 /********************************************************
1100 Resolve via "ADS" method.
1101 *********************************************************/
1103 NTSTATUS resolve_ads(const char *name, int name_type,
1104 const char *sitename,
1105 struct ip_service **return_iplist,
1111 struct dns_rr_srv *dcs = NULL;
1115 if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1116 (name_type != 0x1b)) {
1117 return NT_STATUS_INVALID_PARAMETER;
1120 if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1121 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1122 return NT_STATUS_NO_MEMORY;
1125 switch (name_type) {
1127 DEBUG(5,("resolve_ads: Attempting to resolve "
1128 "PDC for %s using DNS\n", name));
1129 status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1133 DEBUG(5,("resolve_ads: Attempting to resolve "
1134 "DCs for %s using DNS\n", name));
1135 status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1139 DEBUG(5,("resolve_ads: Attempting to resolve "
1140 "KDCs for %s using DNS\n", name));
1141 status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1145 status = NT_STATUS_INVALID_PARAMETER;
1149 if ( !NT_STATUS_IS_OK( status ) ) {
1150 talloc_destroy(ctx);
1154 for (i=0;i<numdcs;i++) {
1155 numaddrs += MAX(dcs[i].num_ips,1);
1158 if ( (*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) == NULL ) {
1159 DEBUG(0,("resolve_ads: malloc failed for %d entries\n", numaddrs ));
1160 talloc_destroy(ctx);
1161 return NT_STATUS_NO_MEMORY;
1164 /* now unroll the list of IP addresses */
1169 while ( i < numdcs && (*return_count<numaddrs) ) {
1170 struct ip_service *r = &(*return_iplist)[*return_count];
1172 r->port = dcs[i].port;
1174 /* If we don't have an IP list for a name, lookup it up */
1176 if ( !dcs[i].ips ) {
1177 r->ip = *interpret_addr2(dcs[i].hostname);
1181 /* use the IP addresses from the SRV sresponse */
1183 if ( j >= dcs[i].num_ips ) {
1189 r->ip = dcs[i].ips[j];
1193 /* make sure it is a valid IP. I considered checking the negative
1194 connection cache, but this is the wrong place for it. Maybe only
1195 as a hac. After think about it, if all of the IP addresses retuend
1196 from DNS are dead, what hope does a netbios name lookup have?
1197 The standard reason for falling back to netbios lookups is that
1198 our DNS server doesn't know anything about the DC's -- jerry */
1200 if ( ! is_zero_ip_v4(r->ip) )
1204 talloc_destroy(ctx);
1205 return NT_STATUS_OK;
1208 /*******************************************************************
1209 Internal interface to resolve a name into an IP address.
1210 Use this function if the string is either an IP address, DNS
1211 or host name or NetBIOS name. This uses the name switch in the
1212 smb.conf to determine the order of name resolution.
1214 Added support for ip addr/port to support ADS ldap servers.
1215 the only place we currently care about the port is in the
1216 resolve_hosts() when looking up DC's via SRV RR entries in DNS
1217 **********************************************************************/
1219 NTSTATUS internal_resolve_name(const char *name, int name_type,
1220 const char *sitename,
1221 struct ip_service **return_iplist,
1222 int *return_count, const char *resolve_order)
1224 pstring name_resolve_list;
1227 bool allones = (strcmp(name,"255.255.255.255") == 0);
1228 bool allzeros = (strcmp(name,"0.0.0.0") == 0);
1229 bool is_address = is_ipaddress_v4(name);
1230 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1233 *return_iplist = NULL;
1236 DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1237 name, name_type, sitename ? sitename : NULL));
1239 if (allzeros || allones || is_address) {
1241 if ( (*return_iplist = SMB_MALLOC_P(struct ip_service)) == NULL ) {
1242 DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1243 return NT_STATUS_NO_MEMORY;
1247 /* ignore the port here */
1248 (*return_iplist)->port = PORT_NONE;
1250 /* if it's in the form of an IP address then get the lib to interpret it */
1251 if (((*return_iplist)->ip.s_addr = inet_addr(name)) == 0xFFFFFFFF ){
1252 DEBUG(1,("internal_resolve_name: inet_addr failed on %s\n", name));
1253 SAFE_FREE(*return_iplist);
1254 return NT_STATUS_INVALID_PARAMETER;
1257 (*return_iplist)->ip.s_addr = allones ? 0xFFFFFFFF : 0;
1260 return NT_STATUS_OK;
1263 /* Check name cache */
1265 if (namecache_fetch(name, name_type, return_iplist, return_count)) {
1266 /* This could be a negative response */
1267 if (*return_count > 0) {
1268 return NT_STATUS_OK;
1270 return NT_STATUS_UNSUCCESSFUL;
1274 /* set the name resolution order */
1276 if ( strcmp( resolve_order, "NULL") == 0 ) {
1277 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
1278 return NT_STATUS_INVALID_PARAMETER;
1281 if ( !resolve_order ) {
1282 pstrcpy(name_resolve_list, lp_name_resolve_order());
1284 pstrcpy(name_resolve_list, resolve_order);
1287 if ( !name_resolve_list[0] ) {
1290 ptr = name_resolve_list;
1293 /* iterate through the name resolution backends */
1295 while (next_token(&ptr, tok, LIST_SEP, sizeof(tok))) {
1296 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
1297 status = resolve_hosts(name, name_type, return_iplist,
1299 if (NT_STATUS_IS_OK(status)) {
1302 } else if(strequal( tok, "kdc")) {
1303 /* deal with KDC_NAME_TYPE names here. This will result in a
1304 SRV record lookup */
1305 status = resolve_ads(name, KDC_NAME_TYPE, sitename,
1306 return_iplist, return_count);
1307 if (NT_STATUS_IS_OK(status)) {
1308 /* Ensure we don't namecache this with the KDC port. */
1309 name_type = KDC_NAME_TYPE;
1312 } else if(strequal( tok, "ads")) {
1313 /* deal with 0x1c and 0x1b names here. This will result in a
1314 SRV record lookup */
1315 status = resolve_ads(name, name_type, sitename,
1316 return_iplist, return_count);
1317 if (NT_STATUS_IS_OK(status)) {
1320 } else if(strequal( tok, "lmhosts")) {
1321 status = resolve_lmhosts(name, name_type,
1322 return_iplist, return_count);
1323 if (NT_STATUS_IS_OK(status)) {
1326 } else if(strequal( tok, "wins")) {
1327 /* don't resolve 1D via WINS */
1328 if (name_type != 0x1D) {
1329 status = resolve_wins(name, name_type,
1332 if (NT_STATUS_IS_OK(status)) {
1336 } else if(strequal( tok, "bcast")) {
1337 status = name_resolve_bcast(name, name_type,
1340 if (NT_STATUS_IS_OK(status)) {
1344 DEBUG(0,("resolve_name: unknown name switch type %s\n",
1349 /* All of the resolve_* functions above have returned false. */
1351 SAFE_FREE(*return_iplist);
1354 return NT_STATUS_UNSUCCESSFUL;
1358 /* Remove duplicate entries. Some queries, notably #1c (domain
1359 controllers) return the PDC in iplist[0] and then all domain
1360 controllers including the PDC in iplist[1..n]. Iterating over
1361 the iplist when the PDC is down will cause two sets of timeouts. */
1363 if ( *return_count ) {
1364 *return_count = remove_duplicate_addrs2( *return_iplist, *return_count );
1367 /* Save in name cache */
1368 if ( DEBUGLEVEL >= 100 ) {
1369 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++)
1370 DEBUG(100, ("Storing name %s of type %d (%s:%d)\n", name,
1371 name_type, inet_ntoa((*return_iplist)[i].ip), (*return_iplist)[i].port));
1374 namecache_store(name, name_type, *return_count, *return_iplist);
1376 /* Display some debugging info */
1378 if ( DEBUGLEVEL >= 10 ) {
1379 DEBUG(10, ("internal_resolve_name: returning %d addresses: ", *return_count));
1381 for (i = 0; i < *return_count; i++) {
1382 DEBUGADD(10, ("%s:%d ", inet_ntoa((*return_iplist)[i].ip), (*return_iplist)[i].port));
1390 /********************************************************
1391 Internal interface to resolve a name into one IP address.
1392 Use this function if the string is either an IP address, DNS
1393 or host name or NetBIOS name. This uses the name switch in the
1394 smb.conf to determine the order of name resolution.
1395 *********************************************************/
1397 bool resolve_name(const char *name, struct in_addr *return_ip, int name_type)
1399 struct ip_service *ip_list = NULL;
1400 char *sitename = sitename_fetch(lp_realm()); /* wild guess */
1403 if (is_ipaddress_v4(name)) {
1404 *return_ip = *interpret_addr2(name);
1405 SAFE_FREE(sitename);
1409 if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
1411 lp_name_resolve_order()))) {
1414 /* only return valid addresses for TCP connections */
1415 for (i=0; i<count; i++) {
1416 char *ip_str = inet_ntoa(ip_list[i].ip);
1418 strcmp(ip_str, "255.255.255.255") != 0 &&
1419 strcmp(ip_str, "0.0.0.0") != 0)
1421 *return_ip = ip_list[i].ip;
1423 SAFE_FREE(sitename);
1430 SAFE_FREE(sitename);
1434 /********************************************************
1435 Find the IP address of the master browser or DMB for a workgroup.
1436 *********************************************************/
1438 bool find_master_ip(const char *group, struct in_addr *master_ip)
1440 struct ip_service *ip_list = NULL;
1444 if (lp_disable_netbios()) {
1445 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
1449 status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
1450 lp_name_resolve_order());
1451 if (NT_STATUS_IS_OK(status)) {
1452 *master_ip = ip_list[0].ip;
1457 status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
1458 lp_name_resolve_order());
1459 if (NT_STATUS_IS_OK(status)) {
1460 *master_ip = ip_list[0].ip;
1469 /********************************************************
1470 Get the IP address list of the primary domain controller
1472 *********************************************************/
1474 bool get_pdc_ip(const char *domain, struct in_addr *ip)
1476 struct ip_service *ip_list = NULL;
1478 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1480 /* Look up #1B name */
1482 if (lp_security() == SEC_ADS) {
1483 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1487 if (!NT_STATUS_IS_OK(status) || count == 0) {
1488 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1490 lp_name_resolve_order());
1491 if (!NT_STATUS_IS_OK(status)) {
1496 /* if we get more than 1 IP back we have to assume it is a
1497 multi-homed PDC and not a mess up */
1500 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
1501 sort_ip_list2( ip_list, count );
1504 *ip = ip_list[0].ip;
1511 /* Private enum type for lookups. */
1513 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
1515 /********************************************************
1516 Get the IP address list of the domain controllers for
1518 *********************************************************/
1520 static NTSTATUS get_dc_list(const char *domain, const char *sitename, struct ip_service **ip_list,
1521 int *count, enum dc_lookup_type lookup_type, bool *ordered)
1523 fstring resolve_order;
1524 char *saf_servername;
1530 int num_addresses = 0;
1531 int local_count, i, j;
1532 struct ip_service *return_iplist = NULL;
1533 struct ip_service *auto_ip_list = NULL;
1534 bool done_auto_lookup = False;
1540 /* if we are restricted to solely using DNS for looking
1541 up a domain controller, make sure that host lookups
1542 are enabled for the 'name resolve order'. If host lookups
1543 are disabled and ads_only is True, then set the string to
1546 fstrcpy( resolve_order, lp_name_resolve_order() );
1547 strlower_m( resolve_order );
1548 if ( lookup_type == DC_ADS_ONLY) {
1549 if ( strstr( resolve_order, "host" ) ) {
1550 fstrcpy( resolve_order, "ads" );
1552 /* DNS SRV lookups used by the ads resolver
1553 are already sorted by priority and weight */
1556 fstrcpy( resolve_order, "NULL" );
1558 } else if (lookup_type == DC_KDC_ONLY) {
1559 /* DNS SRV lookups used by the ads/kdc resolver
1560 are already sorted by priority and weight */
1562 fstrcpy( resolve_order, "kdc" );
1565 /* fetch the server we have affinity for. Add the
1566 'password server' list to a search for our domain controllers */
1568 saf_servername = saf_fetch( domain);
1570 if ( strequal(domain, lp_workgroup()) || strequal(domain, lp_realm()) ) {
1571 pstr_sprintf( pserver, "%s, %s",
1572 saf_servername ? saf_servername : "",
1573 lp_passwordserver() );
1575 pstr_sprintf( pserver, "%s, *",
1576 saf_servername ? saf_servername : "" );
1579 SAFE_FREE( saf_servername );
1581 /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
1584 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
1585 return internal_resolve_name(domain, 0x1C, sitename, ip_list,
1586 count, resolve_order);
1589 DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
1592 * if '*' appears in the "password server" list then add
1593 * an auto lookup to the list of manually configured
1594 * DC's. If any DC is listed by name, then the list should be
1595 * considered to be ordered
1599 while (next_token(&p,name,LIST_SEP,sizeof(name))) {
1600 if (strequal(name, "*")) {
1601 status = internal_resolve_name(domain, 0x1C, sitename,
1605 if (NT_STATUS_IS_OK(status)) {
1606 num_addresses += auto_count;
1608 done_auto_lookup = True;
1609 DEBUG(8,("Adding %d DC's from auto lookup\n", auto_count));
1615 /* if we have no addresses and haven't done the auto lookup, then
1616 just return the list of DC's. Or maybe we just failed. */
1618 if ( (num_addresses == 0) ) {
1619 if ( done_auto_lookup ) {
1620 DEBUG(4,("get_dc_list: no servers found\n"));
1621 SAFE_FREE(auto_ip_list);
1622 return NT_STATUS_NO_LOGON_SERVERS;
1624 return internal_resolve_name(domain, 0x1C, sitename, ip_list,
1625 count, resolve_order);
1628 if ( (return_iplist = SMB_MALLOC_ARRAY(struct ip_service, num_addresses)) == NULL ) {
1629 DEBUG(3,("get_dc_list: malloc fail !\n"));
1630 SAFE_FREE(auto_ip_list);
1631 return NT_STATUS_NO_MEMORY;
1637 /* fill in the return list now with real IP's */
1639 while ( (local_count<num_addresses) && next_token(&p,name,LIST_SEP,sizeof(name)) ) {
1640 struct in_addr name_ip;
1642 /* copy any addersses from the auto lookup */
1644 if ( strequal(name, "*") ) {
1645 for ( j=0; j<auto_count; j++ ) {
1646 /* Check for and don't copy any known bad DC IP's. */
1647 if(!NT_STATUS_IS_OK(check_negative_conn_cache(domain,
1648 inet_ntoa(auto_ip_list[j].ip)))) {
1649 DEBUG(5,("get_dc_list: negative entry %s removed from DC list\n",
1650 inet_ntoa(auto_ip_list[j].ip) ));
1653 return_iplist[local_count].ip = auto_ip_list[j].ip;
1654 return_iplist[local_count].port = auto_ip_list[j].port;
1661 /* added support for address:port syntax for ads (not that I think
1662 anyone will ever run the LDAP server in an AD domain on something
1663 other than port 389 */
1665 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
1666 if ( (port_str=strchr(name, ':')) != NULL ) {
1669 port = atoi( port_str );
1672 /* explicit lookup; resolve_name() will handle names & IP addresses */
1673 if ( resolve_name( name, &name_ip, 0x20 ) ) {
1675 /* Check for and don't copy any known bad DC IP's. */
1676 if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain, inet_ntoa(name_ip))) ) {
1677 DEBUG(5,("get_dc_list: negative entry %s removed from DC list\n",name ));
1681 return_iplist[local_count].ip = name_ip;
1682 return_iplist[local_count].port = port;
1688 SAFE_FREE(auto_ip_list);
1690 /* need to remove duplicates in the list if we have any
1691 explicit password servers */
1693 if ( local_count ) {
1694 local_count = remove_duplicate_addrs2( return_iplist, local_count );
1697 if ( DEBUGLEVEL >= 4 ) {
1698 DEBUG(4,("get_dc_list: returning %d ip addresses in an %sordered list\n", local_count,
1699 *ordered ? "":"un"));
1700 DEBUG(4,("get_dc_list: "));
1701 for ( i=0; i<local_count; i++ )
1702 DEBUGADD(4,("%s:%d ", inet_ntoa(return_iplist[i].ip), return_iplist[i].port ));
1706 *ip_list = return_iplist;
1707 *count = local_count;
1709 return ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
1712 /*********************************************************************
1713 Small wrapper function to get the DC list and sort it if neccessary.
1714 *********************************************************************/
1716 NTSTATUS get_sorted_dc_list( const char *domain, const char *sitename, struct ip_service **ip_list, int *count, bool ads_only )
1720 enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
1722 DEBUG(8,("get_sorted_dc_list: attempting lookup for name %s (sitename %s) "
1725 sitename ? sitename : "NULL",
1726 (ads_only ? "ads" : lp_name_resolve_order())));
1729 lookup_type = DC_ADS_ONLY;
1732 status = get_dc_list(domain, sitename, ip_list, count, lookup_type, &ordered);
1733 if (!NT_STATUS_IS_OK(status)) {
1737 /* only sort if we don't already have an ordered list */
1739 sort_ip_list2( *ip_list, *count );
1742 return NT_STATUS_OK;
1745 /*********************************************************************
1746 Get the KDC list - re-use all the logic in get_dc_list.
1747 *********************************************************************/
1749 NTSTATUS get_kdc_list( const char *realm, const char *sitename, struct ip_service **ip_list, int *count)
1757 status = get_dc_list(realm, sitename, ip_list, count, DC_KDC_ONLY, &ordered);
1759 if (!NT_STATUS_IS_OK(status)) {
1763 /* only sort if we don't already have an ordered list */
1765 sort_ip_list2( *ip_list, *count );
1768 return NT_STATUS_OK;