b30035719072fdf688102a8f8dbe86d70204850b
[anatoliy/anatoliy.git] / source3 / winbindd / winbindd_cm.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon connection manager
5
6    Copyright (C) Tim Potter                2001
7    Copyright (C) Andrew Bartlett           2002
8    Copyright (C) Gerald (Jerry) Carter     2003-2005.
9    Copyright (C) Volker Lendecke           2004-2005
10    Copyright (C) Jeremy Allison            2006
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3 of the License, or
15    (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 /*
27    We need to manage connections to domain controllers without having to
28    mess up the main winbindd code with other issues.  The aim of the
29    connection manager is to:
30
31        - make connections to domain controllers and cache them
32        - re-establish connections when networks or servers go down
33        - centralise the policy on connection timeouts, domain controller
34          selection etc
35        - manage re-entrancy for when winbindd becomes able to handle
36          multiple outstanding rpc requests
37
38    Why not have connection management as part of the rpc layer like tng?
39    Good question.  This code may morph into libsmb/rpc_cache.c or something
40    like that but at the moment it's simply staying as part of winbind.  I
41    think the TNG architecture of forcing every user of the rpc layer to use
42    the connection caching system is a bad idea.  It should be an optional
43    method of using the routines.
44
45    The TNG design is quite good but I disagree with some aspects of the
46    implementation. -tpot
47
48  */
49
50 /*
51    TODO:
52
53      - I'm pretty annoyed by all the make_nmb_name() stuff.  It should be
54        moved down into another function.
55
56      - Take care when destroying cli_structs as they can be shared between
57        various sam handles.
58
59  */
60
61 #include "includes.h"
62 #include "winbindd.h"
63 #include "../libcli/auth/libcli_auth.h"
64 #include "../librpc/gen_ndr/cli_netlogon.h"
65 #include "rpc_client/cli_netlogon.h"
66 #include "../librpc/gen_ndr/cli_samr.h"
67 #include "../librpc/gen_ndr/cli_lsa.h"
68 #include "rpc_client/cli_lsarpc.h"
69 #include "../librpc/gen_ndr/cli_dssetup.h"
70 #include "libads/sitename_cache.h"
71 #include "librpc/gen_ndr/messaging.h"
72 #include "libsmb/clidgram.h"
73
74 #undef DBGC_CLASS
75 #define DBGC_CLASS DBGC_WINBIND
76
77 struct dc_name_ip {
78         fstring name;
79         struct sockaddr_storage ss;
80 };
81
82 extern struct winbindd_methods reconnect_methods;
83 extern bool override_logfile;
84
85 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain);
86 static void set_dc_type_and_flags( struct winbindd_domain *domain );
87 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
88                     struct dc_name_ip **dcs, int *num_dcs);
89
90 /****************************************************************
91  Child failed to find DC's. Reschedule check.
92 ****************************************************************/
93
94 static void msg_failed_to_go_online(struct messaging_context *msg,
95                                     void *private_data,
96                                     uint32_t msg_type,
97                                     struct server_id server_id,
98                                     DATA_BLOB *data)
99 {
100         struct winbindd_domain *domain;
101         const char *domainname = (const char *)data->data;
102
103         if (data->data == NULL || data->length == 0) {
104                 return;
105         }
106
107         DEBUG(5,("msg_fail_to_go_online: received for domain %s.\n", domainname));
108
109         for (domain = domain_list(); domain; domain = domain->next) {
110                 if (domain->internal) {
111                         continue;
112                 }
113
114                 if (strequal(domain->name, domainname)) {
115                         if (domain->online) {
116                                 /* We're already online, ignore. */
117                                 DEBUG(5,("msg_fail_to_go_online: domain %s "
118                                         "already online.\n", domainname));
119                                 continue;
120                         }
121
122                         /* Reschedule the online check. */
123                         set_domain_offline(domain);
124                         break;
125                 }
126         }
127 }
128
129 /****************************************************************
130  Actually cause a reconnect from a message.
131 ****************************************************************/
132
133 static void msg_try_to_go_online(struct messaging_context *msg,
134                                  void *private_data,
135                                  uint32_t msg_type,
136                                  struct server_id server_id,
137                                  DATA_BLOB *data)
138 {
139         struct winbindd_domain *domain;
140         const char *domainname = (const char *)data->data;
141
142         if (data->data == NULL || data->length == 0) {
143                 return;
144         }
145
146         DEBUG(5,("msg_try_to_go_online: received for domain %s.\n", domainname));
147
148         for (domain = domain_list(); domain; domain = domain->next) {
149                 if (domain->internal) {
150                         continue;
151                 }
152
153                 if (strequal(domain->name, domainname)) {
154
155                         if (domain->online) {
156                                 /* We're already online, ignore. */
157                                 DEBUG(5,("msg_try_to_go_online: domain %s "
158                                         "already online.\n", domainname));
159                                 continue;
160                         }
161
162                         /* This call takes care of setting the online
163                            flag to true if we connected, or re-adding
164                            the offline handler if false. Bypasses online
165                            check so always does network calls. */
166
167                         init_dc_connection_network(domain);
168                         break;
169                 }
170         }
171 }
172
173 /****************************************************************
174  Fork a child to try and contact a DC. Do this as contacting a
175  DC requires blocking lookups and we don't want to block our
176  parent.
177 ****************************************************************/
178
179 static bool fork_child_dc_connect(struct winbindd_domain *domain)
180 {
181         struct dc_name_ip *dcs = NULL;
182         int num_dcs = 0;
183         TALLOC_CTX *mem_ctx = NULL;
184         pid_t parent_pid = sys_getpid();
185         char *lfile = NULL;
186
187         if (domain->dc_probe_pid != (pid_t)-1) {
188                 /*
189                  * We might already have a DC probe
190                  * child working, check.
191                  */
192                 if (process_exists_by_pid(domain->dc_probe_pid)) {
193                         DEBUG(10,("fork_child_dc_connect: pid %u already "
194                                 "checking for DC's.\n",
195                                 (unsigned int)domain->dc_probe_pid));
196                         return true;
197                 }
198                 domain->dc_probe_pid = (pid_t)-1;
199         }
200
201         domain->dc_probe_pid = sys_fork();
202
203         if (domain->dc_probe_pid == (pid_t)-1) {
204                 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
205                 return False;
206         }
207
208         if (domain->dc_probe_pid != (pid_t)0) {
209                 /* Parent */
210                 messaging_register(winbind_messaging_context(), NULL,
211                                    MSG_WINBIND_TRY_TO_GO_ONLINE,
212                                    msg_try_to_go_online);
213                 messaging_register(winbind_messaging_context(), NULL,
214                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
215                                    msg_failed_to_go_online);
216                 return True;
217         }
218
219         /* Child. */
220
221         /* Leave messages blocked - we will never process one. */
222
223         if (!override_logfile) {
224                 if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) == -1) {
225                         DEBUG(0, ("fork_child_dc_connect: out of memory.\n"));
226                         _exit(1);
227                 }
228         }
229
230         if (!winbindd_reinit_after_fork(lfile)) {
231                 messaging_send_buf(winbind_messaging_context(),
232                                    pid_to_procid(parent_pid),
233                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
234                                    (uint8 *)domain->name,
235                                    strlen(domain->name)+1);
236                 _exit(1);
237         }
238         SAFE_FREE(lfile);
239
240         mem_ctx = talloc_init("fork_child_dc_connect");
241         if (!mem_ctx) {
242                 DEBUG(0,("talloc_init failed.\n"));
243                 messaging_send_buf(winbind_messaging_context(),
244                                    pid_to_procid(parent_pid),
245                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
246                                    (uint8 *)domain->name,
247                                    strlen(domain->name)+1);
248                 _exit(1);
249         }
250
251         if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
252                 /* Still offline ? Can't find DC's. */
253                 messaging_send_buf(winbind_messaging_context(),
254                                    pid_to_procid(parent_pid),
255                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
256                                    (uint8 *)domain->name,
257                                    strlen(domain->name)+1);
258                 _exit(0);
259         }
260
261         /* We got a DC. Send a message to our parent to get it to
262            try and do the same. */
263
264         messaging_send_buf(winbind_messaging_context(),
265                            pid_to_procid(parent_pid),
266                            MSG_WINBIND_TRY_TO_GO_ONLINE,
267                            (uint8 *)domain->name,
268                            strlen(domain->name)+1);
269         _exit(0);
270 }
271
272 /****************************************************************
273  Handler triggered if we're offline to try and detect a DC.
274 ****************************************************************/
275
276 static void check_domain_online_handler(struct event_context *ctx,
277                                         struct timed_event *te,
278                                         struct timeval now,
279                                         void *private_data)
280 {
281         struct winbindd_domain *domain =
282                 (struct winbindd_domain *)private_data;
283
284         DEBUG(10,("check_domain_online_handler: called for domain "
285                   "%s (online = %s)\n", domain->name, 
286                   domain->online ? "True" : "False" ));
287
288         TALLOC_FREE(domain->check_online_event);
289
290         /* Are we still in "startup" mode ? */
291
292         if (domain->startup && (now.tv_sec > domain->startup_time + 30)) {
293                 /* No longer in "startup" mode. */
294                 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
295                         domain->name ));
296                 domain->startup = False;
297         }
298
299         /* We've been told to stay offline, so stay
300            that way. */
301
302         if (get_global_winbindd_state_offline()) {
303                 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
304                         domain->name ));
305                 return;
306         }
307
308         /* Fork a child to test if it can contact a DC. 
309            If it can then send ourselves a message to
310            cause a reconnect. */
311
312         fork_child_dc_connect(domain);
313 }
314
315 /****************************************************************
316  If we're still offline setup the timeout check.
317 ****************************************************************/
318
319 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
320 {
321         int wbr = lp_winbind_reconnect_delay();
322
323         if (domain->startup) {
324                 domain->check_online_timeout = 10;
325         } else if (domain->check_online_timeout < wbr) {
326                 domain->check_online_timeout = wbr;
327         }
328 }
329
330 /****************************************************************
331  Set domain offline and also add handler to put us back online
332  if we detect a DC.
333 ****************************************************************/
334
335 void set_domain_offline(struct winbindd_domain *domain)
336 {
337         DEBUG(10,("set_domain_offline: called for domain %s\n",
338                 domain->name ));
339
340         TALLOC_FREE(domain->check_online_event);
341
342         if (domain->internal) {
343                 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
344                         domain->name ));
345                 return;
346         }
347
348         domain->online = False;
349
350         /* Offline domains are always initialized. They're
351            re-initialized when they go back online. */
352
353         domain->initialized = True;
354
355         /* We only add the timeout handler that checks and
356            allows us to go back online when we've not
357            been told to remain offline. */
358
359         if (get_global_winbindd_state_offline()) {
360                 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
361                         domain->name ));
362                 return;
363         }
364
365         /* If we're in startup mode, check again in 10 seconds, not in
366            lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
367
368         calc_new_online_timeout_check(domain);
369
370         domain->check_online_event = event_add_timed(winbind_event_context(),
371                                                 NULL,
372                                                 timeval_current_ofs(domain->check_online_timeout,0),
373                                                 check_domain_online_handler,
374                                                 domain);
375
376         /* The above *has* to succeed for winbindd to work. */
377         if (!domain->check_online_event) {
378                 smb_panic("set_domain_offline: failed to add online handler");
379         }
380
381         DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
382                 domain->name ));
383
384         /* Send an offline message to the idmap child when our
385            primary domain goes offline */
386
387         if ( domain->primary ) {
388                 struct winbindd_child *idmap = idmap_child();
389
390                 if ( idmap->pid != 0 ) {
391                         messaging_send_buf(winbind_messaging_context(),
392                                            pid_to_procid(idmap->pid), 
393                                            MSG_WINBIND_OFFLINE, 
394                                            (uint8 *)domain->name, 
395                                            strlen(domain->name)+1);
396                 }                       
397         }
398
399         return; 
400 }
401
402 /****************************************************************
403  Set domain online - if allowed.
404 ****************************************************************/
405
406 static void set_domain_online(struct winbindd_domain *domain)
407 {
408         DEBUG(10,("set_domain_online: called for domain %s\n",
409                 domain->name ));
410
411         if (domain->internal) {
412                 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
413                         domain->name ));
414                 return;
415         }
416
417         if (get_global_winbindd_state_offline()) {
418                 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
419                         domain->name ));
420                 return;
421         }
422
423         winbindd_set_locator_kdc_envs(domain);
424
425         /* If we are waiting to get a krb5 ticket, trigger immediately. */
426         ccache_regain_all_now();
427
428         /* Ok, we're out of any startup mode now... */
429         domain->startup = False;
430
431         if (domain->online == False) {
432                 /* We were offline - now we're online. We default to
433                    using the MS-RPC backend if we started offline,
434                    and if we're going online for the first time we
435                    should really re-initialize the backends and the
436                    checks to see if we're talking to an AD or NT domain.
437                 */
438
439                 domain->initialized = False;
440
441                 /* 'reconnect_methods' is the MS-RPC backend. */
442                 if (domain->backend == &reconnect_methods) {
443                         domain->backend = NULL;
444                 }
445         }
446
447         /* Ensure we have no online timeout checks. */
448         domain->check_online_timeout = 0;
449         TALLOC_FREE(domain->check_online_event);
450
451         /* Ensure we ignore any pending child messages. */
452         messaging_deregister(winbind_messaging_context(),
453                              MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
454         messaging_deregister(winbind_messaging_context(),
455                              MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
456
457         domain->online = True;
458
459         /* Send an online message to the idmap child when our
460            primary domain comes online */
461
462         if ( domain->primary ) {
463                 struct winbindd_child *idmap = idmap_child();
464
465                 if ( idmap->pid != 0 ) {
466                         messaging_send_buf(winbind_messaging_context(),
467                                            pid_to_procid(idmap->pid), 
468                                            MSG_WINBIND_ONLINE, 
469                                            (uint8 *)domain->name, 
470                                            strlen(domain->name)+1);
471                 }                       
472         }
473
474         return; 
475 }
476
477 /****************************************************************
478  Requested to set a domain online.
479 ****************************************************************/
480
481 void set_domain_online_request(struct winbindd_domain *domain)
482 {
483         struct timeval tev;
484
485         DEBUG(10,("set_domain_online_request: called for domain %s\n",
486                 domain->name ));
487
488         if (get_global_winbindd_state_offline()) {
489                 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
490                         domain->name ));
491                 return;
492         }
493
494         if (domain->internal) {
495                 DEBUG(10, ("set_domain_online_request: Internal domains are "
496                            "always online\n"));
497                 return;
498         }
499
500         /* We've been told it's safe to go online and
501            try and connect to a DC. But I don't believe it
502            because network manager seems to lie.
503            Wait at least 5 seconds. Heuristics suck... */
504
505
506         GetTimeOfDay(&tev);
507
508         /* Go into "startup" mode again. */
509         domain->startup_time = tev.tv_sec;
510         domain->startup = True;
511
512         tev.tv_sec += 5;
513
514         if (!domain->check_online_event) {
515                 /* If we've come from being globally offline we
516                    don't have a check online event handler set.
517                    We need to add one now we're trying to go
518                    back online. */
519
520                 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
521                         domain->name ));
522         }
523
524         TALLOC_FREE(domain->check_online_event);
525
526         domain->check_online_event = event_add_timed(winbind_event_context(),
527                                                      NULL,
528                                                      tev,
529                                                      check_domain_online_handler,
530                                                      domain);
531
532         /* The above *has* to succeed for winbindd to work. */
533         if (!domain->check_online_event) {
534                 smb_panic("set_domain_online_request: failed to add online handler");
535         }
536 }
537
538 /****************************************************************
539  Add -ve connection cache entries for domain and realm.
540 ****************************************************************/
541
542 void winbind_add_failed_connection_entry(const struct winbindd_domain *domain,
543                                         const char *server,
544                                         NTSTATUS result)
545 {
546         add_failed_connection_entry(domain->name, server, result);
547         /* If this was the saf name for the last thing we talked to,
548            remove it. */
549         saf_delete(domain->name);
550         if (*domain->alt_name) {
551                 add_failed_connection_entry(domain->alt_name, server, result);
552                 saf_delete(domain->alt_name);
553         }
554         winbindd_unset_locator_kdc_env(domain);
555 }
556
557 /* Choose between anonymous or authenticated connections.  We need to use
558    an authenticated connection if DCs have the RestrictAnonymous registry
559    entry set > 0, or the "Additional restrictions for anonymous
560    connections" set in the win2k Local Security Policy. 
561
562    Caller to free() result in domain, username, password
563 */
564
565 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
566 {
567         *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
568         *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
569         *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
570
571         if (*username && **username) {
572
573                 if (!*domain || !**domain)
574                         *domain = smb_xstrdup(lp_workgroup());
575
576                 if (!*password || !**password)
577                         *password = smb_xstrdup("");
578
579                 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n", 
580                           *domain, *username));
581
582         } else {
583                 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
584                 *username = smb_xstrdup("");
585                 *domain = smb_xstrdup("");
586                 *password = smb_xstrdup("");
587         }
588 }
589
590 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
591                                      fstring dcname,
592                                      struct sockaddr_storage *dc_ss)
593 {
594         struct winbindd_domain *our_domain = NULL;
595         struct rpc_pipe_client *netlogon_pipe = NULL;
596         NTSTATUS result;
597         WERROR werr;
598         TALLOC_CTX *mem_ctx;
599         unsigned int orig_timeout;
600         const char *tmp = NULL;
601         const char *p;
602
603         /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
604          * moment.... */
605
606         if (IS_DC) {
607                 return False;
608         }
609
610         if (domain->primary) {
611                 return False;
612         }
613
614         our_domain = find_our_domain();
615
616         if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
617                 return False;
618         }
619
620         result = cm_connect_netlogon(our_domain, &netlogon_pipe);
621         if (!NT_STATUS_IS_OK(result)) {
622                 talloc_destroy(mem_ctx);
623                 return False;
624         }
625
626         /* This call can take a long time - allow the server to time out.
627            35 seconds should do it. */
628
629         orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
630
631         if (our_domain->active_directory) {
632                 struct netr_DsRGetDCNameInfo *domain_info = NULL;
633
634                 result = rpccli_netr_DsRGetDCName(netlogon_pipe,
635                                                   mem_ctx,
636                                                   our_domain->dcname,
637                                                   domain->name,
638                                                   NULL,
639                                                   NULL,
640                                                   DS_RETURN_DNS_NAME,
641                                                   &domain_info,
642                                                   &werr);
643                 if (NT_STATUS_IS_OK(result) && W_ERROR_IS_OK(werr)) {
644                         tmp = talloc_strdup(
645                                 mem_ctx, domain_info->dc_unc);
646                         if (tmp == NULL) {
647                                 DEBUG(0, ("talloc_strdup failed\n"));
648                                 talloc_destroy(mem_ctx);
649                                 return false;
650                         }
651                         if (strlen(domain->alt_name) == 0) {
652                                 fstrcpy(domain->alt_name,
653                                         domain_info->domain_name);
654                         }
655                         if (strlen(domain->forest_name) == 0) {
656                                 fstrcpy(domain->forest_name,
657                                         domain_info->forest_name);
658                         }
659                 }
660         } else {
661                 result = rpccli_netr_GetAnyDCName(netlogon_pipe, mem_ctx,
662                                                   our_domain->dcname,
663                                                   domain->name,
664                                                   &tmp,
665                                                   &werr);
666         }
667
668         /* And restore our original timeout. */
669         rpccli_set_timeout(netlogon_pipe, orig_timeout);
670
671         if (!NT_STATUS_IS_OK(result)) {
672                 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
673                         nt_errstr(result)));
674                 talloc_destroy(mem_ctx);
675                 return false;
676         }
677
678         if (!W_ERROR_IS_OK(werr)) {
679                 DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
680                            win_errstr(werr)));
681                 talloc_destroy(mem_ctx);
682                 return false;
683         }
684
685         /* rpccli_netr_GetAnyDCName gives us a name with \\ */
686         p = strip_hostname(tmp);
687
688         fstrcpy(dcname, p);
689
690         talloc_destroy(mem_ctx);
691
692         DEBUG(10,("rpccli_netr_GetAnyDCName returned %s\n", dcname));
693
694         if (!resolve_name(dcname, dc_ss, 0x20, true)) {
695                 return False;
696         }
697
698         return True;
699 }
700
701 /**
702  * Helper function to assemble trust password and account name
703  */
704 static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
705                                 char **machine_password,
706                                 char **machine_account,
707                                 char **machine_krb5_principal)
708 {
709         const char *account_name;
710         const char *name = NULL;
711
712         /* If we are a DC and this is not our own domain */
713
714         if (IS_DC) {
715                 name = domain->name;
716         } else {
717                 struct winbindd_domain *our_domain = find_our_domain();
718
719                 if (!our_domain)
720                         return NT_STATUS_INVALID_SERVER_STATE;          
721
722                 name = our_domain->name;                
723         }       
724
725         if (!get_trust_pw_clear(name, machine_password,
726                                 &account_name, NULL))
727         {
728                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
729         }
730
731         if ((machine_account != NULL) &&
732             (asprintf(machine_account, "%s$", account_name) == -1))
733         {
734                 return NT_STATUS_NO_MEMORY;
735         }
736
737         /* For now assume our machine account only exists in our domain */
738
739         if (machine_krb5_principal != NULL)
740         {
741                 struct winbindd_domain *our_domain = find_our_domain();
742
743                 if (!our_domain) {
744                         return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;                       
745                 }
746
747                 if (asprintf(machine_krb5_principal, "%s$@%s",
748                              account_name, our_domain->alt_name) == -1)
749                 {
750                         return NT_STATUS_NO_MEMORY;
751                 }
752
753                 strupper_m(*machine_krb5_principal);
754         }
755
756         return NT_STATUS_OK;
757 }
758
759 /************************************************************************
760  Given a fd with a just-connected TCP connection to a DC, open a connection
761  to the pipe.
762 ************************************************************************/
763
764 static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
765                                       const int sockfd,
766                                       const char *controller,
767                                       struct cli_state **cli,
768                                       bool *retry)
769 {
770         char *machine_password = NULL;
771         char *machine_krb5_principal = NULL;
772         char *machine_account = NULL;
773         char *ipc_username = NULL;
774         char *ipc_domain = NULL;
775         char *ipc_password = NULL;
776
777         struct named_mutex *mutex;
778
779         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
780
781         struct sockaddr peeraddr;
782         socklen_t peeraddr_len;
783
784         struct sockaddr_in *peeraddr_in =
785                 (struct sockaddr_in *)(void *)&peeraddr;
786
787         DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
788                 controller, domain->name ));
789
790         *retry = True;
791
792         mutex = grab_named_mutex(talloc_tos(), controller,
793                                  WINBIND_SERVER_MUTEX_WAIT_TIME);
794         if (mutex == NULL) {
795                 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
796                          controller));
797                 result = NT_STATUS_POSSIBLE_DEADLOCK;
798                 goto done;
799         }
800
801         if ((*cli = cli_initialise()) == NULL) {
802                 DEBUG(1, ("Could not cli_initialize\n"));
803                 result = NT_STATUS_NO_MEMORY;
804                 goto done;
805         }
806
807         (*cli)->timeout = 10000;        /* 10 seconds */
808         (*cli)->fd = sockfd;
809         fstrcpy((*cli)->desthost, controller);
810         (*cli)->use_kerberos = True;
811
812         peeraddr_len = sizeof(peeraddr);
813
814         if ((getpeername((*cli)->fd, &peeraddr, &peeraddr_len) != 0)) {
815                 DEBUG(0,("cm_prepare_connection: getpeername failed with: %s\n",
816                         strerror(errno)));
817                 result = NT_STATUS_UNSUCCESSFUL;
818                 goto done;
819         }
820
821         if ((peeraddr_len != sizeof(struct sockaddr_in))
822 #ifdef HAVE_IPV6
823             && (peeraddr_len != sizeof(struct sockaddr_in6))
824 #endif
825             ) {
826                 DEBUG(0,("cm_prepare_connection: got unexpected peeraddr len %d\n",
827                         peeraddr_len));
828                 result = NT_STATUS_UNSUCCESSFUL;
829                 goto done;
830         }
831
832         if ((peeraddr_in->sin_family != PF_INET)
833 #ifdef HAVE_IPV6
834             && (peeraddr_in->sin_family != PF_INET6)
835 #endif
836             ) {
837                 DEBUG(0,("cm_prepare_connection: got unexpected family %d\n",
838                         peeraddr_in->sin_family));
839                 result = NT_STATUS_UNSUCCESSFUL;
840                 goto done;
841         }
842
843         if (ntohs(peeraddr_in->sin_port) == 139) {
844                 struct nmb_name calling;
845                 struct nmb_name called;
846
847                 make_nmb_name(&calling, global_myname(), 0x0);
848                 make_nmb_name(&called, "*SMBSERVER", 0x20);
849
850                 if (!cli_session_request(*cli, &calling, &called)) {
851                         DEBUG(8, ("cli_session_request failed for %s\n",
852                                   controller));
853                         result = NT_STATUS_UNSUCCESSFUL;
854                         goto done;
855                 }
856         }
857
858         result = cli_negprot(*cli);
859
860         if (!NT_STATUS_IS_OK(result)) {
861                 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
862                 goto done;
863         }
864
865         if (!is_dc_trusted_domain_situation(domain->name) &&
866             (*cli)->protocol >= PROTOCOL_NT1 &&
867             (*cli)->capabilities & CAP_EXTENDED_SECURITY)
868         {
869                 ADS_STATUS ads_status;
870
871                 result = get_trust_creds(domain, &machine_password,
872                                          &machine_account,
873                                          &machine_krb5_principal);
874                 if (!NT_STATUS_IS_OK(result)) {
875                         goto anon_fallback;
876                 }
877
878                 if (lp_security() == SEC_ADS) {
879
880                         /* Try a krb5 session */
881
882                         (*cli)->use_kerberos = True;
883                         DEBUG(5, ("connecting to %s from %s with kerberos principal "
884                                   "[%s] and realm [%s]\n", controller, global_myname(),
885                                   machine_krb5_principal, domain->alt_name));
886
887                         winbindd_set_locator_kdc_envs(domain);
888
889                         ads_status = cli_session_setup_spnego(*cli,
890                                                               machine_krb5_principal, 
891                                                               machine_password,
892                                                               lp_workgroup(),
893                                                               domain->alt_name);
894
895                         if (!ADS_ERR_OK(ads_status)) {
896                                 DEBUG(4,("failed kerberos session setup with %s\n",
897                                          ads_errstr(ads_status)));
898                         }
899
900                         result = ads_ntstatus(ads_status);
901                         if (NT_STATUS_IS_OK(result)) {
902                                 /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
903                                 result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
904                                 if (!NT_STATUS_IS_OK(result)) {
905                                         goto done;
906                                 }
907                                 goto session_setup_done;
908                         }
909                 }
910
911                 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
912                 (*cli)->use_kerberos = False;
913
914                 DEBUG(5, ("connecting to %s from %s with username "
915                           "[%s]\\[%s]\n",  controller, global_myname(),
916                           lp_workgroup(), machine_account));
917
918                 ads_status = cli_session_setup_spnego(*cli,
919                                                       machine_account, 
920                                                       machine_password, 
921                                                       lp_workgroup(),
922                                                       NULL);
923                 if (!ADS_ERR_OK(ads_status)) {
924                         DEBUG(4, ("authenticated session setup failed with %s\n",
925                                 ads_errstr(ads_status)));
926                 }
927
928                 result = ads_ntstatus(ads_status);
929                 if (NT_STATUS_IS_OK(result)) {
930                         /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
931                         result = cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
932                         if (!NT_STATUS_IS_OK(result)) {
933                                 goto done;
934                         }
935                         goto session_setup_done;
936                 }
937         }
938
939         /* Fall back to non-kerberos session setup with auth_user */
940
941         (*cli)->use_kerberos = False;
942
943         cm_get_ipc_userpass(&ipc_username, &ipc_domain, &ipc_password);
944
945         if ((((*cli)->sec_mode & NEGOTIATE_SECURITY_CHALLENGE_RESPONSE) != 0) &&
946             (strlen(ipc_username) > 0)) {
947
948                 /* Only try authenticated if we have a username */
949
950                 DEBUG(5, ("connecting to %s from %s with username "
951                           "[%s]\\[%s]\n",  controller, global_myname(),
952                           ipc_domain, ipc_username));
953
954                 if (NT_STATUS_IS_OK(cli_session_setup(
955                                             *cli, ipc_username,
956                                             ipc_password, strlen(ipc_password)+1,
957                                             ipc_password, strlen(ipc_password)+1,
958                                             ipc_domain))) {
959                         /* Successful logon with given username. */
960                         result = cli_init_creds(*cli, ipc_username, ipc_domain, ipc_password);
961                         if (!NT_STATUS_IS_OK(result)) {
962                                 goto done;
963                         }
964                         goto session_setup_done;
965                 } else {
966                         DEBUG(4, ("authenticated session setup with user %s\\%s failed.\n",
967                                 ipc_domain, ipc_username ));
968                 }
969         }
970
971  anon_fallback:
972
973         /* Fall back to anonymous connection, this might fail later */
974         DEBUG(10,("cm_prepare_connection: falling back to anonymous "
975                 "connection for DC %s\n",
976                 controller ));
977
978         if (NT_STATUS_IS_OK(cli_session_setup(*cli, "", NULL, 0,
979                                               NULL, 0, ""))) {
980                 DEBUG(5, ("Connected anonymously\n"));
981                 result = cli_init_creds(*cli, "", "", "");
982                 if (!NT_STATUS_IS_OK(result)) {
983                         goto done;
984                 }
985                 goto session_setup_done;
986         }
987
988         result = cli_nt_error(*cli);
989
990         if (NT_STATUS_IS_OK(result))
991                 result = NT_STATUS_UNSUCCESSFUL;
992
993         /* We can't session setup */
994
995         goto done;
996
997  session_setup_done:
998
999         /* cache the server name for later connections */
1000
1001         saf_store( domain->name, (*cli)->desthost );
1002         if (domain->alt_name && (*cli)->use_kerberos) {
1003                 saf_store( domain->alt_name, (*cli)->desthost );
1004         }
1005
1006         winbindd_set_locator_kdc_envs(domain);
1007
1008         result = cli_tcon_andx(*cli, "IPC$", "IPC", "", 0);
1009
1010         if (!NT_STATUS_IS_OK(result)) {
1011                 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
1012                 goto done;
1013         }
1014
1015         TALLOC_FREE(mutex);
1016         *retry = False;
1017
1018         /* set the domain if empty; needed for schannel connections */
1019         if ( !(*cli)->domain[0] ) {
1020                 result = cli_set_domain((*cli), domain->name);
1021                 if (!NT_STATUS_IS_OK(result)) {
1022                         return result;
1023                 }
1024         }
1025
1026         result = NT_STATUS_OK;
1027
1028  done:
1029         TALLOC_FREE(mutex);
1030         SAFE_FREE(machine_account);
1031         SAFE_FREE(machine_password);
1032         SAFE_FREE(machine_krb5_principal);
1033         SAFE_FREE(ipc_username);
1034         SAFE_FREE(ipc_domain);
1035         SAFE_FREE(ipc_password);
1036
1037         if (!NT_STATUS_IS_OK(result)) {
1038                 winbind_add_failed_connection_entry(domain, controller, result);
1039                 if ((*cli) != NULL) {
1040                         cli_shutdown(*cli);
1041                         *cli = NULL;
1042                 }
1043         }
1044
1045         return result;
1046 }
1047
1048 /*******************************************************************
1049  Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1050  array.
1051
1052  Keeps the list unique by not adding duplicate entries.
1053
1054  @param[in] mem_ctx talloc memory context to allocate from
1055  @param[in] domain_name domain of the DC
1056  @param[in] dcname name of the DC to add to the list
1057  @param[in] pss Internet address and port pair to add to the list
1058  @param[in,out] dcs array of dc_name_ip structures to add to
1059  @param[in,out] num_dcs number of dcs returned in the dcs array
1060  @return true if the list was added to, false otherwise
1061 *******************************************************************/
1062
1063 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1064                               const char *dcname, struct sockaddr_storage *pss,
1065                               struct dc_name_ip **dcs, int *num)
1066 {
1067         int i = 0;
1068
1069         if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1070                 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1071                 return False;
1072         }
1073
1074         /* Make sure there's no duplicates in the list */
1075         for (i=0; i<*num; i++)
1076                 if (sockaddr_equal(
1077                             (struct sockaddr *)(void *)&(*dcs)[i].ss,
1078                             (struct sockaddr *)(void *)pss))
1079                         return False;
1080
1081         *dcs = TALLOC_REALLOC_ARRAY(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1082
1083         if (*dcs == NULL)
1084                 return False;
1085
1086         fstrcpy((*dcs)[*num].name, dcname);
1087         (*dcs)[*num].ss = *pss;
1088         *num += 1;
1089         return True;
1090 }
1091
1092 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1093                                   struct sockaddr_storage *pss, uint16 port,
1094                                   struct sockaddr_storage **addrs, int *num)
1095 {
1096         *addrs = TALLOC_REALLOC_ARRAY(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1097
1098         if (*addrs == NULL) {
1099                 *num = 0;
1100                 return False;
1101         }
1102
1103         (*addrs)[*num] = *pss;
1104         set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1105
1106         *num += 1;
1107         return True;
1108 }
1109
1110 /*******************************************************************
1111  convert an ip to a name
1112 *******************************************************************/
1113
1114 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1115                 const struct winbindd_domain *domain,
1116                 struct sockaddr_storage *pss,
1117                 fstring name )
1118 {
1119         struct ip_service ip_list;
1120         uint32_t nt_version = NETLOGON_NT_VERSION_1;
1121
1122         ip_list.ss = *pss;
1123         ip_list.port = 0;
1124
1125 #ifdef WITH_ADS
1126         /* For active directory servers, try to get the ldap server name.
1127            None of these failures should be considered critical for now */
1128
1129         if (lp_security() == SEC_ADS) {
1130                 ADS_STRUCT *ads;
1131                 ADS_STATUS ads_status;
1132                 char addr[INET6_ADDRSTRLEN];
1133
1134                 print_sockaddr(addr, sizeof(addr), pss);
1135
1136                 ads = ads_init(domain->alt_name, domain->name, addr);
1137                 ads->auth.flags |= ADS_AUTH_NO_BIND;
1138
1139                 ads_status = ads_connect(ads);
1140                 if (ADS_ERR_OK(ads_status)) {
1141                         /* We got a cldap packet. */
1142                         fstrcpy(name, ads->config.ldap_server_name);
1143                         namecache_store(name, 0x20, 1, &ip_list);
1144
1145                         DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1146
1147                         if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1148                                 if (ads_closest_dc(ads)) {
1149                                         char *sitename = sitename_fetch(ads->config.realm);
1150
1151                                         /* We're going to use this KDC for this realm/domain.
1152                                            If we are using sites, then force the krb5 libs
1153                                            to use this KDC. */
1154
1155                                         create_local_private_krb5_conf_for_domain(domain->alt_name,
1156                                                                         domain->name,
1157                                                                         sitename,
1158                                                                         pss,
1159                                                                         name);
1160
1161                                         SAFE_FREE(sitename);
1162                                 } else {
1163                                         /* use an off site KDC */
1164                                         create_local_private_krb5_conf_for_domain(domain->alt_name,
1165                                                                         domain->name,
1166                                                                         NULL,
1167                                                                         pss,
1168                                                                         name);
1169                                 }
1170                                 winbindd_set_locator_kdc_envs(domain);
1171
1172                                 /* Ensure we contact this DC also. */
1173                                 saf_store( domain->name, name);
1174                                 saf_store( domain->alt_name, name);
1175                         }
1176
1177                         ads_destroy( &ads );
1178                         return True;
1179                 }
1180
1181                 ads_destroy( &ads );
1182         }
1183 #endif
1184
1185         /* try GETDC requests next */
1186
1187         if (send_getdc_request(mem_ctx, winbind_messaging_context(),
1188                                pss, domain->name, &domain->sid,
1189                                nt_version)) {
1190                 const char *dc_name = NULL;
1191                 int i;
1192                 smb_msleep(100);
1193                 for (i=0; i<5; i++) {
1194                         if (receive_getdc_response(mem_ctx, pss, domain->name,
1195                                                    &nt_version,
1196                                                    &dc_name, NULL)) {
1197                                 fstrcpy(name, dc_name);
1198                                 namecache_store(name, 0x20, 1, &ip_list);
1199                                 return True;
1200                         }
1201                         smb_msleep(500);
1202                 }
1203         }
1204
1205         /* try node status request */
1206
1207         if ( name_status_find(domain->name, 0x1c, 0x20, pss, name) ) {
1208                 namecache_store(name, 0x20, 1, &ip_list);
1209                 return True;
1210         }
1211         return False;
1212 }
1213
1214 /*******************************************************************
1215  Retrieve a list of IP addresses for domain controllers.
1216
1217  The array is sorted in the preferred connection order.
1218
1219  @param[in] mem_ctx talloc memory context to allocate from
1220  @param[in] domain domain to retrieve DCs for
1221  @param[out] dcs array of dcs that will be returned
1222  @param[out] num_dcs number of dcs returned in the dcs array
1223  @return always true
1224 *******************************************************************/
1225
1226 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1227                     struct dc_name_ip **dcs, int *num_dcs)
1228 {
1229         fstring dcname;
1230         struct  sockaddr_storage ss;
1231         struct  ip_service *ip_list = NULL;
1232         int     iplist_size = 0;
1233         int     i;
1234         bool    is_our_domain;
1235         enum security_types sec = (enum security_types)lp_security();
1236
1237         is_our_domain = strequal(domain->name, lp_workgroup());
1238
1239         /* If not our domain, get the preferred DC, by asking our primary DC */
1240         if ( !is_our_domain
1241                 && get_dc_name_via_netlogon(domain, dcname, &ss)
1242                 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1243                        num_dcs) )
1244         {
1245                 char addr[INET6_ADDRSTRLEN];
1246                 print_sockaddr(addr, sizeof(addr), &ss);
1247                 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1248                            dcname, addr));
1249                 return True;
1250         }
1251
1252         if (sec == SEC_ADS) {
1253                 char *sitename = NULL;
1254
1255                 /* We need to make sure we know the local site before
1256                    doing any DNS queries, as this will restrict the
1257                    get_sorted_dc_list() call below to only fetching
1258                    DNS records for the correct site. */
1259
1260                 /* Find any DC to get the site record.
1261                    We deliberately don't care about the
1262                    return here. */
1263
1264                 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1265
1266                 sitename = sitename_fetch(domain->alt_name);
1267                 if (sitename) {
1268
1269                         /* Do the site-specific AD dns lookup first. */
1270                         get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1271                                &iplist_size, True);
1272
1273                         /* Add ips to the DC array.  We don't look up the name
1274                            of the DC in this function, but we fill in the char*
1275                            of the ip now to make the failed connection cache
1276                            work */
1277                         for ( i=0; i<iplist_size; i++ ) {
1278                                 char addr[INET6_ADDRSTRLEN];
1279                                 print_sockaddr(addr, sizeof(addr),
1280                                                 &ip_list[i].ss);
1281                                 add_one_dc_unique(mem_ctx,
1282                                                 domain->name,
1283                                                 addr,
1284                                                 &ip_list[i].ss,
1285                                                 dcs,
1286                                                 num_dcs);
1287                         }
1288
1289                         SAFE_FREE(ip_list);
1290                         SAFE_FREE(sitename);
1291                         iplist_size = 0;
1292                 }
1293
1294                 /* Now we add DCs from the main AD DNS lookup. */
1295                 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1296                         &iplist_size, True);
1297
1298                 for ( i=0; i<iplist_size; i++ ) {
1299                         char addr[INET6_ADDRSTRLEN];
1300                         print_sockaddr(addr, sizeof(addr),
1301                                         &ip_list[i].ss);
1302                         add_one_dc_unique(mem_ctx,
1303                                         domain->name,
1304                                         addr,
1305                                         &ip_list[i].ss,
1306                                         dcs,
1307                                         num_dcs);
1308                 }
1309
1310                 SAFE_FREE(ip_list);
1311                 iplist_size = 0;
1312         }
1313
1314         /* Try standard netbios queries if no ADS */
1315         if (*num_dcs == 0) {
1316                 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1317                        False);
1318
1319                 for ( i=0; i<iplist_size; i++ ) {
1320                         char addr[INET6_ADDRSTRLEN];
1321                         print_sockaddr(addr, sizeof(addr),
1322                                         &ip_list[i].ss);
1323                         add_one_dc_unique(mem_ctx,
1324                                         domain->name,
1325                                         addr,
1326                                         &ip_list[i].ss,
1327                                         dcs,
1328                                         num_dcs);
1329                 }
1330
1331                 SAFE_FREE(ip_list);
1332                 iplist_size = 0;
1333         }
1334
1335         return True;
1336 }
1337
1338 /*******************************************************************
1339  Find and make a connection to a DC in the given domain.
1340
1341  @param[in] mem_ctx talloc memory context to allocate from
1342  @param[in] domain domain to find a dc in
1343  @param[out] dcname NetBIOS or FQDN of DC that's connected to
1344  @param[out] pss DC Internet address and port
1345  @param[out] fd fd of the open socket connected to the newly found dc
1346  @return true when a DC connection is made, false otherwise
1347 *******************************************************************/
1348
1349 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1350                         struct winbindd_domain *domain,
1351                         fstring dcname, struct sockaddr_storage *pss, int *fd)
1352 {
1353         struct dc_name_ip *dcs = NULL;
1354         int num_dcs = 0;
1355
1356         const char **dcnames = NULL;
1357         int num_dcnames = 0;
1358
1359         struct sockaddr_storage *addrs = NULL;
1360         int num_addrs = 0;
1361
1362         int i, fd_index;
1363
1364         *fd = -1;
1365
1366  again:
1367         if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1368                 return False;
1369
1370         for (i=0; i<num_dcs; i++) {
1371
1372                 if (!add_string_to_array(mem_ctx, dcs[i].name,
1373                                     &dcnames, &num_dcnames)) {
1374                         return False;
1375                 }
1376                 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 445,
1377                                       &addrs, &num_addrs)) {
1378                         return False;
1379                 }
1380
1381                 if (!add_string_to_array(mem_ctx, dcs[i].name,
1382                                     &dcnames, &num_dcnames)) {
1383                         return False;
1384                 }
1385                 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, 139,
1386                                       &addrs, &num_addrs)) {
1387                         return False;
1388                 }
1389         }
1390
1391         if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1392                 return False;
1393
1394         if ((addrs == NULL) || (dcnames == NULL))
1395                 return False;
1396
1397         /* 5 second timeout. */
1398         if (!open_any_socket_out(addrs, num_addrs, 5000, &fd_index, fd) ) {
1399                 for (i=0; i<num_dcs; i++) {
1400                         char ab[INET6_ADDRSTRLEN];
1401                         print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1402                         DEBUG(10, ("find_new_dc: open_any_socket_out failed for "
1403                                 "domain %s address %s. Error was %s\n",
1404                                 domain->name, ab, strerror(errno) ));
1405                         winbind_add_failed_connection_entry(domain,
1406                                 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1407                 }
1408                 return False;
1409         }
1410
1411         *pss = addrs[fd_index];
1412
1413         if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1414                 /* Ok, we've got a name for the DC */
1415                 fstrcpy(dcname, dcnames[fd_index]);
1416                 return True;
1417         }
1418
1419         /* Try to figure out the name */
1420         if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1421                 return True;
1422         }
1423
1424         /* We can not continue without the DC's name */
1425         winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1426                                     NT_STATUS_UNSUCCESSFUL);
1427
1428         /* Throw away all arrays as we're doing this again. */
1429         TALLOC_FREE(dcs);
1430         num_dcs = 0;
1431
1432         TALLOC_FREE(dcnames);
1433         num_dcnames = 0;
1434
1435         TALLOC_FREE(addrs);
1436         num_addrs = 0;
1437
1438         close(*fd);
1439         *fd = -1;
1440
1441         goto again;
1442 }
1443
1444 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1445                                    struct winbindd_cm_conn *new_conn)
1446 {
1447         TALLOC_CTX *mem_ctx;
1448         NTSTATUS result;
1449         char *saf_servername = saf_fetch( domain->name );
1450         int retries;
1451
1452         if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1453                 SAFE_FREE(saf_servername);
1454                 set_domain_offline(domain);
1455                 return NT_STATUS_NO_MEMORY;
1456         }
1457
1458         /* we have to check the server affinity cache here since 
1459            later we selecte a DC based on response time and not preference */
1460
1461         /* Check the negative connection cache
1462            before talking to it. It going down may have
1463            triggered the reconnection. */
1464
1465         if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1466
1467                 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1468                         saf_servername, domain->name ));
1469
1470                 /* convert an ip address to a name */
1471                 if (is_ipaddress( saf_servername ) ) {
1472                         fstring saf_name;
1473                         struct sockaddr_storage ss;
1474
1475                         if (!interpret_string_addr(&ss, saf_servername,
1476                                                 AI_NUMERICHOST)) {
1477                                 return NT_STATUS_UNSUCCESSFUL;
1478                         }
1479                         if (dcip_to_name(mem_ctx, domain, &ss, saf_name )) {
1480                                 fstrcpy( domain->dcname, saf_name );
1481                         } else {
1482                                 winbind_add_failed_connection_entry(
1483                                         domain, saf_servername,
1484                                         NT_STATUS_UNSUCCESSFUL);
1485                         }
1486                 } else {
1487                         fstrcpy( domain->dcname, saf_servername );
1488                 }
1489
1490                 SAFE_FREE( saf_servername );
1491         }
1492
1493         for (retries = 0; retries < 3; retries++) {
1494                 int fd = -1;
1495                 bool retry = False;
1496
1497                 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1498
1499                 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1500                         domain->dcname, domain->name ));
1501
1502                 if (*domain->dcname 
1503                         && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1504                         && (resolve_name(domain->dcname, &domain->dcaddr, 0x20, true)))
1505                 {
1506                         struct sockaddr_storage *addrs = NULL;
1507                         int num_addrs = 0;
1508                         int dummy = 0;
1509
1510                         if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 445, &addrs, &num_addrs)) {
1511                                 set_domain_offline(domain);
1512                                 talloc_destroy(mem_ctx);
1513                                 return NT_STATUS_NO_MEMORY;
1514                         }
1515                         if (!add_sockaddr_to_array(mem_ctx, &domain->dcaddr, 139, &addrs, &num_addrs)) {
1516                                 set_domain_offline(domain);
1517                                 talloc_destroy(mem_ctx);
1518                                 return NT_STATUS_NO_MEMORY;
1519                         }
1520
1521                         /* 5 second timeout. */
1522                         if (!open_any_socket_out(addrs, num_addrs, 5000, &dummy, &fd)) {
1523                                 fd = -1;
1524                         }
1525                 }
1526
1527                 if ((fd == -1) 
1528                         && !find_new_dc(mem_ctx, domain, domain->dcname, &domain->dcaddr, &fd))
1529                 {
1530                         /* This is the one place where we will
1531                            set the global winbindd offline state
1532                            to true, if a "WINBINDD_OFFLINE" entry
1533                            is found in the winbindd cache. */
1534                         set_global_winbindd_state_offline();
1535                         break;
1536                 }
1537
1538                 new_conn->cli = NULL;
1539
1540                 result = cm_prepare_connection(domain, fd, domain->dcname,
1541                         &new_conn->cli, &retry);
1542
1543                 if (!retry)
1544                         break;
1545         }
1546
1547         if (NT_STATUS_IS_OK(result)) {
1548
1549                 winbindd_set_locator_kdc_envs(domain);
1550
1551                 if (domain->online == False) {
1552                         /* We're changing state from offline to online. */
1553                         set_global_winbindd_state_online();
1554                 }
1555                 set_domain_online(domain);
1556         } else {
1557                 /* Ensure we setup the retry handler. */
1558                 set_domain_offline(domain);
1559         }
1560
1561         talloc_destroy(mem_ctx);
1562         return result;
1563 }
1564
1565 /* Close down all open pipes on a connection. */
1566
1567 void invalidate_cm_connection(struct winbindd_cm_conn *conn)
1568 {
1569         /* We're closing down a possibly dead
1570            connection. Don't have impossibly long (10s) timeouts. */
1571
1572         if (conn->cli) {
1573                 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1574         }
1575
1576         if (conn->samr_pipe != NULL) {
1577                 if (is_valid_policy_hnd(&conn->sam_connect_handle)) {
1578                         rpccli_samr_Close(conn->samr_pipe, talloc_tos(),
1579                                           &conn->sam_connect_handle);
1580                 }
1581                 TALLOC_FREE(conn->samr_pipe);
1582                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1583                 if (conn->cli) {
1584                         cli_set_timeout(conn->cli, 500);
1585                 }
1586         }
1587
1588         if (conn->lsa_pipe != NULL) {
1589                 if (is_valid_policy_hnd(&conn->lsa_policy)) {
1590                         rpccli_lsa_Close(conn->lsa_pipe, talloc_tos(),
1591                                          &conn->lsa_policy);
1592                 }
1593                 TALLOC_FREE(conn->lsa_pipe);
1594                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1595                 if (conn->cli) {
1596                         cli_set_timeout(conn->cli, 500);
1597                 }
1598         }
1599
1600         if (conn->lsa_pipe_tcp != NULL) {
1601                 if (is_valid_policy_hnd(&conn->lsa_policy)) {
1602                         rpccli_lsa_Close(conn->lsa_pipe, talloc_tos(),
1603                                          &conn->lsa_policy);
1604                 }
1605                 TALLOC_FREE(conn->lsa_pipe_tcp);
1606                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1607                 if (conn->cli) {
1608                         cli_set_timeout(conn->cli, 500);
1609                 }
1610         }
1611
1612         if (conn->netlogon_pipe != NULL) {
1613                 TALLOC_FREE(conn->netlogon_pipe);
1614                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
1615                 if (conn->cli) {
1616                         cli_set_timeout(conn->cli, 500);
1617                 }
1618         }
1619
1620         if (conn->cli) {
1621                 cli_shutdown(conn->cli);
1622         }
1623
1624         conn->cli = NULL;
1625 }
1626
1627 void close_conns_after_fork(void)
1628 {
1629         struct winbindd_domain *domain;
1630
1631         for (domain = domain_list(); domain; domain = domain->next) {
1632                 struct cli_state *cli = domain->conn.cli;
1633
1634                 /*
1635                  * first close the low level SMB TCP connection
1636                  * so that we don't generate any SMBclose
1637                  * requests in invalidate_cm_connection()
1638                  */
1639                 if (cli && cli->fd != -1) {
1640                         close(domain->conn.cli->fd);
1641                         domain->conn.cli->fd = -1;
1642                 }
1643
1644                 invalidate_cm_connection(&domain->conn);
1645         }
1646 }
1647
1648 static bool connection_ok(struct winbindd_domain *domain)
1649 {
1650         bool ok;
1651
1652         ok = cli_state_is_connected(domain->conn.cli);
1653         if (!ok) {
1654                 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
1655                           domain->dcname, domain->name));
1656                 return False;
1657         }
1658
1659         if (domain->online == False) {
1660                 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
1661                 return False;
1662         }
1663
1664         return True;
1665 }
1666
1667 /* Initialize a new connection up to the RPC BIND.
1668    Bypass online status check so always does network calls. */
1669
1670 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain)
1671 {
1672         NTSTATUS result;
1673
1674         /* Internal connections never use the network. */
1675         if (domain->internal) {
1676                 domain->initialized = True;
1677                 return NT_STATUS_OK;
1678         }
1679
1680         if (!winbindd_can_contact_domain(domain)) {
1681                 invalidate_cm_connection(&domain->conn);
1682                 domain->initialized = True;
1683                 return NT_STATUS_OK;
1684         }
1685
1686         if (connection_ok(domain)) {
1687                 if (!domain->initialized) {
1688                         set_dc_type_and_flags(domain);
1689                 }
1690                 return NT_STATUS_OK;
1691         }
1692
1693         invalidate_cm_connection(&domain->conn);
1694
1695         result = cm_open_connection(domain, &domain->conn);
1696
1697         if (NT_STATUS_IS_OK(result) && !domain->initialized) {
1698                 set_dc_type_and_flags(domain);
1699         }
1700
1701         return result;
1702 }
1703
1704 NTSTATUS init_dc_connection(struct winbindd_domain *domain)
1705 {
1706         if (domain->internal) {
1707                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1708         }
1709
1710         if (domain->initialized && !domain->online) {
1711                 /* We check for online status elsewhere. */
1712                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1713         }
1714
1715         return init_dc_connection_network(domain);
1716 }
1717
1718 static NTSTATUS init_dc_connection_rpc(struct winbindd_domain *domain)
1719 {
1720         NTSTATUS status;
1721
1722         status = init_dc_connection(domain);
1723         if (!NT_STATUS_IS_OK(status)) {
1724                 return status;
1725         }
1726
1727         if (!domain->internal && domain->conn.cli == NULL) {
1728                 /* happens for trusted domains without inbound trust */
1729                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
1730         }
1731
1732         return NT_STATUS_OK;
1733 }
1734
1735 /******************************************************************************
1736  Set the trust flags (direction and forest location) for a domain
1737 ******************************************************************************/
1738
1739 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
1740 {
1741         struct winbindd_domain *our_domain;
1742         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
1743         struct netr_DomainTrustList trusts;
1744         int i;
1745         uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
1746                         NETR_TRUST_FLAG_OUTBOUND |
1747                         NETR_TRUST_FLAG_INBOUND);
1748         struct rpc_pipe_client *cli;
1749         TALLOC_CTX *mem_ctx = NULL;
1750
1751         DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
1752
1753         /* Our primary domain doesn't need to worry about trust flags.
1754            Force it to go through the network setup */
1755         if ( domain->primary ) {                
1756                 return False;           
1757         }
1758
1759         our_domain = find_our_domain();
1760
1761         if ( !connection_ok(our_domain) ) {
1762                 DEBUG(3,("set_dc_type_and_flags_trustinfo: No connection to our domain!\n"));           
1763                 return False;
1764         }
1765
1766         /* This won't work unless our domain is AD */
1767
1768         if ( !our_domain->active_directory ) {
1769                 return False;
1770         }
1771
1772         /* Use DsEnumerateDomainTrusts to get us the trust direction
1773            and type */
1774
1775         result = cm_connect_netlogon(our_domain, &cli);
1776
1777         if (!NT_STATUS_IS_OK(result)) {
1778                 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
1779                           "a connection to %s for PIPE_NETLOGON (%s)\n", 
1780                           domain->name, nt_errstr(result)));
1781                 return False;
1782         }
1783
1784         if ( (mem_ctx = talloc_init("set_dc_type_and_flags_trustinfo")) == NULL ) {
1785                 DEBUG(0,("set_dc_type_and_flags_trustinfo: talloc_init() failed!\n"));
1786                 return False;
1787         }       
1788
1789         result = rpccli_netr_DsrEnumerateDomainTrusts(cli, mem_ctx,
1790                                                       cli->desthost,
1791                                                       flags,
1792                                                       &trusts,
1793                                                       NULL);
1794         if (!NT_STATUS_IS_OK(result)) {
1795                 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
1796                         "failed to query trusted domain list: %s\n",
1797                         nt_errstr(result)));
1798                 talloc_destroy(mem_ctx);
1799                 return false;
1800         }
1801
1802         /* Now find the domain name and get the flags */
1803
1804         for ( i=0; i<trusts.count; i++ ) {
1805                 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
1806                         domain->domain_flags          = trusts.array[i].trust_flags;
1807                         domain->domain_type           = trusts.array[i].trust_type;
1808                         domain->domain_trust_attribs  = trusts.array[i].trust_attributes;
1809
1810                         if ( domain->domain_type == NETR_TRUST_TYPE_UPLEVEL )
1811                                 domain->active_directory = True;
1812
1813                         /* This flag is only set if the domain is *our* 
1814                            primary domain and the primary domain is in
1815                            native mode */
1816
1817                         domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
1818
1819                         DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
1820                                   "native mode.\n", domain->name, 
1821                                   domain->native_mode ? "" : "NOT "));
1822
1823                         DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
1824                                  "running active directory.\n", domain->name, 
1825                                  domain->active_directory ? "" : "NOT "));
1826
1827
1828                         domain->initialized = True;
1829
1830                         break;
1831                 }               
1832         }
1833
1834         talloc_destroy( mem_ctx );
1835
1836         return domain->initialized;     
1837 }
1838
1839 /******************************************************************************
1840  We can 'sense' certain things about the DC by it's replies to certain
1841  questions.
1842
1843  This tells us if this particular remote server is Active Directory, and if it
1844  is native mode.
1845 ******************************************************************************/
1846
1847 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
1848 {
1849         NTSTATUS                result;
1850         WERROR werr;
1851         TALLOC_CTX              *mem_ctx = NULL;
1852         struct rpc_pipe_client  *cli = NULL;
1853         struct policy_handle pol;
1854         union dssetup_DsRoleInfo info;
1855         union lsa_PolicyInformation *lsa_info = NULL;
1856
1857         if (!connection_ok(domain)) {
1858                 return;
1859         }
1860
1861         mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
1862                               domain->name);
1863         if (!mem_ctx) {
1864                 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
1865                 return;
1866         }
1867
1868         DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
1869
1870         result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1871                                           &ndr_table_dssetup.syntax_id,
1872                                           &cli);
1873
1874         if (!NT_STATUS_IS_OK(result)) {
1875                 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1876                           "PI_DSSETUP on domain %s: (%s)\n",
1877                           domain->name, nt_errstr(result)));
1878
1879                 /* if this is just a non-AD domain we need to continue
1880                  * identifying so that we can in the end return with
1881                  * domain->initialized = True - gd */
1882
1883                 goto no_dssetup;
1884         }
1885
1886         result = rpccli_dssetup_DsRoleGetPrimaryDomainInformation(cli, mem_ctx,
1887                                                                   DS_ROLE_BASIC_INFORMATION,
1888                                                                   &info,
1889                                                                   &werr);
1890         TALLOC_FREE(cli);
1891
1892         if (!NT_STATUS_IS_OK(result)) {
1893                 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
1894                           "on domain %s failed: (%s)\n",
1895                           domain->name, nt_errstr(result)));
1896
1897                 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
1898                  * every opcode on the DSSETUP pipe, continue with
1899                  * no_dssetup mode here as well to get domain->initialized
1900                  * set - gd */
1901
1902                 if (NT_STATUS_V(result) == DCERPC_FAULT_OP_RNG_ERROR) {
1903                         goto no_dssetup;
1904                 }
1905
1906                 TALLOC_FREE(mem_ctx);
1907                 return;
1908         }
1909
1910         if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
1911             !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
1912                 domain->native_mode = True;
1913         } else {
1914                 domain->native_mode = False;
1915         }
1916
1917 no_dssetup:
1918         result = cli_rpc_pipe_open_noauth(domain->conn.cli,
1919                                           &ndr_table_lsarpc.syntax_id, &cli);
1920
1921         if (!NT_STATUS_IS_OK(result)) {
1922                 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
1923                           "PI_LSARPC on domain %s: (%s)\n",
1924                           domain->name, nt_errstr(result)));
1925                 TALLOC_FREE(cli);
1926                 TALLOC_FREE(mem_ctx);
1927                 return;
1928         }
1929
1930         result = rpccli_lsa_open_policy2(cli, mem_ctx, True, 
1931                                          SEC_FLAG_MAXIMUM_ALLOWED, &pol);
1932
1933         if (NT_STATUS_IS_OK(result)) {
1934                 /* This particular query is exactly what Win2k clients use 
1935                    to determine that the DC is active directory */
1936                 result = rpccli_lsa_QueryInfoPolicy2(cli, mem_ctx,
1937                                                      &pol,
1938                                                      LSA_POLICY_INFO_DNS,
1939                                                      &lsa_info);
1940         }
1941
1942         if (NT_STATUS_IS_OK(result)) {
1943                 domain->active_directory = True;
1944
1945                 if (lsa_info->dns.name.string) {
1946                         fstrcpy(domain->name, lsa_info->dns.name.string);
1947                 }
1948
1949                 if (lsa_info->dns.dns_domain.string) {
1950                         fstrcpy(domain->alt_name,
1951                                 lsa_info->dns.dns_domain.string);
1952                 }
1953
1954                 /* See if we can set some domain trust flags about
1955                    ourself */
1956
1957                 if (lsa_info->dns.dns_forest.string) {
1958                         fstrcpy(domain->forest_name,
1959                                 lsa_info->dns.dns_forest.string);
1960
1961                         if (strequal(domain->forest_name, domain->alt_name)) {
1962                                 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
1963                         }
1964                 }
1965
1966                 if (lsa_info->dns.sid) {
1967                         sid_copy(&domain->sid, lsa_info->dns.sid);
1968                 }
1969         } else {
1970                 domain->active_directory = False;
1971
1972                 result = rpccli_lsa_open_policy(cli, mem_ctx, True, 
1973                                                 SEC_FLAG_MAXIMUM_ALLOWED,
1974                                                 &pol);
1975
1976                 if (!NT_STATUS_IS_OK(result)) {
1977                         goto done;
1978                 }
1979
1980                 result = rpccli_lsa_QueryInfoPolicy(cli, mem_ctx,
1981                                                     &pol,
1982                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
1983                                                     &lsa_info);
1984
1985                 if (NT_STATUS_IS_OK(result)) {
1986
1987                         if (lsa_info->account_domain.name.string) {
1988                                 fstrcpy(domain->name,
1989                                         lsa_info->account_domain.name.string);
1990                         }
1991
1992                         if (lsa_info->account_domain.sid) {
1993                                 sid_copy(&domain->sid, lsa_info->account_domain.sid);
1994                         }
1995                 }
1996         }
1997 done:
1998
1999         DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
2000                   domain->name, domain->native_mode ? "" : "NOT "));
2001
2002         DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
2003                   domain->name, domain->active_directory ? "" : "NOT "));
2004
2005         domain->can_do_ncacn_ip_tcp = domain->active_directory;
2006
2007         TALLOC_FREE(cli);
2008
2009         TALLOC_FREE(mem_ctx);
2010
2011         domain->initialized = True;
2012 }
2013
2014 /**********************************************************************
2015  Set the domain_flags (trust attributes, domain operating modes, etc... 
2016 ***********************************************************************/
2017
2018 static void set_dc_type_and_flags( struct winbindd_domain *domain )
2019 {
2020         /* we always have to contact our primary domain */
2021
2022         if ( domain->primary ) {
2023                 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
2024                           "primary domain\n"));
2025                 set_dc_type_and_flags_connect( domain );
2026                 return;         
2027         }
2028
2029         /* Use our DC to get the information if possible */
2030
2031         if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
2032                 /* Otherwise, fallback to contacting the 
2033                    domain directly */
2034                 set_dc_type_and_flags_connect( domain );
2035         }
2036
2037         return;
2038 }
2039
2040
2041
2042 /**********************************************************************
2043 ***********************************************************************/
2044
2045 static bool cm_get_schannel_creds(struct winbindd_domain *domain,
2046                                    struct netlogon_creds_CredentialState **ppdc)
2047 {
2048         NTSTATUS result;
2049         struct rpc_pipe_client *netlogon_pipe;
2050
2051         if (lp_client_schannel() == False) {
2052                 return False;
2053         }
2054
2055         result = cm_connect_netlogon(domain, &netlogon_pipe);
2056         if (!NT_STATUS_IS_OK(result)) {
2057                 return False;
2058         }
2059
2060         /* Return a pointer to the struct netlogon_creds_CredentialState from the
2061            netlogon pipe. */
2062
2063         if (!domain->conn.netlogon_pipe->dc) {
2064                 return false;
2065         }
2066
2067         *ppdc = domain->conn.netlogon_pipe->dc;
2068         return True;
2069 }
2070
2071 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2072                         struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2073 {
2074         struct winbindd_cm_conn *conn;
2075         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2076         struct netlogon_creds_CredentialState *p_creds;
2077         char *machine_password = NULL;
2078         char *machine_account = NULL;
2079         char *domain_name = NULL;
2080
2081         if (strequal(domain->name, get_global_sam_name())) {
2082                 result = open_internal_samr_conn(mem_ctx, domain, cli, sam_handle);
2083                 if (!NT_STATUS_IS_OK(result)) {
2084                         return result;
2085                 }
2086                 return NT_STATUS_OK;
2087         }
2088
2089         result = init_dc_connection_rpc(domain);
2090         if (!NT_STATUS_IS_OK(result)) {
2091                 return result;
2092         }
2093
2094         conn = &domain->conn;
2095
2096         if (rpccli_is_connected(conn->samr_pipe)) {
2097                 goto done;
2098         }
2099
2100         TALLOC_FREE(conn->samr_pipe);
2101
2102         /*
2103          * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2104          * sign and sealed pipe using the machine account password by
2105          * preference. If we can't - try schannel, if that fails, try
2106          * anonymous.
2107          */
2108
2109         if ((conn->cli->user_name[0] == '\0') ||
2110             (conn->cli->domain[0] == '\0') || 
2111             (conn->cli->password == NULL || conn->cli->password[0] == '\0'))
2112         {
2113                 result = get_trust_creds(domain, &machine_password,
2114                                          &machine_account, NULL);
2115                 if (!NT_STATUS_IS_OK(result)) {
2116                         DEBUG(10, ("cm_connect_sam: No no user available for "
2117                                    "domain %s, trying schannel\n", conn->cli->domain));
2118                         goto schannel;
2119                 }
2120                 domain_name = domain->name;
2121         } else {
2122                 machine_password = SMB_STRDUP(conn->cli->password);
2123                 machine_account = SMB_STRDUP(conn->cli->user_name);
2124                 domain_name = conn->cli->domain;
2125         }
2126
2127         if (!machine_password || !machine_account) {
2128                 result = NT_STATUS_NO_MEMORY;
2129                 goto done;
2130         }
2131
2132         /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2133            authenticated SAMR pipe with sign & seal. */
2134         result = cli_rpc_pipe_open_spnego_ntlmssp(conn->cli,
2135                                                   &ndr_table_samr.syntax_id,
2136                                                   NCACN_NP,
2137                                                   DCERPC_AUTH_LEVEL_PRIVACY,
2138                                                   domain_name,
2139                                                   machine_account,
2140                                                   machine_password,
2141                                                   &conn->samr_pipe);
2142
2143         if (!NT_STATUS_IS_OK(result)) {
2144                 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2145                           "pipe for domain %s using NTLMSSP "
2146                           "authenticated pipe: user %s\\%s. Error was "
2147                           "%s\n", domain->name, domain_name,
2148                           machine_account, nt_errstr(result)));
2149                 goto schannel;
2150         }
2151
2152         DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2153                   "domain %s using NTLMSSP authenticated "
2154                   "pipe: user %s\\%s\n", domain->name,
2155                   domain_name, machine_account));
2156
2157         result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2158                                       conn->samr_pipe->desthost,
2159                                       SEC_FLAG_MAXIMUM_ALLOWED,
2160                                       &conn->sam_connect_handle);
2161         if (NT_STATUS_IS_OK(result)) {
2162                 goto open_domain;
2163         }
2164         DEBUG(10,("cm_connect_sam: ntlmssp-sealed rpccli_samr_Connect2 "
2165                   "failed for domain %s, error was %s. Trying schannel\n",
2166                   domain->name, nt_errstr(result) ));
2167         TALLOC_FREE(conn->samr_pipe);
2168
2169  schannel:
2170
2171         /* Fall back to schannel if it's a W2K pre-SP1 box. */
2172
2173         if (!cm_get_schannel_creds(domain, &p_creds)) {
2174                 /* If this call fails - conn->cli can now be NULL ! */
2175                 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2176                            "for domain %s, trying anon\n", domain->name));
2177                 goto anonymous;
2178         }
2179         result = cli_rpc_pipe_open_schannel_with_key
2180                 (conn->cli, &ndr_table_samr.syntax_id, NCACN_NP,
2181                  DCERPC_AUTH_LEVEL_PRIVACY,
2182                  domain->name, &p_creds, &conn->samr_pipe);
2183
2184         if (!NT_STATUS_IS_OK(result)) {
2185                 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2186                           "domain %s using schannel. Error was %s\n",
2187                           domain->name, nt_errstr(result) ));
2188                 goto anonymous;
2189         }
2190         DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2191                   "schannel.\n", domain->name ));
2192
2193         result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2194                                       conn->samr_pipe->desthost,
2195                                       SEC_FLAG_MAXIMUM_ALLOWED,
2196                                       &conn->sam_connect_handle);
2197         if (NT_STATUS_IS_OK(result)) {
2198                 goto open_domain;
2199         }
2200         DEBUG(10,("cm_connect_sam: schannel-sealed rpccli_samr_Connect2 failed "
2201                   "for domain %s, error was %s. Trying anonymous\n",
2202                   domain->name, nt_errstr(result) ));
2203         TALLOC_FREE(conn->samr_pipe);
2204
2205  anonymous:
2206
2207         /* Finally fall back to anonymous. */
2208         result = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr.syntax_id,
2209                                           &conn->samr_pipe);
2210
2211         if (!NT_STATUS_IS_OK(result)) {
2212                 goto done;
2213         }
2214
2215         result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
2216                                       conn->samr_pipe->desthost,
2217                                       SEC_FLAG_MAXIMUM_ALLOWED,
2218                                       &conn->sam_connect_handle);
2219         if (!NT_STATUS_IS_OK(result)) {
2220                 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2221                           "for domain %s Error was %s\n",
2222                           domain->name, nt_errstr(result) ));
2223                 goto done;
2224         }
2225
2226  open_domain:
2227         result = rpccli_samr_OpenDomain(conn->samr_pipe,
2228                                         mem_ctx,
2229                                         &conn->sam_connect_handle,
2230                                         SEC_FLAG_MAXIMUM_ALLOWED,
2231                                         &domain->sid,
2232                                         &conn->sam_domain_handle);
2233
2234  done:
2235
2236         if (NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
2237                 /*
2238                  * if we got access denied, we might just have no access rights
2239                  * to talk to the remote samr server server (e.g. when we are a
2240                  * PDC and we are connecting a w2k8 pdc via an interdomain
2241                  * trust). In that case do not invalidate the whole connection
2242                  * stack
2243                  */
2244                 TALLOC_FREE(conn->samr_pipe);
2245                 ZERO_STRUCT(conn->sam_domain_handle);
2246                 return result;
2247         } else if (!NT_STATUS_IS_OK(result)) {
2248                 invalidate_cm_connection(conn);
2249                 return result;
2250         }
2251
2252         *cli = conn->samr_pipe;
2253         *sam_handle = conn->sam_domain_handle;
2254         SAFE_FREE(machine_password);
2255         SAFE_FREE(machine_account);
2256         return result;
2257 }
2258
2259 /**********************************************************************
2260  open an schanneld ncacn_ip_tcp connection to LSA
2261 ***********************************************************************/
2262
2263 NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2264                             TALLOC_CTX *mem_ctx,
2265                             struct rpc_pipe_client **cli)
2266 {
2267         struct winbindd_cm_conn *conn;
2268         NTSTATUS status;
2269
2270         DEBUG(10,("cm_connect_lsa_tcp\n"));
2271
2272         status = init_dc_connection_rpc(domain);
2273         if (!NT_STATUS_IS_OK(status)) {
2274                 return status;
2275         }
2276
2277         conn = &domain->conn;
2278
2279         if (conn->lsa_pipe_tcp &&
2280             conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2281             conn->lsa_pipe_tcp->auth->auth_level == DCERPC_AUTH_LEVEL_PRIVACY &&
2282             rpccli_is_connected(conn->lsa_pipe_tcp)) {
2283                 goto done;
2284         }
2285
2286         TALLOC_FREE(conn->lsa_pipe_tcp);
2287
2288         status = cli_rpc_pipe_open_schannel(conn->cli,
2289                                             &ndr_table_lsarpc.syntax_id,
2290                                             NCACN_IP_TCP,
2291                                             DCERPC_AUTH_LEVEL_PRIVACY,
2292                                             domain->name,
2293                                             &conn->lsa_pipe_tcp);
2294         if (!NT_STATUS_IS_OK(status)) {
2295                 DEBUG(10,("cli_rpc_pipe_open_schannel failed: %s\n",
2296                         nt_errstr(status)));
2297                 goto done;
2298         }
2299
2300  done:
2301         if (!NT_STATUS_IS_OK(status)) {
2302                 TALLOC_FREE(conn->lsa_pipe_tcp);
2303                 return status;
2304         }
2305
2306         *cli = conn->lsa_pipe_tcp;
2307
2308         return status;
2309 }
2310
2311 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2312                         struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2313 {
2314         struct winbindd_cm_conn *conn;
2315         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2316         struct netlogon_creds_CredentialState *p_creds;
2317
2318         result = init_dc_connection_rpc(domain);
2319         if (!NT_STATUS_IS_OK(result))
2320                 return result;
2321
2322         conn = &domain->conn;
2323
2324         if (rpccli_is_connected(conn->lsa_pipe)) {
2325                 goto done;
2326         }
2327
2328         TALLOC_FREE(conn->lsa_pipe);
2329
2330         if ((conn->cli->user_name[0] == '\0') ||
2331             (conn->cli->domain[0] == '\0') || 
2332             (conn->cli->password == NULL || conn->cli->password[0] == '\0')) {
2333                 DEBUG(10, ("cm_connect_lsa: No no user available for "
2334                            "domain %s, trying schannel\n", conn->cli->domain));
2335                 goto schannel;
2336         }
2337
2338         /* We have an authenticated connection. Use a NTLMSSP SPNEGO
2339          * authenticated LSA pipe with sign & seal. */
2340         result = cli_rpc_pipe_open_spnego_ntlmssp
2341                 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2342                  DCERPC_AUTH_LEVEL_PRIVACY,
2343                  conn->cli->domain, conn->cli->user_name, conn->cli->password,
2344                  &conn->lsa_pipe);
2345
2346         if (!NT_STATUS_IS_OK(result)) {
2347                 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2348                           "domain %s using NTLMSSP authenticated pipe: user "
2349                           "%s\\%s. Error was %s. Trying schannel.\n",
2350                           domain->name, conn->cli->domain,
2351                           conn->cli->user_name, nt_errstr(result)));
2352                 goto schannel;
2353         }
2354
2355         DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2356                   "NTLMSSP authenticated pipe: user %s\\%s\n",
2357                   domain->name, conn->cli->domain, conn->cli->user_name ));
2358
2359         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2360                                         SEC_FLAG_MAXIMUM_ALLOWED,
2361                                         &conn->lsa_policy);
2362         if (NT_STATUS_IS_OK(result)) {
2363                 goto done;
2364         }
2365
2366         DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2367                   "schannel\n"));
2368
2369         TALLOC_FREE(conn->lsa_pipe);
2370
2371  schannel:
2372
2373         /* Fall back to schannel if it's a W2K pre-SP1 box. */
2374
2375         if (!cm_get_schannel_creds(domain, &p_creds)) {
2376                 /* If this call fails - conn->cli can now be NULL ! */
2377                 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
2378                            "for domain %s, trying anon\n", domain->name));
2379                 goto anonymous;
2380         }
2381         result = cli_rpc_pipe_open_schannel_with_key
2382                 (conn->cli, &ndr_table_lsarpc.syntax_id, NCACN_NP,
2383                  DCERPC_AUTH_LEVEL_PRIVACY,
2384                  domain->name, &p_creds, &conn->lsa_pipe);
2385
2386         if (!NT_STATUS_IS_OK(result)) {
2387                 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2388                           "domain %s using schannel. Error was %s\n",
2389                           domain->name, nt_errstr(result) ));
2390                 goto anonymous;
2391         }
2392         DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2393                   "schannel.\n", domain->name ));
2394
2395         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2396                                         SEC_FLAG_MAXIMUM_ALLOWED,
2397                                         &conn->lsa_policy);
2398         if (NT_STATUS_IS_OK(result)) {
2399                 goto done;
2400         }
2401
2402         DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2403                   "anonymous\n"));
2404
2405         TALLOC_FREE(conn->lsa_pipe);
2406
2407  anonymous:
2408
2409         result = cli_rpc_pipe_open_noauth(conn->cli,
2410                                           &ndr_table_lsarpc.syntax_id,
2411                                           &conn->lsa_pipe);
2412         if (!NT_STATUS_IS_OK(result)) {
2413                 result = NT_STATUS_PIPE_NOT_AVAILABLE;
2414                 goto done;
2415         }
2416
2417         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2418                                         SEC_FLAG_MAXIMUM_ALLOWED,
2419                                         &conn->lsa_policy);
2420  done:
2421         if (!NT_STATUS_IS_OK(result)) {
2422                 invalidate_cm_connection(conn);
2423                 return result;
2424         }
2425
2426         *cli = conn->lsa_pipe;
2427         *lsa_policy = conn->lsa_policy;
2428         return result;
2429 }
2430
2431 /****************************************************************************
2432  Open the netlogon pipe to this DC. Use schannel if specified in client conf.
2433  session key stored in conn->netlogon_pipe->dc->sess_key.
2434 ****************************************************************************/
2435
2436 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
2437                              struct rpc_pipe_client **cli)
2438 {
2439         struct winbindd_cm_conn *conn;
2440         NTSTATUS result;
2441
2442         uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
2443         uint8  mach_pwd[16];
2444         enum netr_SchannelType sec_chan_type;
2445         const char *account_name;
2446         struct rpc_pipe_client *netlogon_pipe = NULL;
2447
2448         *cli = NULL;
2449
2450         result = init_dc_connection_rpc(domain);
2451         if (!NT_STATUS_IS_OK(result)) {
2452                 return result;
2453         }
2454
2455         conn = &domain->conn;
2456
2457         if (rpccli_is_connected(conn->netlogon_pipe)) {
2458                 *cli = conn->netlogon_pipe;
2459                 return NT_STATUS_OK;
2460         }
2461
2462         TALLOC_FREE(conn->netlogon_pipe);
2463
2464         result = cli_rpc_pipe_open_noauth(conn->cli,
2465                                           &ndr_table_netlogon.syntax_id,
2466                                           &netlogon_pipe);
2467         if (!NT_STATUS_IS_OK(result)) {
2468                 return result;
2469         }
2470
2471         if ((!IS_DC) && (!domain->primary)) {
2472                 /* Clear the schannel request bit and drop down */
2473                 neg_flags &= ~NETLOGON_NEG_SCHANNEL;            
2474                 goto no_schannel;
2475         }
2476
2477         if (lp_client_schannel() != False) {
2478                 neg_flags |= NETLOGON_NEG_SCHANNEL;
2479         }
2480
2481         if (!get_trust_pw_hash(domain->name, mach_pwd, &account_name,
2482                                &sec_chan_type))
2483         {
2484                 TALLOC_FREE(netlogon_pipe);
2485                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2486         }
2487
2488         result = rpccli_netlogon_setup_creds(
2489                  netlogon_pipe,
2490                  domain->dcname, /* server name. */
2491                  domain->name,   /* domain name */
2492                  global_myname(), /* client name */
2493                  account_name,   /* machine account */
2494                  mach_pwd,       /* machine password */
2495                  sec_chan_type,  /* from get_trust_pw */
2496                  &neg_flags);
2497
2498         if (!NT_STATUS_IS_OK(result)) {
2499                 TALLOC_FREE(netlogon_pipe);
2500                 return result;
2501         }
2502
2503         if ((lp_client_schannel() == True) &&
2504                         ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2505                 DEBUG(3, ("Server did not offer schannel\n"));
2506                 TALLOC_FREE(netlogon_pipe);
2507                 return NT_STATUS_ACCESS_DENIED;
2508         }
2509
2510  no_schannel:
2511         if ((lp_client_schannel() == False) ||
2512                         ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
2513                 /*
2514                  * NetSamLogonEx only works for schannel
2515                  */
2516                 domain->can_do_samlogon_ex = False;
2517
2518                 /* We're done - just keep the existing connection to NETLOGON
2519                  * open */
2520                 conn->netlogon_pipe = netlogon_pipe;
2521                 *cli = conn->netlogon_pipe;
2522                 return NT_STATUS_OK;
2523         }
2524
2525         /* Using the credentials from the first pipe, open a signed and sealed
2526            second netlogon pipe. The session key is stored in the schannel
2527            part of the new pipe auth struct.
2528         */
2529
2530         result = cli_rpc_pipe_open_schannel_with_key(
2531                 conn->cli, &ndr_table_netlogon.syntax_id, NCACN_NP,
2532                 DCERPC_AUTH_LEVEL_PRIVACY, domain->name, &netlogon_pipe->dc,
2533                 &conn->netlogon_pipe);
2534
2535         /* We can now close the initial netlogon pipe. */
2536         TALLOC_FREE(netlogon_pipe);
2537
2538         if (!NT_STATUS_IS_OK(result)) {
2539                 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
2540                           "was %s\n", nt_errstr(result)));
2541
2542                 invalidate_cm_connection(conn);
2543                 return result;
2544         }
2545
2546         /*
2547          * Always try netr_LogonSamLogonEx. We will fall back for NT4
2548          * which gives DCERPC_FAULT_OP_RNG_ERROR (function not
2549          * supported). We used to only try SamLogonEx for AD, but
2550          * Samba DCs can also do it. And because we don't distinguish
2551          * between Samba and NT4, always try it once.
2552          */
2553         domain->can_do_samlogon_ex = true;
2554
2555         *cli = conn->netlogon_pipe;
2556         return NT_STATUS_OK;
2557 }