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