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