2 Unix SMB/CIFS implementation.
4 Copyright (C) Andrew Tridgell 1994-1998
5 Copyright (C) Jeremy Allison 2007.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 /* nmbd.c sets this to True. */
24 bool global_in_nmbd = False;
26 /****************************
27 * SERVER AFFINITY ROUTINES *
28 ****************************/
30 /* Server affinity is the concept of preferring the last domain
31 controller with whom you had a successful conversation */
33 /****************************************************************************
34 ****************************************************************************/
35 #define SAFKEY_FMT "SAF/DOMAIN/%s"
38 static char *saf_key(const char *domain)
42 asprintf_strupper_m(&keystr, SAFKEY_FMT, domain);
47 /****************************************************************************
48 ****************************************************************************/
50 bool saf_store( const char *domain, const char *servername )
56 if ( !domain || !servername ) {
57 DEBUG(2,("saf_store: "
58 "Refusing to store empty domain or servername!\n"));
62 if ( (strlen(domain) == 0) || (strlen(servername) == 0) ) {
63 DEBUG(0,("saf_store: "
64 "refusing to store 0 length domain or servername!\n"));
68 if ( !gencache_init() )
71 key = saf_key( domain );
72 expire = time( NULL ) + SAF_TTL;
74 DEBUG(10,("saf_store: domain = [%s], server = [%s], expire = [%u]\n",
75 domain, servername, (unsigned int)expire ));
77 ret = gencache_set( key, servername, expire );
84 bool saf_delete( const char *domain )
90 DEBUG(2,("saf_delete: Refusing to delete empty domain\n"));
94 if ( !gencache_init() )
97 key = saf_key(domain);
98 ret = gencache_del(key);
101 DEBUG(10,("saf_delete: domain = [%s]\n", domain ));
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",
137 DEBUG(5,("saf_fetch: Returning \"%s\" for \"%s\" domain\n",
144 /****************************************************************************
145 Generate a random trn_id.
146 ****************************************************************************/
148 static int generate_trn_id(void)
152 generate_random_buffer((uint8 *)&id, sizeof(id));
154 return id % (unsigned)0x7FFF;
157 /****************************************************************************
158 Parse a node status response into an array of structures.
159 ****************************************************************************/
161 static NODE_STATUS_STRUCT *parse_node_status(char *p,
163 struct node_status_extra *extra)
165 NODE_STATUS_STRUCT *ret;
168 *num_names = CVAL(p,0);
173 ret = SMB_MALLOC_ARRAY(NODE_STATUS_STRUCT,*num_names);
178 for (i=0;i< *num_names;i++) {
179 StrnCpy(ret[i].name,p,15);
180 trim_char(ret[i].name,'\0',' ');
181 ret[i].type = CVAL(p,15);
182 ret[i].flags = p[16];
184 DEBUG(10, ("%s#%02x: flags = 0x%02x\n", ret[i].name,
185 ret[i].type, ret[i].flags));
188 * Also, pick up the MAC address ...
191 memcpy(&extra->mac_addr, p, 6); /* Fill in the mac addr */
197 /****************************************************************************
198 Do a NBT node status query on an open socket and return an array of
199 structures holding the returned names or NULL if the query failed.
200 **************************************************************************/
202 NODE_STATUS_STRUCT *node_status_query(int fd,
203 struct nmb_name *name,
204 const struct sockaddr_storage *to_ss,
206 struct node_status_extra *extra)
210 int retry_time = 2000;
212 struct packet_struct p;
213 struct packet_struct *p2;
214 struct nmb_packet *nmb = &p.packet.nmb;
215 NODE_STATUS_STRUCT *ret;
219 if (to_ss->ss_family != AF_INET) {
220 /* Can't do node status to IPv6 */
223 nmb->header.name_trn_id = generate_trn_id();
224 nmb->header.opcode = 0;
225 nmb->header.response = false;
226 nmb->header.nm_flags.bcast = false;
227 nmb->header.nm_flags.recursion_available = false;
228 nmb->header.nm_flags.recursion_desired = false;
229 nmb->header.nm_flags.trunc = false;
230 nmb->header.nm_flags.authoritative = false;
231 nmb->header.rcode = 0;
232 nmb->header.qdcount = 1;
233 nmb->header.ancount = 0;
234 nmb->header.nscount = 0;
235 nmb->header.arcount = 0;
236 nmb->question.question_name = *name;
237 nmb->question.question_type = 0x21;
238 nmb->question.question_class = 0x1;
240 p.ip = ((const struct sockaddr_in *)to_ss)->sin_addr;
243 p.timestamp = time(NULL);
244 p.packet_type = NMB_PACKET;
248 if (!send_packet(&p))
254 struct timeval tval2;
255 GetTimeOfDay(&tval2);
256 if (TvalDiff(&tval,&tval2) > retry_time) {
259 if (!found && !send_packet(&p))
265 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
266 struct nmb_packet *nmb2 = &p2->packet.nmb;
267 debug_nmb_packet(p2);
269 if (nmb2->header.opcode != 0 ||
270 nmb2->header.nm_flags.bcast ||
271 nmb2->header.rcode ||
272 !nmb2->header.ancount ||
273 nmb2->answers->rr_type != 0x21) {
274 /* XXXX what do we do with this? could be a
275 redirect, but we'll discard it for the
281 ret = parse_node_status(&nmb2->answers->rdata[0],
291 /****************************************************************************
292 Find the first type XX name in a node status reply - used for finding
293 a servers name given its IP. Return the matched name in *name.
294 **************************************************************************/
296 bool name_status_find(const char *q_name,
299 const struct sockaddr_storage *to_ss,
302 char addr[INET6_ADDRSTRLEN];
303 struct sockaddr_storage ss;
304 NODE_STATUS_STRUCT *status = NULL;
305 struct nmb_name nname;
310 if (lp_disable_netbios()) {
311 DEBUG(5,("name_status_find(%s#%02x): netbios is disabled\n",
316 print_sockaddr(addr, sizeof(addr), to_ss);
318 DEBUG(10, ("name_status_find: looking up %s#%02x at %s\n", q_name,
321 /* Check the cache first. */
323 if (namecache_status_fetch(q_name, q_type, type, to_ss, name)) {
327 if (to_ss->ss_family != AF_INET) {
328 /* Can't do node status to IPv6 */
332 if (!interpret_string_addr(&ss, lp_socket_address(),
333 AI_NUMERICHOST|AI_PASSIVE)) {
337 sock = open_socket_in(SOCK_DGRAM, 0, 3, &ss, True);
341 /* W2K PDC's seem not to respond to '*'#0. JRA */
342 make_nmb_name(&nname, q_name, q_type);
343 status = node_status_query(sock, &nname, to_ss, &count, NULL);
348 for (i=0;i<count;i++) {
349 if (status[i].type == type)
355 pull_ascii_nstring(name, sizeof(fstring), status[i].name);
357 /* Store the result in the cache. */
358 /* but don't store an entry for 0x1c names here. Here we have
359 a single host and DOMAIN<0x1c> names should be a list of hosts */
361 if ( q_type != 0x1c ) {
362 namecache_status_store(q_name, q_type, type, to_ss, name);
370 DEBUG(10, ("name_status_find: name %sfound", result ? "" : "not "));
373 DEBUGADD(10, (", name %s ip address is %s", name, addr));
381 comparison function used by sort_addr_list
384 static int addr_compare(const struct sockaddr_storage *ss1,
385 const struct sockaddr_storage *ss2)
387 int max_bits1=0, max_bits2=0;
388 int num_interfaces = iface_count();
391 /* Sort IPv6 addresses first. */
392 if (ss1->ss_family != ss2->ss_family) {
393 if (ss2->ss_family == AF_INET) {
400 /* Here we know both addresses are of the same
403 for (i=0;i<num_interfaces;i++) {
404 const struct sockaddr_storage *pss = iface_n_bcast(i);
405 unsigned char *p_ss1 = NULL;
406 unsigned char *p_ss2 = NULL;
407 unsigned char *p_if = NULL;
411 if (pss->ss_family != ss1->ss_family) {
412 /* Ignore interfaces of the wrong type. */
415 if (pss->ss_family == AF_INET) {
416 p_if = (unsigned char *)
417 &((const struct sockaddr_in *)pss)->sin_addr;
418 p_ss1 = (unsigned char *)
419 &((const struct sockaddr_in *)ss1)->sin_addr;
420 p_ss2 = (unsigned char *)
421 &((const struct sockaddr_in *)ss2)->sin_addr;
424 #if defined(HAVE_IPV6)
425 if (pss->ss_family == AF_INET6) {
426 p_if = (unsigned char *)
427 &((const struct sockaddr_in6 *)pss)->sin6_addr;
428 p_ss1 = (unsigned char *)
429 &((const struct sockaddr_in6 *)ss1)->sin6_addr;
430 p_ss2 = (unsigned char *)
431 &((const struct sockaddr_in6 *)ss2)->sin6_addr;
435 if (!p_ss1 || !p_ss2 || !p_if || len == 0) {
438 bits1 = matching_len_bits(p_ss1, p_if, len);
439 bits2 = matching_len_bits(p_ss2, p_if, len);
440 max_bits1 = MAX(bits1, max_bits1);
441 max_bits2 = MAX(bits2, max_bits2);
444 /* Bias towards directly reachable IPs */
445 if (iface_local(ss1)) {
446 if (ss1->ss_family == AF_INET) {
452 if (iface_local(ss2)) {
453 if (ss2->ss_family == AF_INET) {
459 return max_bits2 - max_bits1;
462 /*******************************************************************
463 compare 2 ldap IPs by nearness to our interfaces - used in qsort
464 *******************************************************************/
466 int ip_service_compare(struct ip_service *ss1, struct ip_service *ss2)
470 if ((result = addr_compare(&ss1->ss, &ss2->ss)) != 0) {
474 if (ss1->port > ss2->port) {
478 if (ss1->port < ss2->port) {
486 sort an IP list so that names that are close to one of our interfaces
487 are at the top. This prevents the problem where a WINS server returns an IP
488 that is not reachable from our subnet as the first match
491 static void sort_addr_list(struct sockaddr_storage *sslist, int count)
497 qsort(sslist, count, sizeof(struct sockaddr_storage),
498 QSORT_CAST addr_compare);
501 static void sort_service_list(struct ip_service *servlist, int count)
507 qsort(servlist, count, sizeof(struct ip_service),
508 QSORT_CAST ip_service_compare);
511 /**********************************************************************
512 Remove any duplicate address/port pairs in the list
513 *********************************************************************/
515 static int remove_duplicate_addrs2(struct ip_service *iplist, int count )
519 DEBUG(10,("remove_duplicate_addrs2: "
520 "looking for duplicate address/port pairs\n"));
522 /* one loop to remove duplicates */
523 for ( i=0; i<count; i++ ) {
524 if ( is_zero_addr(&iplist[i].ss)) {
528 for ( j=i+1; j<count; j++ ) {
529 if (addr_equal(&iplist[i].ss, &iplist[j].ss) &&
530 iplist[i].port == iplist[j].port) {
531 zero_addr(&iplist[j].ss);
536 /* one loop to clean up any holes we left */
537 /* first ip should never be a zero_ip() */
538 for (i = 0; i<count; ) {
539 if (is_zero_addr(&iplist[i].ss) ) {
541 memmove(&iplist[i], &iplist[i+1],
542 (count - i - 1)*sizeof(iplist[i]));
553 /****************************************************************************
554 Do a netbios name query to find someones IP.
555 Returns an array of IP addresses or NULL if none.
556 *count will be set to the number of addresses returned.
557 *timed_out is set if we failed by timing out
558 ****************************************************************************/
560 struct sockaddr_storage *name_query(int fd,
565 const struct sockaddr_storage *to_ss,
572 int retry_time = bcast?250:2000;
574 struct packet_struct p;
575 struct packet_struct *p2;
576 struct nmb_packet *nmb = &p.packet.nmb;
577 struct sockaddr_storage *ss_list = NULL;
579 if (lp_disable_netbios()) {
580 DEBUG(5,("name_query(%s#%02x): netbios is disabled\n",
585 if (to_ss->ss_family != AF_INET) {
593 memset((char *)&p,'\0',sizeof(p));
597 nmb->header.name_trn_id = generate_trn_id();
598 nmb->header.opcode = 0;
599 nmb->header.response = false;
600 nmb->header.nm_flags.bcast = bcast;
601 nmb->header.nm_flags.recursion_available = false;
602 nmb->header.nm_flags.recursion_desired = recurse;
603 nmb->header.nm_flags.trunc = false;
604 nmb->header.nm_flags.authoritative = false;
605 nmb->header.rcode = 0;
606 nmb->header.qdcount = 1;
607 nmb->header.ancount = 0;
608 nmb->header.nscount = 0;
609 nmb->header.arcount = 0;
611 make_nmb_name(&nmb->question.question_name,name,name_type);
613 nmb->question.question_type = 0x20;
614 nmb->question.question_class = 0x1;
616 p.ip = ((struct sockaddr_in *)to_ss)->sin_addr;
619 p.timestamp = time(NULL);
620 p.packet_type = NMB_PACKET;
624 if (!send_packet(&p))
630 struct timeval tval2;
632 GetTimeOfDay(&tval2);
633 if (TvalDiff(&tval,&tval2) > retry_time) {
636 if (!found && !send_packet(&p))
642 if ((p2=receive_nmb_packet(fd,90,nmb->header.name_trn_id))) {
643 struct nmb_packet *nmb2 = &p2->packet.nmb;
644 debug_nmb_packet(p2);
646 /* If we get a Negative Name Query Response from a WINS
647 * server, we should report it and give up.
649 if( 0 == nmb2->header.opcode /* A query response */
650 && !(bcast) /* from a WINS server */
651 && nmb2->header.rcode /* Error returned */
654 if( DEBUGLVL( 3 ) ) {
655 /* Only executed if DEBUGLEVEL >= 3 */
656 dbgtext( "Negative name query "
657 "response, rcode 0x%02x: ",
658 nmb2->header.rcode );
659 switch( nmb2->header.rcode ) {
662 "was invalidly formatted.\n" );
665 dbgtext( "Problem with NBNS, "
666 "cannot process name.\n");
669 dbgtext( "The name requested "
670 "does not exist.\n" );
673 dbgtext( "Unsupported request "
677 dbgtext( "Query refused "
681 dbgtext( "Unrecognized error "
690 if (nmb2->header.opcode != 0 ||
691 nmb2->header.nm_flags.bcast ||
692 nmb2->header.rcode ||
693 !nmb2->header.ancount) {
695 * XXXX what do we do with this? Could be a
696 * redirect, but we'll discard it for the
703 ss_list = SMB_REALLOC_ARRAY(ss_list,
704 struct sockaddr_storage,
706 nmb2->answers->rdlength/6);
709 DEBUG(0,("name_query: Realloc failed.\n"));
714 DEBUG(2,("Got a positive name query response "
718 for (i=0;i<nmb2->answers->rdlength/6;i++) {
720 putip((char *)&ip,&nmb2->answers->rdata[2+i*6]);
721 in_addr_to_sockaddr_storage(&ss_list[(*count)],
723 DEBUGADD(2,("%s ",inet_ntoa(ip)));
730 /* We add the flags back ... */
731 if (nmb2->header.response)
732 (*flags) |= NM_FLAGS_RS;
733 if (nmb2->header.nm_flags.authoritative)
734 (*flags) |= NM_FLAGS_AA;
735 if (nmb2->header.nm_flags.trunc)
736 (*flags) |= NM_FLAGS_TC;
737 if (nmb2->header.nm_flags.recursion_desired)
738 (*flags) |= NM_FLAGS_RD;
739 if (nmb2->header.nm_flags.recursion_available)
740 (*flags) |= NM_FLAGS_RA;
741 if (nmb2->header.nm_flags.bcast)
742 (*flags) |= NM_FLAGS_B;
745 * If we're doing a unicast lookup we only
746 * expect one reply. Don't wait the full 2
747 * seconds if we got one. JRA.
754 /* only set timed_out if we didn't fund what we where looking for*/
756 if ( !found && timed_out ) {
760 /* sort the ip list so we choose close servers first if possible */
761 sort_addr_list(ss_list, *count);
766 /********************************************************
767 Start parsing the lmhosts file.
768 *********************************************************/
770 XFILE *startlmhosts(const char *fname)
772 XFILE *fp = x_fopen(fname,O_RDONLY, 0);
774 DEBUG(4,("startlmhosts: Can't open lmhosts file %s. "
776 fname, strerror(errno)));
782 /********************************************************
783 Parse the next line in the lmhosts file.
784 *********************************************************/
786 bool getlmhostsent(TALLOC_CTX *ctx, XFILE *fp, char **pp_name, int *name_type,
787 struct sockaddr_storage *pss)
793 while(!x_feof(fp) && !x_ferror(fp)) {
804 if (!fgets_slash(line,sizeof(line),fp)) {
814 if (next_token_talloc(ctx, &ptr, &ip, NULL))
816 if (next_token_talloc(ctx, &ptr, &name, NULL))
818 if (next_token_talloc(ctx, &ptr, &flags, NULL))
820 if (next_token_talloc(ctx, &ptr, &extra, NULL))
826 if (count > 0 && count < 2) {
827 DEBUG(0,("getlmhostsent: Ill formed hosts line [%s]\n",
833 DEBUG(0,("getlmhostsent: too many columns "
834 "in lmhosts file (obsolete syntax)\n"));
838 DEBUG(4, ("getlmhostsent: lmhost entry: %s %s %s\n",
841 if (strchr_m(flags,'G') || strchr_m(flags,'S')) {
842 DEBUG(0,("getlmhostsent: group flag "
843 "in lmhosts ignored (obsolete)\n"));
847 if (!interpret_string_addr(pss, ip, AI_NUMERICHOST)) {
848 DEBUG(0,("getlmhostsent: invalid address "
852 /* Extra feature. If the name ends in '#XX',
853 * where XX is a hex number, then only add that name type. */
854 if((ptr1 = strchr_m(name, '#')) != NULL) {
858 *name_type = (int)strtol(ptr1, &endptr, 16);
859 if(!*ptr1 || (endptr == ptr1)) {
860 DEBUG(0,("getlmhostsent: invalid name "
861 "%s containing '#'.\n", name));
865 *(--ptr1) = '\0'; /* Truncate at the '#' */
868 *pp_name = talloc_strdup(ctx, name);
878 /********************************************************
879 Finish parsing the lmhosts file.
880 *********************************************************/
882 void endlmhosts(XFILE *fp)
887 /********************************************************
888 convert an array if struct sockaddr_storage to struct ip_service
889 return false on failure. Port is set to PORT_NONE;
890 *********************************************************/
892 static bool convert_ss2service(struct ip_service **return_iplist,
893 const struct sockaddr_storage *ss_list,
898 if ( count==0 || !ss_list )
901 /* copy the ip address; port will be PORT_NONE */
902 if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, count)) ==
904 DEBUG(0,("convert_ip2service: malloc failed "
905 "for %d enetries!\n", count ));
909 for ( i=0; i<count; i++ ) {
910 (*return_iplist)[i].ss = ss_list[i];
911 (*return_iplist)[i].port = PORT_NONE;
917 /********************************************************
918 Resolve via "bcast" method.
919 *********************************************************/
921 NTSTATUS name_resolve_bcast(const char *name,
923 struct ip_service **return_iplist,
927 int num_interfaces = iface_count();
928 struct sockaddr_storage *ss_list;
929 struct sockaddr_storage ss;
932 if (lp_disable_netbios()) {
933 DEBUG(5,("name_resolve_bcast(%s#%02x): netbios is disabled\n",
935 return NT_STATUS_INVALID_PARAMETER;
938 *return_iplist = NULL;
942 * "bcast" means do a broadcast lookup on all the local interfaces.
945 DEBUG(3,("name_resolve_bcast: Attempting broadcast lookup "
946 "for name %s<0x%x>\n", name, name_type));
948 if (!interpret_string_addr(&ss, lp_socket_address(),
949 AI_NUMERICHOST|AI_PASSIVE)) {
953 sock = open_socket_in( SOCK_DGRAM, 0, 3, &ss, true );
955 return NT_STATUS_UNSUCCESSFUL;
958 set_socket_options(sock,"SO_BROADCAST");
960 * Lookup the name on all the interfaces, return on
961 * the first successful match.
963 for( i = num_interfaces-1; i >= 0; i--) {
964 const struct sockaddr_storage *pss = iface_n_bcast(i);
967 /* Done this way to fix compiler error on IRIX 5.x */
971 ss_list = name_query(sock, name, name_type, true,
972 true, pss, return_count, &flags, NULL);
978 /* failed - no response */
981 return NT_STATUS_UNSUCCESSFUL;
985 status = NT_STATUS_OK;
986 if (!convert_ss2service(return_iplist, ss_list, *return_count) )
987 status = NT_STATUS_INVALID_PARAMETER;
994 /********************************************************
995 Resolve via "wins" method.
996 *********************************************************/
998 NTSTATUS resolve_wins(const char *name,
1000 struct ip_service **return_iplist,
1005 struct sockaddr_storage src_ss, *ss_list = NULL;
1006 struct in_addr src_ip;
1009 if (lp_disable_netbios()) {
1010 DEBUG(5,("resolve_wins(%s#%02x): netbios is disabled\n",
1012 return NT_STATUS_INVALID_PARAMETER;
1015 *return_iplist = NULL;
1018 DEBUG(3,("resolve_wins: Attempting wins lookup for name %s<0x%x>\n",
1021 if (wins_srv_count() < 1) {
1022 DEBUG(3,("resolve_wins: WINS server resolution selected "
1023 "and no WINS servers listed.\n"));
1024 return NT_STATUS_INVALID_PARAMETER;
1027 /* we try a lookup on each of the WINS tags in turn */
1028 wins_tags = wins_srv_tags();
1031 /* huh? no tags?? give up in disgust */
1032 return NT_STATUS_INVALID_PARAMETER;
1035 /* the address we will be sending from */
1036 if (!interpret_string_addr(&src_ss, lp_socket_address(),
1037 AI_NUMERICHOST|AI_PASSIVE)) {
1041 if (src_ss.ss_family != AF_INET) {
1042 char addr[INET6_ADDRSTRLEN];
1043 print_sockaddr(addr, sizeof(addr), &src_ss);
1044 DEBUG(3,("resolve_wins: cannot receive WINS replies "
1045 "on IPv6 address %s\n",
1047 return NT_STATUS_INVALID_PARAMETER;
1050 src_ip = ((struct sockaddr_in *)&src_ss)->sin_addr;
1052 /* in the worst case we will try every wins server with every
1054 for (t=0; wins_tags && wins_tags[t]; t++) {
1055 int srv_count = wins_srv_count_tag(wins_tags[t]);
1056 for (i=0; i<srv_count; i++) {
1057 struct sockaddr_storage wins_ss;
1058 struct in_addr wins_ip;
1062 wins_ip = wins_srv_ip_tag(wins_tags[t], src_ip);
1064 if (global_in_nmbd && ismyip_v4(wins_ip)) {
1065 /* yikes! we'll loop forever */
1069 /* skip any that have been unresponsive lately */
1070 if (wins_srv_is_dead(wins_ip, src_ip)) {
1074 DEBUG(3,("resolve_wins: using WINS server %s "
1076 inet_ntoa(wins_ip), wins_tags[t]));
1078 sock = open_socket_in(SOCK_DGRAM, 0, 3, &src_ss, true);
1083 in_addr_to_sockaddr_storage(&wins_ss, wins_ip);
1084 ss_list = name_query(sock,
1094 /* exit loop if we got a list of addresses */
1102 /* Timed out wating for WINS server to respond.
1104 wins_srv_died(wins_ip, src_ip);
1106 /* The name definately isn't in this
1107 group of WINS servers.
1108 goto the next group */
1114 wins_srv_tags_free(wins_tags);
1115 return NT_STATUS_NO_LOGON_SERVERS;
1119 status = NT_STATUS_OK;
1120 if (!convert_ss2service(return_iplist, ss_list, *return_count))
1121 status = NT_STATUS_INVALID_PARAMETER;
1124 wins_srv_tags_free(wins_tags);
1130 /********************************************************
1131 Resolve via "lmhosts" method.
1132 *********************************************************/
1134 static NTSTATUS resolve_lmhosts(const char *name, int name_type,
1135 struct ip_service **return_iplist,
1139 * "lmhosts" means parse the local lmhosts file.
1143 char *lmhost_name = NULL;
1145 struct sockaddr_storage return_ss;
1146 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1147 TALLOC_CTX *ctx = NULL;
1149 *return_iplist = NULL;
1152 DEBUG(3,("resolve_lmhosts: "
1153 "Attempting lmhosts lookup for name %s<0x%x>\n",
1156 fp = startlmhosts(get_dyn_LMHOSTSFILE());
1159 return NT_STATUS_NO_SUCH_FILE;
1161 ctx = talloc_init("resolve_lmhosts");
1164 return NT_STATUS_NO_MEMORY;
1167 while (getlmhostsent(ctx, fp, &lmhost_name, &name_type2, &return_ss)) {
1169 if (!strequal(name, lmhost_name)) {
1170 TALLOC_FREE(lmhost_name);
1174 if ((name_type2 != -1) && (name_type != name_type2)) {
1175 TALLOC_FREE(lmhost_name);
1179 *return_iplist = SMB_REALLOC_ARRAY((*return_iplist),
1183 if ((*return_iplist) == NULL) {
1186 DEBUG(3,("resolve_lmhosts: malloc fail !\n"));
1187 return NT_STATUS_NO_MEMORY;
1190 (*return_iplist)[*return_count].ss = return_ss;
1191 (*return_iplist)[*return_count].port = PORT_NONE;
1194 /* we found something */
1195 status = NT_STATUS_OK;
1197 /* Multiple names only for DC lookup */
1198 if (name_type != 0x1c)
1208 /********************************************************
1209 Resolve via "hosts" method.
1210 *********************************************************/
1212 static NTSTATUS resolve_hosts(const char *name, int name_type,
1213 struct ip_service **return_iplist,
1217 * "host" means do a localhost, or dns lookup.
1219 struct addrinfo hints;
1220 struct addrinfo *ailist = NULL;
1221 struct addrinfo *res = NULL;
1225 if ( name_type != 0x20 && name_type != 0x0) {
1226 DEBUG(5, ("resolve_hosts: not appropriate "
1227 "for name type <0x%x>\n",
1229 return NT_STATUS_INVALID_PARAMETER;
1232 *return_iplist = NULL;
1235 DEBUG(3,("resolve_hosts: Attempting host lookup for name %s<0x%x>\n",
1239 /* By default make sure it supports TCP. */
1240 hints.ai_socktype = SOCK_STREAM;
1241 hints.ai_flags = AI_ADDRCONFIG;
1243 #if !defined(HAVE_IPV6)
1244 /* Unless we have IPv6, we really only want IPv4 addresses back. */
1245 hints.ai_family = AF_INET;
1248 ret = getaddrinfo(name,
1253 DEBUG(3,("resolve_hosts: getaddrinfo failed for name %s [%s]\n",
1255 gai_strerror(ret) ));
1258 for (res = ailist; res; res = res->ai_next) {
1259 struct sockaddr_storage ss;
1261 if (!res->ai_addr || res->ai_addrlen == 0) {
1265 memset(&ss, '\0', sizeof(ss));
1266 memcpy(&ss, res->ai_addr, res->ai_addrlen);
1270 *return_iplist = SMB_REALLOC_ARRAY(*return_iplist,
1273 if (!*return_iplist) {
1274 DEBUG(3,("resolve_hosts: malloc fail !\n"));
1275 freeaddrinfo(ailist);
1276 return NT_STATUS_NO_MEMORY;
1278 (*return_iplist)[i].ss = ss;
1279 (*return_iplist)[i].port = PORT_NONE;
1283 freeaddrinfo(ailist);
1285 if (*return_count) {
1286 return NT_STATUS_OK;
1288 return NT_STATUS_UNSUCCESSFUL;
1291 /********************************************************
1292 Resolve via "ADS" method.
1293 *********************************************************/
1295 NTSTATUS resolve_ads(const char *name,
1297 const char *sitename,
1298 struct ip_service **return_iplist,
1304 struct dns_rr_srv *dcs = NULL;
1308 if ((name_type != 0x1c) && (name_type != KDC_NAME_TYPE) &&
1309 (name_type != 0x1b)) {
1310 return NT_STATUS_INVALID_PARAMETER;
1313 if ( (ctx = talloc_init("resolve_ads")) == NULL ) {
1314 DEBUG(0,("resolve_ads: talloc_init() failed!\n"));
1315 return NT_STATUS_NO_MEMORY;
1318 /* The DNS code needs fixing to find IPv6 addresses... JRA. */
1320 switch (name_type) {
1322 DEBUG(5,("resolve_ads: Attempting to resolve "
1323 "PDC for %s using DNS\n", name));
1324 status = ads_dns_query_pdc(ctx, name, &dcs, &numdcs);
1328 DEBUG(5,("resolve_ads: Attempting to resolve "
1329 "DCs for %s using DNS\n", name));
1330 status = ads_dns_query_dcs(ctx, name, sitename, &dcs,
1334 DEBUG(5,("resolve_ads: Attempting to resolve "
1335 "KDCs for %s using DNS\n", name));
1336 status = ads_dns_query_kdcs(ctx, name, sitename, &dcs,
1340 status = NT_STATUS_INVALID_PARAMETER;
1344 if ( !NT_STATUS_IS_OK( status ) ) {
1345 talloc_destroy(ctx);
1349 for (i=0;i<numdcs;i++) {
1350 numaddrs += MAX(dcs[i].num_ips,1);
1353 if ((*return_iplist = SMB_MALLOC_ARRAY(struct ip_service, numaddrs)) ==
1355 DEBUG(0,("resolve_ads: malloc failed for %d entries\n",
1357 talloc_destroy(ctx);
1358 return NT_STATUS_NO_MEMORY;
1361 /* now unroll the list of IP addresses */
1366 while ( i < numdcs && (*return_count<numaddrs) ) {
1367 struct ip_service *r = &(*return_iplist)[*return_count];
1369 r->port = dcs[i].port;
1371 /* If we don't have an IP list for a name, lookup it up */
1374 interpret_string_addr(&r->ss, dcs[i].hostname, 0);
1378 /* use the IP addresses from the SRV sresponse */
1380 if ( j >= dcs[i].num_ips ) {
1386 r->ss = dcs[i].ss_s[j];
1390 /* make sure it is a valid IP. I considered checking the
1391 * negative connection cache, but this is the wrong place
1392 * for it. Maybe only as a hack. After think about it, if
1393 * all of the IP addresses returned from DNS are dead, what
1394 * hope does a netbios name lookup have ? The standard reason
1395 * for falling back to netbios lookups is that our DNS server
1396 * doesn't know anything about the DC's -- jerry */
1398 if (!is_zero_addr(&r->ss)) {
1403 talloc_destroy(ctx);
1404 return NT_STATUS_OK;
1407 /*******************************************************************
1408 Internal interface to resolve a name into an IP address.
1409 Use this function if the string is either an IP address, DNS
1410 or host name or NetBIOS name. This uses the name switch in the
1411 smb.conf to determine the order of name resolution.
1413 Added support for ip addr/port to support ADS ldap servers.
1414 the only place we currently care about the port is in the
1415 resolve_hosts() when looking up DC's via SRV RR entries in DNS
1416 **********************************************************************/
1418 NTSTATUS internal_resolve_name(const char *name,
1420 const char *sitename,
1421 struct ip_service **return_iplist,
1423 const char *resolve_order)
1425 const char *name_resolve_list;
1428 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1430 TALLOC_CTX *frame = NULL;
1432 *return_iplist = NULL;
1435 DEBUG(10, ("internal_resolve_name: looking up %s#%x (sitename %s)\n",
1436 name, name_type, sitename ? sitename : NULL));
1438 if (is_ipaddress(name)) {
1439 if ((*return_iplist = SMB_MALLOC_P(struct ip_service)) ==
1441 DEBUG(0,("internal_resolve_name: malloc fail !\n"));
1442 return NT_STATUS_NO_MEMORY;
1445 /* ignore the port here */
1446 (*return_iplist)->port = PORT_NONE;
1448 /* if it's in the form of an IP address then get the lib to interpret it */
1449 if (!interpret_string_addr(&(*return_iplist)->ss,
1450 name, AI_NUMERICHOST)) {
1451 DEBUG(1,("internal_resolve_name: interpret_string_addr "
1454 SAFE_FREE(*return_iplist);
1455 return NT_STATUS_INVALID_PARAMETER;
1458 return NT_STATUS_OK;
1461 /* Check name cache */
1463 if (namecache_fetch(name, name_type, return_iplist, return_count)) {
1464 /* This could be a negative response */
1465 if (*return_count > 0) {
1466 return NT_STATUS_OK;
1468 return NT_STATUS_UNSUCCESSFUL;
1472 /* set the name resolution order */
1474 if (strcmp( resolve_order, "NULL") == 0) {
1475 DEBUG(8,("internal_resolve_name: all lookups disabled\n"));
1476 return NT_STATUS_INVALID_PARAMETER;
1479 if (!resolve_order) {
1480 name_resolve_list = lp_name_resolve_order();
1482 name_resolve_list = resolve_order;
1485 if (!name_resolve_list[0]) {
1488 ptr = name_resolve_list;
1491 /* iterate through the name resolution backends */
1493 frame = talloc_stackframe();
1494 while (next_token_talloc(frame, &ptr, &tok, LIST_SEP)) {
1495 if((strequal(tok, "host") || strequal(tok, "hosts"))) {
1496 status = resolve_hosts(name, name_type, return_iplist,
1498 if (NT_STATUS_IS_OK(status)) {
1501 } else if(strequal( tok, "kdc")) {
1502 /* deal with KDC_NAME_TYPE names here.
1503 * This will result in a SRV record lookup */
1504 status = resolve_ads(name, KDC_NAME_TYPE, sitename,
1505 return_iplist, return_count);
1506 if (NT_STATUS_IS_OK(status)) {
1507 /* Ensure we don't namecache
1508 * this with the KDC port. */
1509 name_type = KDC_NAME_TYPE;
1512 } else if(strequal( tok, "ads")) {
1513 /* deal with 0x1c and 0x1b names here.
1514 * This will result in a SRV record lookup */
1515 status = resolve_ads(name, name_type, sitename,
1516 return_iplist, return_count);
1517 if (NT_STATUS_IS_OK(status)) {
1520 } else if(strequal( tok, "lmhosts")) {
1521 status = resolve_lmhosts(name, name_type,
1522 return_iplist, return_count);
1523 if (NT_STATUS_IS_OK(status)) {
1526 } else if(strequal( tok, "wins")) {
1527 /* don't resolve 1D via WINS */
1528 if (name_type != 0x1D) {
1529 status = resolve_wins(name, name_type,
1532 if (NT_STATUS_IS_OK(status)) {
1536 } else if(strequal( tok, "bcast")) {
1537 status = name_resolve_bcast(name, name_type,
1540 if (NT_STATUS_IS_OK(status)) {
1544 DEBUG(0,("resolve_name: unknown name switch type %s\n",
1549 /* All of the resolve_* functions above have returned false. */
1552 SAFE_FREE(*return_iplist);
1555 return NT_STATUS_UNSUCCESSFUL;
1559 /* Remove duplicate entries. Some queries, notably #1c (domain
1560 controllers) return the PDC in iplist[0] and then all domain
1561 controllers including the PDC in iplist[1..n]. Iterating over
1562 the iplist when the PDC is down will cause two sets of timeouts. */
1564 if ( *return_count ) {
1565 *return_count = remove_duplicate_addrs2(*return_iplist,
1569 /* Save in name cache */
1570 if ( DEBUGLEVEL >= 100 ) {
1571 for (i = 0; i < *return_count && DEBUGLEVEL == 100; i++) {
1572 char addr[INET6_ADDRSTRLEN];
1573 print_sockaddr(addr, sizeof(addr),
1574 &(*return_iplist)[i].ss);
1575 DEBUG(100, ("Storing name %s of type %d (%s:%d)\n",
1579 (*return_iplist)[i].port));
1583 namecache_store(name, name_type, *return_count, *return_iplist);
1585 /* Display some debugging info */
1587 if ( DEBUGLEVEL >= 10 ) {
1588 DEBUG(10, ("internal_resolve_name: returning %d addresses: ",
1591 for (i = 0; i < *return_count; i++) {
1592 char addr[INET6_ADDRSTRLEN];
1593 print_sockaddr(addr, sizeof(addr),
1594 &(*return_iplist)[i].ss);
1595 DEBUGADD(10, ("%s:%d ",
1597 (*return_iplist)[i].port));
1606 /********************************************************
1607 Internal interface to resolve a name into one IP address.
1608 Use this function if the string is either an IP address, DNS
1609 or host name or NetBIOS name. This uses the name switch in the
1610 smb.conf to determine the order of name resolution.
1611 *********************************************************/
1613 bool resolve_name(const char *name,
1614 struct sockaddr_storage *return_ss,
1617 struct ip_service *ss_list = NULL;
1618 char *sitename = NULL;
1621 if (is_ipaddress(name)) {
1622 return interpret_string_addr(return_ss, name, AI_NUMERICHOST);
1625 sitename = sitename_fetch(lp_realm()); /* wild guess */
1627 if (NT_STATUS_IS_OK(internal_resolve_name(name, name_type, sitename,
1629 lp_name_resolve_order()))) {
1632 /* only return valid addresses for TCP connections */
1633 for (i=0; i<count; i++) {
1634 if (!is_zero_addr(&ss_list[i].ss) &&
1635 !is_broadcast_addr(&ss_list[i].ss)) {
1636 *return_ss = ss_list[i].ss;
1638 SAFE_FREE(sitename);
1645 SAFE_FREE(sitename);
1649 /********************************************************
1650 Find the IP address of the master browser or DMB for a workgroup.
1651 *********************************************************/
1653 bool find_master_ip(const char *group, struct sockaddr_storage *master_ss)
1655 struct ip_service *ip_list = NULL;
1659 if (lp_disable_netbios()) {
1660 DEBUG(5,("find_master_ip(%s): netbios is disabled\n", group));
1664 status = internal_resolve_name(group, 0x1D, NULL, &ip_list, &count,
1665 lp_name_resolve_order());
1666 if (NT_STATUS_IS_OK(status)) {
1667 *master_ss = ip_list[0].ss;
1672 status = internal_resolve_name(group, 0x1B, NULL, &ip_list, &count,
1673 lp_name_resolve_order());
1674 if (NT_STATUS_IS_OK(status)) {
1675 *master_ss = ip_list[0].ss;
1684 /********************************************************
1685 Get the IP address list of the primary domain controller
1687 *********************************************************/
1689 bool get_pdc_ip(const char *domain, struct sockaddr_storage *pss)
1691 struct ip_service *ip_list = NULL;
1693 NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1695 /* Look up #1B name */
1697 if (lp_security() == SEC_ADS) {
1698 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1702 if (!NT_STATUS_IS_OK(status) || count == 0) {
1703 status = internal_resolve_name(domain, 0x1b, NULL, &ip_list,
1705 lp_name_resolve_order());
1706 if (!NT_STATUS_IS_OK(status)) {
1711 /* if we get more than 1 IP back we have to assume it is a
1712 multi-homed PDC and not a mess up */
1715 DEBUG(6,("get_pdc_ip: PDC has %d IP addresses!\n", count));
1716 sort_service_list(ip_list, count);
1719 *pss = ip_list[0].ss;
1724 /* Private enum type for lookups. */
1726 enum dc_lookup_type { DC_NORMAL_LOOKUP, DC_ADS_ONLY, DC_KDC_ONLY };
1728 /********************************************************
1729 Get the IP address list of the domain controllers for
1731 *********************************************************/
1733 static NTSTATUS get_dc_list(const char *domain,
1734 const char *sitename,
1735 struct ip_service **ip_list,
1737 enum dc_lookup_type lookup_type,
1740 char *resolve_order = NULL;
1741 char *saf_servername = NULL;
1742 char *pserver = NULL;
1744 char *port_str = NULL;
1747 int num_addresses = 0;
1748 int local_count, i, j;
1749 struct ip_service *return_iplist = NULL;
1750 struct ip_service *auto_ip_list = NULL;
1751 bool done_auto_lookup = false;
1754 TALLOC_CTX *ctx = talloc_init("get_dc_list");
1757 return NT_STATUS_NO_MEMORY;
1762 /* if we are restricted to solely using DNS for looking
1763 up a domain controller, make sure that host lookups
1764 are enabled for the 'name resolve order'. If host lookups
1765 are disabled and ads_only is True, then set the string to
1768 resolve_order = talloc_strdup(ctx, lp_name_resolve_order());
1769 if (!resolve_order) {
1770 status = NT_STATUS_NO_MEMORY;
1773 strlower_m(resolve_order);
1774 if (lookup_type == DC_ADS_ONLY) {
1775 if (strstr( resolve_order, "host")) {
1776 resolve_order = talloc_strdup(ctx, "ads");
1778 /* DNS SRV lookups used by the ads resolver
1779 are already sorted by priority and weight */
1782 resolve_order = talloc_strdup(ctx, "NULL");
1784 } else if (lookup_type == DC_KDC_ONLY) {
1785 /* DNS SRV lookups used by the ads/kdc resolver
1786 are already sorted by priority and weight */
1788 resolve_order = talloc_strdup(ctx, "kdc");
1790 if (!resolve_order) {
1791 status = NT_STATUS_NO_MEMORY;
1795 /* fetch the server we have affinity for. Add the
1796 'password server' list to a search for our domain controllers */
1798 saf_servername = saf_fetch( domain);
1800 if (strequal(domain, lp_workgroup()) || strequal(domain, lp_realm())) {
1801 pserver = talloc_asprintf(NULL, "%s, %s",
1802 saf_servername ? saf_servername : "",
1803 lp_passwordserver());
1805 pserver = talloc_asprintf(NULL, "%s, *",
1806 saf_servername ? saf_servername : "");
1809 SAFE_FREE(saf_servername);
1811 status = NT_STATUS_NO_MEMORY;
1815 /* if we are starting from scratch, just lookup DOMAIN<0x1c> */
1818 DEBUG(10,("get_dc_list: no preferred domain controllers.\n"));
1819 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
1820 count, resolve_order);
1824 DEBUG(3,("get_dc_list: preferred server list: \"%s\"\n", pserver ));
1827 * if '*' appears in the "password server" list then add
1828 * an auto lookup to the list of manually configured
1829 * DC's. If any DC is listed by name, then the list should be
1830 * considered to be ordered
1834 while (next_token_talloc(ctx, &p, &name, LIST_SEP)) {
1835 if (strequal(name, "*")) {
1836 status = internal_resolve_name(domain, 0x1C, sitename,
1840 if (NT_STATUS_IS_OK(status)) {
1841 num_addresses += auto_count;
1843 done_auto_lookup = true;
1844 DEBUG(8,("Adding %d DC's from auto lookup\n",
1851 /* if we have no addresses and haven't done the auto lookup, then
1852 just return the list of DC's. Or maybe we just failed. */
1854 if ((num_addresses == 0)) {
1855 if (done_auto_lookup) {
1856 DEBUG(4,("get_dc_list: no servers found\n"));
1857 status = NT_STATUS_NO_LOGON_SERVERS;
1860 status = internal_resolve_name(domain, 0x1C, sitename, ip_list,
1861 count, resolve_order);
1865 if ((return_iplist = SMB_MALLOC_ARRAY(struct ip_service,
1866 num_addresses)) == NULL) {
1867 DEBUG(3,("get_dc_list: malloc fail !\n"));
1868 status = NT_STATUS_NO_MEMORY;
1875 /* fill in the return list now with real IP's */
1877 while ((local_count<num_addresses) &&
1878 next_token_talloc(ctx, &p, &name, LIST_SEP)) {
1879 struct sockaddr_storage name_ss;
1881 /* copy any addersses from the auto lookup */
1883 if (strequal(name, "*")) {
1884 for (j=0; j<auto_count; j++) {
1885 char addr[INET6_ADDRSTRLEN];
1886 print_sockaddr(addr,
1888 &auto_ip_list[j].ss);
1889 /* Check for and don't copy any
1890 * known bad DC IP's. */
1891 if(!NT_STATUS_IS_OK(check_negative_conn_cache(
1894 DEBUG(5,("get_dc_list: "
1895 "negative entry %s removed "
1900 return_iplist[local_count].ss =
1902 return_iplist[local_count].port =
1903 auto_ip_list[j].port;
1909 /* added support for address:port syntax for ads
1910 * (not that I think anyone will ever run the LDAP
1911 * server in an AD domain on something other than
1914 port = (lp_security() == SEC_ADS) ? LDAP_PORT : PORT_NONE;
1915 if ((port_str=strchr(name, ':')) != NULL) {
1918 port = atoi(port_str);
1921 /* explicit lookup; resolve_name() will
1922 * handle names & IP addresses */
1923 if (resolve_name( name, &name_ss, 0x20 )) {
1924 char addr[INET6_ADDRSTRLEN];
1925 print_sockaddr(addr,
1929 /* Check for and don't copy any known bad DC IP's. */
1930 if( !NT_STATUS_IS_OK(check_negative_conn_cache(domain,
1932 DEBUG(5,("get_dc_list: negative entry %s "
1933 "removed from DC list\n",
1938 return_iplist[local_count].ss = name_ss;
1939 return_iplist[local_count].port = port;
1945 /* need to remove duplicates in the list if we have any
1946 explicit password servers */
1949 local_count = remove_duplicate_addrs2(return_iplist,
1953 if ( DEBUGLEVEL >= 4 ) {
1954 DEBUG(4,("get_dc_list: returning %d ip addresses "
1955 "in an %sordered list\n",
1957 *ordered ? "":"un"));
1958 DEBUG(4,("get_dc_list: "));
1959 for ( i=0; i<local_count; i++ ) {
1960 char addr[INET6_ADDRSTRLEN];
1961 print_sockaddr(addr,
1963 &return_iplist[i].ss);
1964 DEBUGADD(4,("%s:%d ", addr, return_iplist[i].port ));
1969 *ip_list = return_iplist;
1970 *count = local_count;
1972 status = ( *count != 0 ? NT_STATUS_OK : NT_STATUS_NO_LOGON_SERVERS );
1976 SAFE_FREE(auto_ip_list);
1981 /*********************************************************************
1982 Small wrapper function to get the DC list and sort it if neccessary.
1983 *********************************************************************/
1985 NTSTATUS get_sorted_dc_list( const char *domain,
1986 const char *sitename,
1987 struct ip_service **ip_list,
1993 enum dc_lookup_type lookup_type = DC_NORMAL_LOOKUP;
1995 DEBUG(8,("get_sorted_dc_list: attempting lookup "
1996 "for name %s (sitename %s) using [%s]\n",
1998 sitename ? sitename : "NULL",
1999 (ads_only ? "ads" : lp_name_resolve_order())));
2002 lookup_type = DC_ADS_ONLY;
2005 status = get_dc_list(domain, sitename, ip_list,
2006 count, lookup_type, &ordered);
2007 if (!NT_STATUS_IS_OK(status)) {
2011 /* only sort if we don't already have an ordered list */
2013 sort_service_list(*ip_list, *count);
2016 return NT_STATUS_OK;
2019 /*********************************************************************
2020 Get the KDC list - re-use all the logic in get_dc_list.
2021 *********************************************************************/
2023 NTSTATUS get_kdc_list( const char *realm,
2024 const char *sitename,
2025 struct ip_service **ip_list,
2034 status = get_dc_list(realm, sitename, ip_list,
2035 count, DC_KDC_ONLY, &ordered);
2037 if (!NT_STATUS_IS_OK(status)) {
2041 /* only sort if we don't already have an ordered list */
2043 sort_service_list(*ip_list, *count);
2046 return NT_STATUS_OK;