s3:dsgetdcname: Inline dsgetdcname_cache_refresh
[ira/wip.git] / source3 / libsmb / dsgetdcname.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    dsgetdcname
5
6    Copyright (C) Gerald Carter 2006
7    Copyright (C) Guenther Deschner 2007-2008
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24
25 #define DSGETDCNAME_FMT "DSGETDCNAME/DOMAIN/%s"
26 /* 15 minutes */
27 #define DSGETDCNAME_CACHE_TTL   60*15
28
29 struct ip_service_name {
30         struct sockaddr_storage ss;
31         unsigned port;
32         const char *hostname;
33 };
34
35 static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx,
36                                               uint32_t flags,
37                                               struct sockaddr_storage *ss,
38                                               struct NETLOGON_SAM_LOGON_RESPONSE_EX *r,
39                                               struct netr_DsRGetDCNameInfo **info);
40
41 /****************************************************************
42 ****************************************************************/
43
44 void debug_dsdcinfo_flags(int lvl, uint32_t flags)
45 {
46         DEBUG(lvl,("debug_dsdcinfo_flags: 0x%08x\n\t", flags));
47
48         if (flags & DS_FORCE_REDISCOVERY)
49                 DEBUGADD(lvl,("DS_FORCE_REDISCOVERY "));
50         if (flags & 0x000000002)
51                 DEBUGADD(lvl,("0x00000002 "));
52         if (flags & 0x000000004)
53                 DEBUGADD(lvl,("0x00000004 "));
54         if (flags & 0x000000008)
55                 DEBUGADD(lvl,("0x00000008 "));
56         if (flags & DS_DIRECTORY_SERVICE_REQUIRED)
57                 DEBUGADD(lvl,("DS_DIRECTORY_SERVICE_REQUIRED "));
58         if (flags & DS_DIRECTORY_SERVICE_PREFERRED)
59                 DEBUGADD(lvl,("DS_DIRECTORY_SERVICE_PREFERRED "));
60         if (flags & DS_GC_SERVER_REQUIRED)
61                 DEBUGADD(lvl,("DS_GC_SERVER_REQUIRED "));
62         if (flags & DS_PDC_REQUIRED)
63                 DEBUGADD(lvl,("DS_PDC_REQUIRED "));
64         if (flags & DS_BACKGROUND_ONLY)
65                 DEBUGADD(lvl,("DS_BACKGROUND_ONLY "));
66         if (flags & DS_IP_REQUIRED)
67                 DEBUGADD(lvl,("DS_IP_REQUIRED "));
68         if (flags & DS_KDC_REQUIRED)
69                 DEBUGADD(lvl,("DS_KDC_REQUIRED "));
70         if (flags & DS_TIMESERV_REQUIRED)
71                 DEBUGADD(lvl,("DS_TIMESERV_REQUIRED "));
72         if (flags & DS_WRITABLE_REQUIRED)
73                 DEBUGADD(lvl,("DS_WRITABLE_REQUIRED "));
74         if (flags & DS_GOOD_TIMESERV_PREFERRED)
75                 DEBUGADD(lvl,("DS_GOOD_TIMESERV_PREFERRED "));
76         if (flags & DS_AVOID_SELF)
77                 DEBUGADD(lvl,("DS_AVOID_SELF "));
78         if (flags & DS_ONLY_LDAP_NEEDED)
79                 DEBUGADD(lvl,("DS_ONLY_LDAP_NEEDED "));
80         if (flags & DS_IS_FLAT_NAME)
81                 DEBUGADD(lvl,("DS_IS_FLAT_NAME "));
82         if (flags & DS_IS_DNS_NAME)
83                 DEBUGADD(lvl,("DS_IS_DNS_NAME "));
84         if (flags & 0x00040000)
85                 DEBUGADD(lvl,("0x00040000 "));
86         if (flags & 0x00080000)
87                 DEBUGADD(lvl,("0x00080000 "));
88         if (flags & 0x00100000)
89                 DEBUGADD(lvl,("0x00100000 "));
90         if (flags & 0x00200000)
91                 DEBUGADD(lvl,("0x00200000 "));
92         if (flags & 0x00400000)
93                 DEBUGADD(lvl,("0x00400000 "));
94         if (flags & 0x00800000)
95                 DEBUGADD(lvl,("0x00800000 "));
96         if (flags & 0x01000000)
97                 DEBUGADD(lvl,("0x01000000 "));
98         if (flags & 0x02000000)
99                 DEBUGADD(lvl,("0x02000000 "));
100         if (flags & 0x04000000)
101                 DEBUGADD(lvl,("0x04000000 "));
102         if (flags & 0x08000000)
103                 DEBUGADD(lvl,("0x08000000 "));
104         if (flags & 0x10000000)
105                 DEBUGADD(lvl,("0x10000000 "));
106         if (flags & 0x20000000)
107                 DEBUGADD(lvl,("0x20000000 "));
108         if (flags & DS_RETURN_DNS_NAME)
109                 DEBUGADD(lvl,("DS_RETURN_DNS_NAME "));
110         if (flags & DS_RETURN_FLAT_NAME)
111                 DEBUGADD(lvl,("DS_RETURN_FLAT_NAME "));
112         if (flags)
113                 DEBUGADD(lvl,("\n"));
114 }
115
116 /****************************************************************
117 ****************************************************************/
118
119 static char *dsgetdcname_cache_key(TALLOC_CTX *mem_ctx, const char *domain)
120 {
121         if (!domain) {
122                 return NULL;
123         }
124
125         return talloc_asprintf_strupper_m(mem_ctx, DSGETDCNAME_FMT, domain);
126 }
127
128 /****************************************************************
129 ****************************************************************/
130
131 static NTSTATUS dsgetdcname_cache_delete(TALLOC_CTX *mem_ctx,
132                                         const char *domain_name)
133 {
134         char *key;
135
136         key = dsgetdcname_cache_key(mem_ctx, domain_name);
137         if (!key) {
138                 return NT_STATUS_NO_MEMORY;
139         }
140
141         if (!gencache_del(key)) {
142                 return NT_STATUS_UNSUCCESSFUL;
143         }
144
145         return NT_STATUS_OK;
146 }
147
148 /****************************************************************
149 ****************************************************************/
150
151 static NTSTATUS dsgetdcname_cache_store(TALLOC_CTX *mem_ctx,
152                                         const char *domain_name,
153                                         const DATA_BLOB *blob)
154 {
155         time_t expire_time;
156         char *key;
157         bool ret = false;
158
159         key = dsgetdcname_cache_key(mem_ctx, domain_name);
160         if (!key) {
161                 return NT_STATUS_NO_MEMORY;
162         }
163
164         expire_time = time(NULL) + DSGETDCNAME_CACHE_TTL;
165
166         ret = gencache_set_data_blob(key, blob, expire_time);
167
168         return ret ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
169 }
170
171 /****************************************************************
172 ****************************************************************/
173
174 static NTSTATUS store_cldap_reply(TALLOC_CTX *mem_ctx,
175                                   uint32_t flags,
176                                   struct sockaddr_storage *ss,
177                                   uint32_t nt_version,
178                                   struct NETLOGON_SAM_LOGON_RESPONSE_EX *r)
179 {
180         DATA_BLOB blob;
181         enum ndr_err_code ndr_err;
182         NTSTATUS status;
183         char addr[INET6_ADDRSTRLEN];
184
185        print_sockaddr(addr, sizeof(addr), ss);
186
187         /* FIXME */
188         r->sockaddr_size = 0x10; /* the w32 winsock addr size */
189         r->sockaddr.sockaddr_family = 2; /* AF_INET */
190         r->sockaddr.pdc_ip = talloc_strdup(mem_ctx, addr);
191
192         ndr_err = ndr_push_struct_blob(&blob, mem_ctx, NULL, r,
193                        (ndr_push_flags_fn_t)ndr_push_NETLOGON_SAM_LOGON_RESPONSE_EX);
194         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
195                 return ndr_map_error2ntstatus(ndr_err);
196         }
197
198         if (r->domain) {
199                 status = dsgetdcname_cache_store(mem_ctx, r->domain, &blob);
200                 if (!NT_STATUS_IS_OK(status)) {
201                         goto done;
202                 }
203                 if (r->client_site) {
204                         sitename_store(r->domain, r->client_site);
205                 }
206         }
207         if (r->dns_domain) {
208                 status = dsgetdcname_cache_store(mem_ctx, r->dns_domain, &blob);
209                 if (!NT_STATUS_IS_OK(status)) {
210                         goto done;
211                 }
212                 if (r->client_site) {
213                         sitename_store(r->dns_domain, r->client_site);
214                 }
215         }
216
217         status = NT_STATUS_OK;
218
219  done:
220         data_blob_free(&blob);
221
222         return status;
223 }
224
225 /****************************************************************
226 ****************************************************************/
227
228 static uint32_t get_cldap_reply_server_flags(struct netlogon_samlogon_response *r,
229                                              uint32_t nt_version)
230 {
231         switch (nt_version & 0x0000001f) {
232                 case 0:
233                 case 1:
234                 case 16:
235                 case 17:
236                         return 0;
237                 case 2:
238                 case 3:
239                 case 18:
240                 case 19:
241                         return r->data.nt5.server_type;
242                 case 4:
243                 case 5:
244                 case 6:
245                 case 7:
246                         return r->data.nt5_ex.server_type;
247                 case 8:
248                 case 9:
249                 case 10:
250                 case 11:
251                 case 12:
252                 case 13:
253                 case 14:
254                 case 15:
255                         return r->data.nt5_ex.server_type;
256                 case 20:
257                 case 21:
258                 case 22:
259                 case 23:
260                 case 24:
261                 case 25:
262                 case 26:
263                 case 27:
264                 case 28:
265                         return r->data.nt5_ex.server_type;
266                 case 29:
267                 case 30:
268                 case 31:
269                         return r->data.nt5_ex.server_type;
270                 default:
271                         return 0;
272         }
273 }
274
275 /****************************************************************
276 ****************************************************************/
277
278 #define RETURN_ON_FALSE(x) if (!(x)) return false;
279
280 static bool check_cldap_reply_required_flags(uint32_t ret_flags,
281                                              uint32_t req_flags)
282 {
283         if (ret_flags == 0) {
284                 return true;
285         }
286
287         if (req_flags & DS_PDC_REQUIRED)
288                 RETURN_ON_FALSE(ret_flags & NBT_SERVER_PDC);
289
290         if (req_flags & DS_GC_SERVER_REQUIRED)
291                 RETURN_ON_FALSE(ret_flags & NBT_SERVER_GC);
292
293         if (req_flags & DS_ONLY_LDAP_NEEDED)
294                 RETURN_ON_FALSE(ret_flags & NBT_SERVER_LDAP);
295
296         if ((req_flags & DS_DIRECTORY_SERVICE_REQUIRED) ||
297             (req_flags & DS_DIRECTORY_SERVICE_PREFERRED))
298                 RETURN_ON_FALSE(ret_flags & NBT_SERVER_DS);
299
300         if (req_flags & DS_KDC_REQUIRED)
301                 RETURN_ON_FALSE(ret_flags & NBT_SERVER_KDC);
302
303         if (req_flags & DS_TIMESERV_REQUIRED)
304                 RETURN_ON_FALSE(ret_flags & NBT_SERVER_TIMESERV);
305
306         if (req_flags & DS_WRITABLE_REQUIRED)
307                 RETURN_ON_FALSE(ret_flags & NBT_SERVER_WRITABLE);
308
309         return true;
310 }
311
312 /****************************************************************
313 ****************************************************************/
314
315 static NTSTATUS dsgetdcname_cache_fetch(TALLOC_CTX *mem_ctx,
316                                         const char *domain_name,
317                                         struct GUID *domain_guid,
318                                         uint32_t flags,
319                                         const char *site_name,
320                                         struct netr_DsRGetDCNameInfo **info_p)
321 {
322         char *key;
323         DATA_BLOB blob;
324         enum ndr_err_code ndr_err;
325         struct netr_DsRGetDCNameInfo *info;
326         struct NETLOGON_SAM_LOGON_RESPONSE_EX r;
327         NTSTATUS status;
328
329         key = dsgetdcname_cache_key(mem_ctx, domain_name);
330         if (!key) {
331                 return NT_STATUS_NO_MEMORY;
332         }
333
334         if (!gencache_get_data_blob(key, &blob, NULL)) {
335                 return NT_STATUS_NOT_FOUND;
336         }
337
338         info = TALLOC_ZERO_P(mem_ctx, struct netr_DsRGetDCNameInfo);
339         if (!info) {
340                 return NT_STATUS_NO_MEMORY;
341         }
342
343         ndr_err = ndr_pull_struct_blob(&blob, mem_ctx, NULL, &r,
344                       (ndr_pull_flags_fn_t)ndr_pull_NETLOGON_SAM_LOGON_RESPONSE_EX);
345
346         data_blob_free(&blob);
347         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
348                 dsgetdcname_cache_delete(mem_ctx, domain_name);
349                 return ndr_map_error2ntstatus(ndr_err);
350         }
351
352         status = make_dc_info_from_cldap_reply(mem_ctx, flags, NULL,
353                                                &r, &info);
354         if (!NT_STATUS_IS_OK(status)) {
355                 return status;
356         }
357
358         if (DEBUGLEVEL >= 10) {
359                 NDR_PRINT_DEBUG(netr_DsRGetDCNameInfo, info);
360         }
361
362         /* check flags */
363         if (!check_cldap_reply_required_flags(info->dc_flags, flags)) {
364                 DEBUG(10,("invalid flags\n"));
365                 return NT_STATUS_INVALID_PARAMETER;
366         }
367
368         if ((flags & DS_IP_REQUIRED) &&
369             (info->dc_address_type != DS_ADDRESS_TYPE_INET)) {
370                 return NT_STATUS_INVALID_PARAMETER_MIX;
371         }
372
373         *info_p = info;
374
375         return NT_STATUS_OK;
376 }
377
378 /****************************************************************
379 ****************************************************************/
380
381 static NTSTATUS dsgetdcname_cached(TALLOC_CTX *mem_ctx,
382                                    struct messaging_context *msg_ctx,
383                                    const char *domain_name,
384                                    struct GUID *domain_guid,
385                                    uint32_t flags,
386                                    const char *site_name,
387                                    struct netr_DsRGetDCNameInfo **info)
388 {
389         NTSTATUS status;
390
391         status = dsgetdcname_cache_fetch(mem_ctx, domain_name, domain_guid,
392                                          flags, site_name, info);
393         if (!NT_STATUS_IS_OK(status)
394             && !NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
395                 DEBUG(10,("dsgetdcname_cached: cache fetch failed with: %s\n",
396                         nt_errstr(status)));
397                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
398         }
399
400         if (flags & DS_BACKGROUND_ONLY) {
401                 return status;
402         }
403
404         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
405                 struct netr_DsRGetDCNameInfo *dc_info;
406
407                 status = dsgetdcname(mem_ctx, msg_ctx, domain_name,
408                                      domain_guid, site_name,
409                                      flags | DS_FORCE_REDISCOVERY,
410                                      &dc_info);
411
412                 if (!NT_STATUS_IS_OK(status)) {
413                         return status;
414                 }
415         }
416
417         return status;
418 }
419
420 /****************************************************************
421 ****************************************************************/
422
423 static bool check_allowed_required_flags(uint32_t flags,
424                                          const char *site_name)
425 {
426         uint32_t return_type = flags & (DS_RETURN_FLAT_NAME|DS_RETURN_DNS_NAME);
427         uint32_t offered_type = flags & (DS_IS_FLAT_NAME|DS_IS_DNS_NAME);
428         uint32_t query_type = flags & (DS_BACKGROUND_ONLY|DS_FORCE_REDISCOVERY);
429
430         /* FIXME: check for DSGETDC_VALID_FLAGS and check for excluse bits
431          * (DS_PDC_REQUIRED, DS_KDC_REQUIRED, DS_GC_SERVER_REQUIRED) */
432
433         debug_dsdcinfo_flags(10, flags);
434
435         if ((flags & DS_TRY_NEXTCLOSEST_SITE) && site_name) {
436                 return false;
437         }
438
439         if (return_type == (DS_RETURN_FLAT_NAME|DS_RETURN_DNS_NAME)) {
440                 return false;
441         }
442
443         if (offered_type == (DS_IS_DNS_NAME|DS_IS_FLAT_NAME)) {
444                 return false;
445         }
446
447         if (query_type == (DS_BACKGROUND_ONLY|DS_FORCE_REDISCOVERY)) {
448                 return false;
449         }
450
451 #if 0
452         if ((flags & DS_RETURN_DNS_NAME) && (!(flags & DS_IP_REQUIRED))) {
453                 printf("gd: here5 \n");
454                 return false;
455         }
456 #endif
457         return true;
458 }
459
460 /****************************************************************
461 ****************************************************************/
462
463 static NTSTATUS discover_dc_netbios(TALLOC_CTX *mem_ctx,
464                                     const char *domain_name,
465                                     uint32_t flags,
466                                     struct ip_service_name **returned_dclist,
467                                     int *returned_count)
468 {
469         NTSTATUS status;
470         enum nbt_name_type name_type = NBT_NAME_LOGON;
471         struct ip_service *iplist;
472         int i;
473         struct ip_service_name *dclist = NULL;
474         int count;
475
476         *returned_dclist = NULL;
477         *returned_count = 0;
478
479         if (lp_disable_netbios()) {
480                 return NT_STATUS_NOT_SUPPORTED;
481         }
482
483         if (flags & DS_PDC_REQUIRED) {
484                 name_type = NBT_NAME_PDC;
485         }
486
487         status = internal_resolve_name(domain_name, name_type, NULL,
488                                        &iplist, &count,
489                                        "lmhosts wins bcast");
490         if (!NT_STATUS_IS_OK(status)) {
491                 DEBUG(10,("discover_dc_netbios: failed to find DC\n"));
492                 return status;
493         }
494
495         dclist = TALLOC_ZERO_ARRAY(mem_ctx, struct ip_service_name, count);
496         if (!dclist) {
497                 return NT_STATUS_NO_MEMORY;
498         }
499
500         for (i=0; i<count; i++) {
501
502                 char addr[INET6_ADDRSTRLEN];
503                 struct ip_service_name *r = &dclist[i];
504
505                 print_sockaddr(addr, sizeof(addr),
506                                &iplist[i].ss);
507
508                 r->ss   = iplist[i].ss;
509                 r->port = iplist[i].port;
510                 r->hostname = talloc_strdup(mem_ctx, addr);
511                 if (!r->hostname) {
512                         return NT_STATUS_NO_MEMORY;
513                 }
514
515         }
516
517         *returned_dclist = dclist;
518         *returned_count = count;
519
520         return NT_STATUS_OK;
521 }
522
523 /****************************************************************
524 ****************************************************************/
525
526 static NTSTATUS discover_dc_dns(TALLOC_CTX *mem_ctx,
527                                 const char *domain_name,
528                                 struct GUID *domain_guid,
529                                 uint32_t flags,
530                                 const char *site_name,
531                                 struct ip_service_name **returned_dclist,
532                                 int *return_count)
533 {
534         int i, j;
535         NTSTATUS status;
536         struct dns_rr_srv *dcs = NULL;
537         int numdcs = 0;
538         int numaddrs = 0;
539         struct ip_service_name *dclist = NULL;
540         int count = 0;
541
542         if (flags & DS_PDC_REQUIRED) {
543                 status = ads_dns_query_pdc(mem_ctx, domain_name,
544                                            &dcs, &numdcs);
545         } else if (flags & DS_GC_SERVER_REQUIRED) {
546                 status = ads_dns_query_gcs(mem_ctx, domain_name, site_name,
547                                            &dcs, &numdcs);
548         } else if (flags & DS_KDC_REQUIRED) {
549                 status = ads_dns_query_kdcs(mem_ctx, domain_name, site_name,
550                                             &dcs, &numdcs);
551         } else if (flags & DS_DIRECTORY_SERVICE_REQUIRED) {
552                 status = ads_dns_query_dcs(mem_ctx, domain_name, site_name,
553                                            &dcs, &numdcs);
554         } else if (domain_guid) {
555                 status = ads_dns_query_dcs_guid(mem_ctx, domain_name,
556                                                 domain_guid, &dcs, &numdcs);
557         } else {
558                 status = ads_dns_query_dcs(mem_ctx, domain_name, site_name,
559                                            &dcs, &numdcs);
560         }
561
562         if (!NT_STATUS_IS_OK(status)) {
563                 return status;
564         }
565
566         if (numdcs == 0) {
567                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
568         }
569
570         for (i=0;i<numdcs;i++) {
571                 numaddrs += MAX(dcs[i].num_ips,1);
572         }
573
574         dclist = TALLOC_ZERO_ARRAY(mem_ctx,
575                                    struct ip_service_name,
576                                    numaddrs);
577         if (!dclist) {
578                 return NT_STATUS_NO_MEMORY;
579         }
580
581         /* now unroll the list of IP addresses */
582
583         *return_count = 0;
584         i = 0;
585         j = 0;
586
587         while ((i < numdcs) && (count < numaddrs)) {
588
589                 struct ip_service_name *r = &dclist[count];
590
591                 r->port = dcs[i].port;
592                 r->hostname = dcs[i].hostname;
593
594                 /* If we don't have an IP list for a name, lookup it up */
595
596                 if (!dcs[i].ss_s) {
597                         interpret_string_addr_prefer_ipv4(&r->ss,
598                                                 dcs[i].hostname, 0);
599                         i++;
600                         j = 0;
601                 } else {
602                         /* use the IP addresses from the SRV sresponse */
603
604                         if (j >= dcs[i].num_ips) {
605                                 i++;
606                                 j = 0;
607                                 continue;
608                         }
609
610                         r->ss = dcs[i].ss_s[j];
611                         j++;
612                 }
613
614                 /* make sure it is a valid IP.  I considered checking the
615                  * negative connection cache, but this is the wrong place for
616                  * it.  Maybe only as a hac.  After think about it, if all of
617                  * the IP addresses retuend from DNS are dead, what hope does a
618                  * netbios name lookup have?  The standard reason for falling
619                  * back to netbios lookups is that our DNS server doesn't know
620                  * anything about the DC's   -- jerry */
621
622                 if (!is_zero_addr((struct sockaddr *)(void *)&r->ss)) {
623                         count++;
624                         continue;
625                 }
626         }
627
628         *returned_dclist = dclist;
629         *return_count = count;
630
631         if (count > 0) {
632                 return NT_STATUS_OK;
633         }
634
635         return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
636 }
637
638 /****************************************************************
639 ****************************************************************/
640
641 static NTSTATUS make_domain_controller_info(TALLOC_CTX *mem_ctx,
642                                             const char *dc_unc,
643                                             const char *dc_address,
644                                             uint32_t dc_address_type,
645                                             const struct GUID *domain_guid,
646                                             const char *domain_name,
647                                             const char *forest_name,
648                                             uint32_t flags,
649                                             const char *dc_site_name,
650                                             const char *client_site_name,
651                                             struct netr_DsRGetDCNameInfo **info_out)
652 {
653         struct netr_DsRGetDCNameInfo *info;
654
655         info = TALLOC_ZERO_P(mem_ctx, struct netr_DsRGetDCNameInfo);
656         NT_STATUS_HAVE_NO_MEMORY(info);
657
658         if (dc_unc) {
659                 info->dc_unc = talloc_strdup(mem_ctx, dc_unc);
660                 NT_STATUS_HAVE_NO_MEMORY(info->dc_unc);
661         }
662
663         if (dc_address) {
664                 if (!(dc_address[0] == '\\' && dc_address[1] == '\\')) {
665                         info->dc_address = talloc_asprintf(mem_ctx, "\\\\%s",
666                                                            dc_address);
667                 } else {
668                         info->dc_address = talloc_strdup(mem_ctx, dc_address);
669                 }
670                 NT_STATUS_HAVE_NO_MEMORY(info->dc_address);
671         }
672
673         info->dc_address_type = dc_address_type;
674
675         if (domain_guid) {
676                 info->domain_guid = *domain_guid;
677         }
678
679         if (domain_name) {
680                 info->domain_name = talloc_strdup(mem_ctx, domain_name);
681                 NT_STATUS_HAVE_NO_MEMORY(info->domain_name);
682         }
683
684         if (forest_name && *forest_name) {
685                 info->forest_name = talloc_strdup(mem_ctx, forest_name);
686                 NT_STATUS_HAVE_NO_MEMORY(info->forest_name);
687                 flags |= DS_DNS_FOREST;
688         }
689
690         info->dc_flags = flags;
691
692         if (dc_site_name) {
693                 info->dc_site_name = talloc_strdup(mem_ctx, dc_site_name);
694                 NT_STATUS_HAVE_NO_MEMORY(info->dc_site_name);
695         }
696
697         if (client_site_name) {
698                 info->client_site_name = talloc_strdup(mem_ctx,
699                                                        client_site_name);
700                 NT_STATUS_HAVE_NO_MEMORY(info->client_site_name);
701         }
702
703         *info_out = info;
704
705         return NT_STATUS_OK;
706 }
707
708 /****************************************************************
709 ****************************************************************/
710
711 static void map_dc_and_domain_names(uint32_t flags,
712                                     const char *dc_name,
713                                     const char *domain_name,
714                                     const char *dns_dc_name,
715                                     const char *dns_domain_name,
716                                     uint32_t *dc_flags,
717                                     const char **hostname_p,
718                                     const char **domain_p)
719 {
720         switch (flags & 0xf0000000) {
721                 case DS_RETURN_FLAT_NAME:
722                         if (dc_name && domain_name &&
723                             *dc_name && *domain_name) {
724                                 *hostname_p = dc_name;
725                                 *domain_p = domain_name;
726                                 break;
727                         }
728                 case DS_RETURN_DNS_NAME:
729                 default:
730                         if (dns_dc_name && dns_domain_name &&
731                             *dns_dc_name && *dns_domain_name) {
732                                 *hostname_p = dns_dc_name;
733                                 *domain_p = dns_domain_name;
734                                 *dc_flags |= DS_DNS_DOMAIN | DS_DNS_CONTROLLER;
735                                 break;
736                         }
737                         if (dc_name && domain_name &&
738                             *dc_name && *domain_name) {
739                                 *hostname_p = dc_name;
740                                 *domain_p = domain_name;
741                                 break;
742                         }
743         }
744 }
745
746 /****************************************************************
747 ****************************************************************/
748
749 static NTSTATUS make_dc_info_from_cldap_reply(TALLOC_CTX *mem_ctx,
750                                               uint32_t flags,
751                                               struct sockaddr_storage *ss,
752                                               struct NETLOGON_SAM_LOGON_RESPONSE_EX *r,
753                                               struct netr_DsRGetDCNameInfo **info)
754 {
755         const char *dc_hostname = NULL;
756         const char *dc_domain_name = NULL;
757         const char *dc_address = NULL;
758         const char *dc_forest = NULL;
759         uint32_t dc_address_type = 0;
760         uint32_t dc_flags = 0;
761         struct GUID *dc_domain_guid = NULL;
762         const char *dc_server_site = NULL;
763         const char *dc_client_site = NULL;
764
765         char addr[INET6_ADDRSTRLEN];
766
767         if (ss) {
768                 print_sockaddr(addr, sizeof(addr), ss);
769                 dc_address = addr;
770                 dc_address_type = DS_ADDRESS_TYPE_INET;
771         }
772
773         if (!ss && r->sockaddr.pdc_ip) {
774                 dc_address      = r->sockaddr.pdc_ip;
775                 dc_address_type = DS_ADDRESS_TYPE_INET;
776         } else {
777                 dc_address      = r->pdc_name;
778                 dc_address_type = DS_ADDRESS_TYPE_NETBIOS;
779         }
780
781         map_dc_and_domain_names(flags,
782                                 r->pdc_name,
783                                 r->domain,
784                                 r->pdc_dns_name,
785                                 r->dns_domain,
786                                 &dc_flags,
787                                 &dc_hostname,
788                                 &dc_domain_name);
789
790         dc_flags        |= r->server_type;
791         dc_forest       = r->forest;
792         dc_domain_guid  = &r->domain_uuid;
793         dc_server_site  = r->server_site;
794         dc_client_site  = r->client_site;
795
796         return make_domain_controller_info(mem_ctx,
797                                            dc_hostname,
798                                            dc_address,
799                                            dc_address_type,
800                                            dc_domain_guid,
801                                            dc_domain_name,
802                                            dc_forest,
803                                            dc_flags,
804                                            dc_server_site,
805                                            dc_client_site,
806                                            info);
807 }
808
809 /****************************************************************
810 ****************************************************************/
811
812 static uint32_t map_ds_flags_to_nt_version(uint32_t flags)
813 {
814         uint32_t nt_version = 0;
815
816         if (flags & DS_PDC_REQUIRED) {
817                 nt_version |= NETLOGON_NT_VERSION_PDC;
818         }
819
820         if (flags & DS_GC_SERVER_REQUIRED) {
821                 nt_version |= NETLOGON_NT_VERSION_GC;
822         }
823
824         if (flags & DS_TRY_NEXTCLOSEST_SITE) {
825                 nt_version |= NETLOGON_NT_VERSION_WITH_CLOSEST_SITE;
826         }
827
828         if (flags & DS_IP_REQUIRED) {
829                 nt_version |= NETLOGON_NT_VERSION_IP;
830         }
831
832         return nt_version;
833 }
834
835 /****************************************************************
836 ****************************************************************/
837
838 static NTSTATUS process_dc_dns(TALLOC_CTX *mem_ctx,
839                                const char *domain_name,
840                                uint32_t flags,
841                                struct ip_service_name *dclist,
842                                int num_dcs,
843                                struct netr_DsRGetDCNameInfo **info)
844 {
845         int i = 0;
846         bool valid_dc = false;
847         struct netlogon_samlogon_response *r = NULL;
848         uint32_t nt_version = NETLOGON_NT_VERSION_5 |
849                               NETLOGON_NT_VERSION_5EX;
850         uint32_t ret_flags = 0;
851         NTSTATUS status;
852
853         nt_version |= map_ds_flags_to_nt_version(flags);
854
855         for (i=0; i<num_dcs; i++) {
856
857                 DEBUG(10,("LDAP ping to %s\n", dclist[i].hostname));
858
859                 if (ads_cldap_netlogon(mem_ctx, dclist[i].hostname,
860                                         domain_name,
861                                         nt_version,
862                                         &r))
863                 {
864                         nt_version = r->ntver;
865                         ret_flags = get_cldap_reply_server_flags(r, nt_version);
866
867                         if (check_cldap_reply_required_flags(ret_flags, flags)) {
868                                 valid_dc = true;
869                                 break;
870                         }
871                 }
872
873                 continue;
874         }
875
876         if (!valid_dc) {
877                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
878         }
879
880         status = make_dc_info_from_cldap_reply(mem_ctx, flags, &dclist[i].ss,
881                                                &r->data.nt5_ex, info);
882         if (NT_STATUS_IS_OK(status)) {
883                 return store_cldap_reply(mem_ctx, flags, &dclist[i].ss,
884                                          nt_version, &r->data.nt5_ex);
885         }
886
887         return status;
888 }
889
890 /****************************************************************
891 ****************************************************************/
892
893 static struct event_context *ev_context(void)
894 {
895         static struct event_context *ctx;
896
897         if (!ctx && !(ctx = event_context_init(NULL))) {
898                 smb_panic("Could not init event context");
899         }
900         return ctx;
901 }
902
903 /****************************************************************
904 ****************************************************************/
905
906 static struct messaging_context *msg_context(TALLOC_CTX *mem_ctx)
907 {
908         static struct messaging_context *ctx;
909
910         if (!ctx && !(ctx = messaging_init(mem_ctx, server_id_self(),
911                                            ev_context()))) {
912                 smb_panic("Could not init messaging context");
913         }
914         return ctx;
915 }
916
917 /****************************************************************
918 ****************************************************************/
919
920 static NTSTATUS process_dc_netbios(TALLOC_CTX *mem_ctx,
921                                    struct messaging_context *msg_ctx,
922                                    const char *domain_name,
923                                    uint32_t flags,
924                                    struct ip_service_name *dclist,
925                                    int num_dcs,
926                                    struct netr_DsRGetDCNameInfo **info)
927 {
928         struct sockaddr_storage ss;
929         struct ip_service ip_list;
930         enum nbt_name_type name_type = NBT_NAME_LOGON;
931         NTSTATUS status;
932         int i;
933         const char *dc_name = NULL;
934         fstring tmp_dc_name;
935         struct netlogon_samlogon_response *r = NULL;
936         bool store_cache = false;
937         uint32_t nt_version = NETLOGON_NT_VERSION_1 |
938                               NETLOGON_NT_VERSION_5 |
939                               NETLOGON_NT_VERSION_5EX_WITH_IP;
940
941         if (!msg_ctx) {
942                 msg_ctx = msg_context(mem_ctx);
943         }
944
945         if (flags & DS_PDC_REQUIRED) {
946                 name_type = NBT_NAME_PDC;
947         }
948
949         nt_version |= map_ds_flags_to_nt_version(flags);
950
951         DEBUG(10,("process_dc_netbios\n"));
952
953         for (i=0; i<num_dcs; i++) {
954
955                 ip_list.ss = dclist[i].ss;
956                 ip_list.port = 0;
957
958                 if (!interpret_string_addr_prefer_ipv4(&ss, dclist[i].hostname, AI_NUMERICHOST)) {
959                         return NT_STATUS_UNSUCCESSFUL;
960                 }
961
962                 if (send_getdc_request(mem_ctx, msg_ctx,
963                                        &dclist[i].ss, domain_name,
964                                        NULL, nt_version))
965                 {
966                         int k;
967                         smb_msleep(300);
968                         for (k=0; k<5; k++) {
969                                 if (receive_getdc_response(mem_ctx,
970                                                            &dclist[i].ss,
971                                                            domain_name,
972                                                            &nt_version,
973                                                            &dc_name,
974                                                            &r)) {
975                                         store_cache = true;
976                                         namecache_store(dc_name, NBT_NAME_SERVER, 1, &ip_list);
977                                         goto make_reply;
978                                 }
979                                 smb_msleep(1500);
980                         }
981                 }
982
983                 if (name_status_find(domain_name,
984                                      name_type,
985                                      NBT_NAME_SERVER,
986                                      &dclist[i].ss,
987                                      tmp_dc_name))
988                 {
989                         struct NETLOGON_SAM_LOGON_RESPONSE_NT40 logon1;
990
991                         r = TALLOC_ZERO_P(mem_ctx, struct netlogon_samlogon_response);
992                         NT_STATUS_HAVE_NO_MEMORY(r);
993
994                         ZERO_STRUCT(logon1);
995
996                         nt_version = NETLOGON_NT_VERSION_1;
997
998                         logon1.nt_version = nt_version;
999                         logon1.server = tmp_dc_name;
1000                         logon1.domain = talloc_strdup_upper(mem_ctx, domain_name);
1001                         NT_STATUS_HAVE_NO_MEMORY(logon1.domain);
1002
1003                         r->data.nt4 = logon1;
1004                         r->ntver = nt_version;
1005
1006                         map_netlogon_samlogon_response(r);
1007
1008                         namecache_store(tmp_dc_name, NBT_NAME_SERVER, 1, &ip_list);
1009
1010                         goto make_reply;
1011                 }
1012         }
1013
1014         return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1015
1016  make_reply:
1017
1018         status = make_dc_info_from_cldap_reply(mem_ctx, flags, &dclist[i].ss,
1019                                                &r->data.nt5_ex, info);
1020         if (NT_STATUS_IS_OK(status) && store_cache) {
1021                 return store_cldap_reply(mem_ctx, flags, &dclist[i].ss,
1022                                          nt_version, &r->data.nt5_ex);
1023         }
1024
1025         return status;
1026 }
1027
1028 /****************************************************************
1029 ****************************************************************/
1030
1031 static NTSTATUS dsgetdcname_rediscover(TALLOC_CTX *mem_ctx,
1032                                        struct messaging_context *msg_ctx,
1033                                        const char *domain_name,
1034                                        struct GUID *domain_guid,
1035                                        uint32_t flags,
1036                                        const char *site_name,
1037                                        struct netr_DsRGetDCNameInfo **info)
1038 {
1039         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1040         struct ip_service_name *dclist = NULL;
1041         int num_dcs;
1042
1043         DEBUG(10,("dsgetdcname_rediscover\n"));
1044
1045         if (flags & DS_IS_FLAT_NAME) {
1046
1047                 status = discover_dc_netbios(mem_ctx, domain_name, flags,
1048                                              &dclist, &num_dcs);
1049                 NT_STATUS_NOT_OK_RETURN(status);
1050
1051                 return process_dc_netbios(mem_ctx, msg_ctx, domain_name, flags,
1052                                           dclist, num_dcs, info);
1053         }
1054
1055         if (flags & DS_IS_DNS_NAME) {
1056
1057                 status = discover_dc_dns(mem_ctx, domain_name, domain_guid,
1058                                          flags, site_name, &dclist, &num_dcs);
1059                 NT_STATUS_NOT_OK_RETURN(status);
1060
1061                 return process_dc_dns(mem_ctx, domain_name, flags,
1062                                       dclist, num_dcs, info);
1063         }
1064
1065         status = discover_dc_dns(mem_ctx, domain_name, domain_guid, flags,
1066                                  site_name, &dclist, &num_dcs);
1067
1068         if (NT_STATUS_IS_OK(status) && num_dcs != 0) {
1069
1070                 status = process_dc_dns(mem_ctx, domain_name, flags, dclist,
1071                                         num_dcs, info);
1072                 if (NT_STATUS_IS_OK(status)) {
1073                         return status;
1074                 }
1075         }
1076
1077         status = discover_dc_netbios(mem_ctx, domain_name, flags, &dclist,
1078                                      &num_dcs);
1079         NT_STATUS_NOT_OK_RETURN(status);
1080
1081         return process_dc_netbios(mem_ctx, msg_ctx, domain_name, flags, dclist,
1082                                   num_dcs, info);
1083 }
1084
1085 static bool is_closest_site(struct netr_DsRGetDCNameInfo *info)
1086 {
1087         if (info->dc_flags & DS_SERVER_CLOSEST) {
1088                 return true;
1089         }
1090
1091         if (!info->client_site_name) {
1092                 return true;
1093         }
1094
1095         if (!info->dc_site_name) {
1096                 return false;
1097         }
1098
1099         if (strcmp(info->client_site_name, info->dc_site_name) == 0) {
1100                 return true;
1101         }
1102
1103         return false;
1104 }
1105
1106 /********************************************************************
1107  dsgetdcname.
1108
1109  This will be the only public function here.
1110 ********************************************************************/
1111
1112 NTSTATUS dsgetdcname(TALLOC_CTX *mem_ctx,
1113                      struct messaging_context *msg_ctx,
1114                      const char *domain_name,
1115                      struct GUID *domain_guid,
1116                      const char *site_name,
1117                      uint32_t flags,
1118                      struct netr_DsRGetDCNameInfo **info)
1119 {
1120         NTSTATUS status = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1121         struct netr_DsRGetDCNameInfo *myinfo = NULL;
1122         char *query_site = NULL;
1123         bool first = true;
1124         struct netr_DsRGetDCNameInfo *first_info = NULL;
1125
1126         DEBUG(10,("dsgetdcname: domain_name: %s, "
1127                   "domain_guid: %s, site_name: %s, flags: 0x%08x\n",
1128                   domain_name,
1129                   domain_guid ? GUID_string(mem_ctx, domain_guid) : "(null)",
1130                   site_name, flags));
1131
1132         *info = NULL;
1133
1134         if (!check_allowed_required_flags(flags, site_name)) {
1135                 DEBUG(0,("invalid flags specified\n"));
1136                 return NT_STATUS_INVALID_PARAMETER;
1137         }
1138
1139         if (!site_name) {
1140                 query_site = sitename_fetch(domain_name);
1141         } else {
1142                 query_site = SMB_STRDUP(site_name);
1143         }
1144
1145         if (flags & DS_FORCE_REDISCOVERY) {
1146                 goto rediscover;
1147         }
1148
1149         status = dsgetdcname_cached(mem_ctx, msg_ctx, domain_name, domain_guid,
1150                                     flags, query_site, &myinfo);
1151         if (NT_STATUS_IS_OK(status)) {
1152                 goto done;
1153         }
1154
1155         if (flags & DS_BACKGROUND_ONLY) {
1156                 goto done;
1157         }
1158
1159  rediscover:
1160         status = dsgetdcname_rediscover(mem_ctx, msg_ctx, domain_name,
1161                                         domain_guid, flags, query_site,
1162                                         &myinfo);
1163
1164  done:
1165         SAFE_FREE(query_site);
1166
1167         if (!NT_STATUS_IS_OK(status)) {
1168                 if (!first) {
1169                         *info = first_info;
1170                         return NT_STATUS_OK;
1171                 }
1172                 return status;
1173         }
1174
1175         if (!first) {
1176                 TALLOC_FREE(first_info);
1177         } else if (!is_closest_site(myinfo)) {
1178                 first = false;
1179                 first_info = myinfo;
1180                 /* TODO: may use the next_closest_site here */
1181                 query_site = SMB_STRDUP(myinfo->client_site_name);
1182                 goto rediscover;
1183         }
1184
1185         *info = myinfo;
1186         return NT_STATUS_OK;
1187 }