s3:winbindd: improve logic to use CLDAP for a given domain.
[obnox/samba/samba-obnox.git] / source3 / winbindd / winbindd_cm.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon connection manager
5
6    Copyright (C) Tim Potter                2001
7    Copyright (C) Andrew Bartlett           2002
8    Copyright (C) Gerald (Jerry) Carter     2003-2005.
9    Copyright (C) Volker Lendecke           2004-2005
10    Copyright (C) Jeremy Allison            2006
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 3 of the License, or
15    (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 */
25
26 /*
27    We need to manage connections to domain controllers without having to
28    mess up the main winbindd code with other issues.  The aim of the
29    connection manager is to:
30
31        - make connections to domain controllers and cache them
32        - re-establish connections when networks or servers go down
33        - centralise the policy on connection timeouts, domain controller
34          selection etc
35        - manage re-entrancy for when winbindd becomes able to handle
36          multiple outstanding rpc requests
37
38    Why not have connection management as part of the rpc layer like tng?
39    Good question.  This code may morph into libsmb/rpc_cache.c or something
40    like that but at the moment it's simply staying as part of winbind.  I
41    think the TNG architecture of forcing every user of the rpc layer to use
42    the connection caching system is a bad idea.  It should be an optional
43    method of using the routines.
44
45    The TNG design is quite good but I disagree with some aspects of the
46    implementation. -tpot
47
48  */
49
50 /*
51    TODO:
52
53      - I'm pretty annoyed by all the make_nmb_name() stuff.  It should be
54        moved down into another function.
55
56      - Take care when destroying cli_structs as they can be shared between
57        various sam handles.
58
59  */
60
61 #include "includes.h"
62 #include "winbindd.h"
63 #include "../libcli/auth/libcli_auth.h"
64 #include "../librpc/gen_ndr/ndr_netlogon_c.h"
65 #include "rpc_client/cli_pipe.h"
66 #include "rpc_client/cli_netlogon.h"
67 #include "../librpc/gen_ndr/ndr_samr_c.h"
68 #include "../librpc/gen_ndr/ndr_lsa_c.h"
69 #include "rpc_client/cli_lsarpc.h"
70 #include "../librpc/gen_ndr/ndr_dssetup_c.h"
71 #include "libads/sitename_cache.h"
72 #include "libsmb/libsmb.h"
73 #include "libsmb/clidgram.h"
74 #include "ads.h"
75 #include "secrets.h"
76 #include "../libcli/security/security.h"
77 #include "passdb.h"
78 #include "messages.h"
79 #include "auth/gensec/gensec.h"
80 #include "../libcli/smb/smbXcli_base.h"
81 #include "libcli/auth/netlogon_creds_cli.h"
82 #include "auth.h"
83 #include "rpc_server/rpc_ncacn_np.h"
84 #include "auth/credentials/credentials.h"
85 #include "lib/param/param.h"
86
87 #undef DBGC_CLASS
88 #define DBGC_CLASS DBGC_WINBIND
89
90 struct dc_name_ip {
91         fstring name;
92         struct sockaddr_storage ss;
93 };
94
95 extern struct winbindd_methods reconnect_methods;
96 extern bool override_logfile;
97
98 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc);
99 static void set_dc_type_and_flags( struct winbindd_domain *domain );
100 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain );
101 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
102                     struct dc_name_ip **dcs, int *num_dcs);
103
104 /****************************************************************
105  Child failed to find DC's. Reschedule check.
106 ****************************************************************/
107
108 static void msg_failed_to_go_online(struct messaging_context *msg,
109                                     void *private_data,
110                                     uint32_t msg_type,
111                                     struct server_id server_id,
112                                     DATA_BLOB *data)
113 {
114         struct winbindd_domain *domain;
115         const char *domainname = (const char *)data->data;
116
117         if (data->data == NULL || data->length == 0) {
118                 return;
119         }
120
121         DEBUG(5,("msg_fail_to_go_online: received for domain %s.\n", domainname));
122
123         for (domain = domain_list(); domain; domain = domain->next) {
124                 if (domain->internal) {
125                         continue;
126                 }
127
128                 if (strequal(domain->name, domainname)) {
129                         if (domain->online) {
130                                 /* We're already online, ignore. */
131                                 DEBUG(5,("msg_fail_to_go_online: domain %s "
132                                         "already online.\n", domainname));
133                                 continue;
134                         }
135
136                         /* Reschedule the online check. */
137                         set_domain_offline(domain);
138                         break;
139                 }
140         }
141 }
142
143 /****************************************************************
144  Actually cause a reconnect from a message.
145 ****************************************************************/
146
147 static void msg_try_to_go_online(struct messaging_context *msg,
148                                  void *private_data,
149                                  uint32_t msg_type,
150                                  struct server_id server_id,
151                                  DATA_BLOB *data)
152 {
153         struct winbindd_domain *domain;
154         const char *domainname = (const char *)data->data;
155
156         if (data->data == NULL || data->length == 0) {
157                 return;
158         }
159
160         DEBUG(5,("msg_try_to_go_online: received for domain %s.\n", domainname));
161
162         for (domain = domain_list(); domain; domain = domain->next) {
163                 if (domain->internal) {
164                         continue;
165                 }
166
167                 if (strequal(domain->name, domainname)) {
168
169                         if (domain->online) {
170                                 /* We're already online, ignore. */
171                                 DEBUG(5,("msg_try_to_go_online: domain %s "
172                                         "already online.\n", domainname));
173                                 continue;
174                         }
175
176                         /* This call takes care of setting the online
177                            flag to true if we connected, or re-adding
178                            the offline handler if false. Bypasses online
179                            check so always does network calls. */
180
181                         init_dc_connection_network(domain, true);
182                         break;
183                 }
184         }
185 }
186
187 /****************************************************************
188  Fork a child to try and contact a DC. Do this as contacting a
189  DC requires blocking lookups and we don't want to block our
190  parent.
191 ****************************************************************/
192
193 static bool fork_child_dc_connect(struct winbindd_domain *domain)
194 {
195         struct dc_name_ip *dcs = NULL;
196         int num_dcs = 0;
197         TALLOC_CTX *mem_ctx = NULL;
198         pid_t parent_pid = getpid();
199         char *lfile = NULL;
200         NTSTATUS status;
201
202         if (domain->dc_probe_pid != (pid_t)-1) {
203                 /*
204                  * We might already have a DC probe
205                  * child working, check.
206                  */
207                 if (process_exists_by_pid(domain->dc_probe_pid)) {
208                         DEBUG(10,("fork_child_dc_connect: pid %u already "
209                                 "checking for DC's.\n",
210                                 (unsigned int)domain->dc_probe_pid));
211                         return true;
212                 }
213                 domain->dc_probe_pid = (pid_t)-1;
214         }
215
216         domain->dc_probe_pid = fork();
217
218         if (domain->dc_probe_pid == (pid_t)-1) {
219                 DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
220                 return False;
221         }
222
223         if (domain->dc_probe_pid != (pid_t)0) {
224                 /* Parent */
225                 messaging_register(winbind_messaging_context(), NULL,
226                                    MSG_WINBIND_TRY_TO_GO_ONLINE,
227                                    msg_try_to_go_online);
228                 messaging_register(winbind_messaging_context(), NULL,
229                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
230                                    msg_failed_to_go_online);
231                 return True;
232         }
233
234         /* Child. */
235
236         /* Leave messages blocked - we will never process one. */
237
238         if (!override_logfile) {
239                 if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) == -1) {
240                         DEBUG(0, ("fork_child_dc_connect: out of memory.\n"));
241                         _exit(1);
242                 }
243         }
244
245         status = winbindd_reinit_after_fork(NULL, lfile);
246         if (!NT_STATUS_IS_OK(status)) {
247                 DEBUG(1, ("winbindd_reinit_after_fork failed: %s\n",
248                           nt_errstr(status)));
249                 messaging_send_buf(winbind_messaging_context(),
250                                    pid_to_procid(parent_pid),
251                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
252                                    (const uint8_t *)domain->name,
253                                    strlen(domain->name)+1);
254                 _exit(1);
255         }
256         SAFE_FREE(lfile);
257
258         mem_ctx = talloc_init("fork_child_dc_connect");
259         if (!mem_ctx) {
260                 DEBUG(0,("talloc_init failed.\n"));
261                 messaging_send_buf(winbind_messaging_context(),
262                                    pid_to_procid(parent_pid),
263                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
264                                    (const uint8_t *)domain->name,
265                                    strlen(domain->name)+1);
266                 _exit(1);
267         }
268
269         if ((!get_dcs(mem_ctx, domain, &dcs, &num_dcs)) || (num_dcs == 0)) {
270                 /* Still offline ? Can't find DC's. */
271                 messaging_send_buf(winbind_messaging_context(),
272                                    pid_to_procid(parent_pid),
273                                    MSG_WINBIND_FAILED_TO_GO_ONLINE,
274                                    (const uint8_t *)domain->name,
275                                    strlen(domain->name)+1);
276                 _exit(0);
277         }
278
279         /* We got a DC. Send a message to our parent to get it to
280            try and do the same. */
281
282         messaging_send_buf(winbind_messaging_context(),
283                            pid_to_procid(parent_pid),
284                            MSG_WINBIND_TRY_TO_GO_ONLINE,
285                            (const uint8_t *)domain->name,
286                            strlen(domain->name)+1);
287         _exit(0);
288 }
289
290 /****************************************************************
291  Handler triggered if we're offline to try and detect a DC.
292 ****************************************************************/
293
294 static void check_domain_online_handler(struct tevent_context *ctx,
295                                         struct tevent_timer *te,
296                                         struct timeval now,
297                                         void *private_data)
298 {
299         struct winbindd_domain *domain =
300                 (struct winbindd_domain *)private_data;
301
302         DEBUG(10,("check_domain_online_handler: called for domain "
303                   "%s (online = %s)\n", domain->name, 
304                   domain->online ? "True" : "False" ));
305
306         TALLOC_FREE(domain->check_online_event);
307
308         /* Are we still in "startup" mode ? */
309
310         if (domain->startup && (time_mono(NULL) > domain->startup_time + 30)) {
311                 /* No longer in "startup" mode. */
312                 DEBUG(10,("check_domain_online_handler: domain %s no longer in 'startup' mode.\n",
313                         domain->name ));
314                 domain->startup = False;
315         }
316
317         /* We've been told to stay offline, so stay
318            that way. */
319
320         if (get_global_winbindd_state_offline()) {
321                 DEBUG(10,("check_domain_online_handler: domain %s remaining globally offline\n",
322                         domain->name ));
323                 return;
324         }
325
326         /* Fork a child to test if it can contact a DC. 
327            If it can then send ourselves a message to
328            cause a reconnect. */
329
330         fork_child_dc_connect(domain);
331 }
332
333 /****************************************************************
334  If we're still offline setup the timeout check.
335 ****************************************************************/
336
337 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
338 {
339         int wbr = lp_winbind_reconnect_delay();
340
341         if (domain->startup) {
342                 domain->check_online_timeout = 10;
343         } else if (domain->check_online_timeout < wbr) {
344                 domain->check_online_timeout = wbr;
345         }
346 }
347
348 void winbind_msg_domain_offline(struct messaging_context *msg_ctx,
349                                 void *private_data,
350                                 uint32_t msg_type,
351                                 struct server_id server_id,
352                                 DATA_BLOB *data)
353 {
354         const char *domain_name = (const char *)data->data;
355         struct winbindd_domain *domain;
356
357         domain = find_domain_from_name_noinit(domain_name);
358         if (domain == NULL) {
359                 return;
360         }
361
362         domain->online = false;
363
364         DEBUG(10, ("Domain %s is marked as offline now.\n",
365                    domain_name));
366 }
367
368 void winbind_msg_domain_online(struct messaging_context *msg_ctx,
369                                 void *private_data,
370                                 uint32_t msg_type,
371                                 struct server_id server_id,
372                                 DATA_BLOB *data)
373 {
374         const char *domain_name = (const char *)data->data;
375         struct winbindd_domain *domain;
376
377         domain = find_domain_from_name_noinit(domain_name);
378         if (domain == NULL) {
379                 return;
380         }
381
382         domain->online = true;
383
384         DEBUG(10, ("Domain %s is marked as online now.\n",
385                    domain_name));
386 }
387
388 /****************************************************************
389  Set domain offline and also add handler to put us back online
390  if we detect a DC.
391 ****************************************************************/
392
393 void set_domain_offline(struct winbindd_domain *domain)
394 {
395         pid_t parent_pid = getppid();
396
397         DEBUG(10,("set_domain_offline: called for domain %s\n",
398                 domain->name ));
399
400         TALLOC_FREE(domain->check_online_event);
401
402         if (domain->internal) {
403                 DEBUG(3,("set_domain_offline: domain %s is internal - logic error.\n",
404                         domain->name ));
405                 return;
406         }
407
408         domain->online = False;
409
410         /* Offline domains are always initialized. They're
411            re-initialized when they go back online. */
412
413         domain->initialized = True;
414
415         /* We only add the timeout handler that checks and
416            allows us to go back online when we've not
417            been told to remain offline. */
418
419         if (get_global_winbindd_state_offline()) {
420                 DEBUG(10,("set_domain_offline: domain %s remaining globally offline\n",
421                         domain->name ));
422                 return;
423         }
424
425         /* If we're in startup mode, check again in 10 seconds, not in
426            lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
427
428         calc_new_online_timeout_check(domain);
429
430         domain->check_online_event = tevent_add_timer(winbind_event_context(),
431                                                 NULL,
432                                                 timeval_current_ofs(domain->check_online_timeout,0),
433                                                 check_domain_online_handler,
434                                                 domain);
435
436         /* The above *has* to succeed for winbindd to work. */
437         if (!domain->check_online_event) {
438                 smb_panic("set_domain_offline: failed to add online handler");
439         }
440
441         DEBUG(10,("set_domain_offline: added event handler for domain %s\n",
442                 domain->name ));
443
444         /* Send a message to the parent that the domain is offline. */
445         if (parent_pid > 1 && !domain->internal) {
446                 messaging_send_buf(winbind_messaging_context(),
447                                    pid_to_procid(parent_pid),
448                                    MSG_WINBIND_DOMAIN_OFFLINE,
449                                    (uint8 *)domain->name,
450                                    strlen(domain->name) + 1);
451         }
452
453         /* Send an offline message to the idmap child when our
454            primary domain goes offline */
455
456         if ( domain->primary ) {
457                 struct winbindd_child *idmap = idmap_child();
458
459                 if ( idmap->pid != 0 ) {
460                         messaging_send_buf(winbind_messaging_context(),
461                                            pid_to_procid(idmap->pid), 
462                                            MSG_WINBIND_OFFLINE, 
463                                            (const uint8_t *)domain->name,
464                                            strlen(domain->name)+1);
465                 }                       
466         }
467
468         return; 
469 }
470
471 /****************************************************************
472  Set domain online - if allowed.
473 ****************************************************************/
474
475 static void set_domain_online(struct winbindd_domain *domain)
476 {
477         pid_t parent_pid = getppid();
478
479         DEBUG(10,("set_domain_online: called for domain %s\n",
480                 domain->name ));
481
482         if (domain->internal) {
483                 DEBUG(3,("set_domain_online: domain %s is internal - logic error.\n",
484                         domain->name ));
485                 return;
486         }
487
488         if (get_global_winbindd_state_offline()) {
489                 DEBUG(10,("set_domain_online: domain %s remaining globally offline\n",
490                         domain->name ));
491                 return;
492         }
493
494         winbindd_set_locator_kdc_envs(domain);
495
496         /* If we are waiting to get a krb5 ticket, trigger immediately. */
497         ccache_regain_all_now();
498
499         /* Ok, we're out of any startup mode now... */
500         domain->startup = False;
501
502         if (domain->online == False) {
503                 /* We were offline - now we're online. We default to
504                    using the MS-RPC backend if we started offline,
505                    and if we're going online for the first time we
506                    should really re-initialize the backends and the
507                    checks to see if we're talking to an AD or NT domain.
508                 */
509
510                 domain->initialized = False;
511
512                 /* 'reconnect_methods' is the MS-RPC backend. */
513                 if (domain->backend == &reconnect_methods) {
514                         domain->backend = NULL;
515                 }
516         }
517
518         /* Ensure we have no online timeout checks. */
519         domain->check_online_timeout = 0;
520         TALLOC_FREE(domain->check_online_event);
521
522         /* Ensure we ignore any pending child messages. */
523         messaging_deregister(winbind_messaging_context(),
524                              MSG_WINBIND_TRY_TO_GO_ONLINE, NULL);
525         messaging_deregister(winbind_messaging_context(),
526                              MSG_WINBIND_FAILED_TO_GO_ONLINE, NULL);
527
528         domain->online = True;
529
530         /* Send a message to the parent that the domain is online. */
531         if (parent_pid > 1 && !domain->internal) {
532                 messaging_send_buf(winbind_messaging_context(),
533                                    pid_to_procid(parent_pid),
534                                    MSG_WINBIND_DOMAIN_ONLINE,
535                                    (uint8 *)domain->name,
536                                    strlen(domain->name) + 1);
537         }
538
539         /* Send an online message to the idmap child when our
540            primary domain comes online */
541
542         if ( domain->primary ) {
543                 struct winbindd_child *idmap = idmap_child();
544
545                 if ( idmap->pid != 0 ) {
546                         messaging_send_buf(winbind_messaging_context(),
547                                            pid_to_procid(idmap->pid), 
548                                            MSG_WINBIND_ONLINE, 
549                                            (const uint8_t *)domain->name,
550                                            strlen(domain->name)+1);
551                 }                       
552         }
553
554         return; 
555 }
556
557 /****************************************************************
558  Requested to set a domain online.
559 ****************************************************************/
560
561 void set_domain_online_request(struct winbindd_domain *domain)
562 {
563         struct timeval tev;
564
565         DEBUG(10,("set_domain_online_request: called for domain %s\n",
566                 domain->name ));
567
568         if (get_global_winbindd_state_offline()) {
569                 DEBUG(10,("set_domain_online_request: domain %s remaining globally offline\n",
570                         domain->name ));
571                 return;
572         }
573
574         if (domain->internal) {
575                 DEBUG(10, ("set_domain_online_request: Internal domains are "
576                            "always online\n"));
577                 return;
578         }
579
580         /* We've been told it's safe to go online and
581            try and connect to a DC. But I don't believe it
582            because network manager seems to lie.
583            Wait at least 5 seconds. Heuristics suck... */
584
585
586         GetTimeOfDay(&tev);
587
588         /* Go into "startup" mode again. */
589         domain->startup_time = time_mono(NULL);
590         domain->startup = True;
591
592         tev.tv_sec += 5;
593
594         if (!domain->check_online_event) {
595                 /* If we've come from being globally offline we
596                    don't have a check online event handler set.
597                    We need to add one now we're trying to go
598                    back online. */
599
600                 DEBUG(10,("set_domain_online_request: domain %s was globally offline.\n",
601                         domain->name ));
602         }
603
604         TALLOC_FREE(domain->check_online_event);
605
606         domain->check_online_event = tevent_add_timer(winbind_event_context(),
607                                                      NULL,
608                                                      tev,
609                                                      check_domain_online_handler,
610                                                      domain);
611
612         /* The above *has* to succeed for winbindd to work. */
613         if (!domain->check_online_event) {
614                 smb_panic("set_domain_online_request: failed to add online handler");
615         }
616 }
617
618 /****************************************************************
619  Add -ve connection cache entries for domain and realm.
620 ****************************************************************/
621
622 static void winbind_add_failed_connection_entry(
623         const struct winbindd_domain *domain,
624         const char *server,
625         NTSTATUS result)
626 {
627         add_failed_connection_entry(domain->name, server, result);
628         /* If this was the saf name for the last thing we talked to,
629            remove it. */
630         saf_delete(domain->name);
631         if (domain->alt_name != NULL) {
632                 add_failed_connection_entry(domain->alt_name, server, result);
633                 saf_delete(domain->alt_name);
634         }
635         winbindd_unset_locator_kdc_env(domain);
636 }
637
638 /* Choose between anonymous or authenticated connections.  We need to use
639    an authenticated connection if DCs have the RestrictAnonymous registry
640    entry set > 0, or the "Additional restrictions for anonymous
641    connections" set in the win2k Local Security Policy. 
642
643    Caller to free() result in domain, username, password
644 */
645
646 static void cm_get_ipc_userpass(char **username, char **domain, char **password)
647 {
648         *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
649         *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
650         *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
651
652         if (*username && **username) {
653
654                 if (!*domain || !**domain)
655                         *domain = smb_xstrdup(lp_workgroup());
656
657                 if (!*password || !**password)
658                         *password = smb_xstrdup("");
659
660                 DEBUG(3, ("cm_get_ipc_userpass: Retrieved auth-user from secrets.tdb [%s\\%s]\n", 
661                           *domain, *username));
662
663         } else {
664                 DEBUG(3, ("cm_get_ipc_userpass: No auth-user defined\n"));
665                 *username = smb_xstrdup("");
666                 *domain = smb_xstrdup("");
667                 *password = smb_xstrdup("");
668         }
669 }
670
671 static NTSTATUS cm_get_ipc_credentials(TALLOC_CTX *mem_ctx,
672                                        struct cli_credentials **_creds)
673 {
674
675         TALLOC_CTX *frame = talloc_stackframe();
676         NTSTATUS status = NT_STATUS_INTERNAL_ERROR;
677         struct loadparm_context *lp_ctx;
678         char *username = NULL;
679         char *netbios_domain = NULL;
680         char *password = NULL;
681         struct cli_credentials *creds = NULL;
682         bool ok;
683
684         cm_get_ipc_userpass(&username, &netbios_domain, &password);
685
686         lp_ctx = loadparm_init_s3(frame, loadparm_s3_helpers());
687         if (lp_ctx == NULL) {
688                 DEBUG(1, ("loadparm_init_s3 failed\n"));
689                 status = NT_STATUS_INTERNAL_ERROR;
690                 goto fail;
691         }
692
693         creds = cli_credentials_init(mem_ctx);
694         if (creds == NULL) {
695                 status = NT_STATUS_NO_MEMORY;
696                 goto fail;
697         }
698
699         cli_credentials_set_conf(creds, lp_ctx);
700         cli_credentials_set_kerberos_state(creds, CRED_DONT_USE_KERBEROS);
701
702         ok = cli_credentials_set_domain(creds, netbios_domain, CRED_SPECIFIED);
703         if (!ok) {
704                 status = NT_STATUS_NO_MEMORY;
705                 goto fail;
706         }
707
708         ok = cli_credentials_set_username(creds, username, CRED_SPECIFIED);
709         if (!ok) {
710                 status = NT_STATUS_NO_MEMORY;
711                 goto fail;
712         }
713
714         ok = cli_credentials_set_password(creds, password, CRED_SPECIFIED);
715         if (!ok) {
716                 status = NT_STATUS_NO_MEMORY;
717                 goto fail;
718         }
719
720         *_creds = creds;
721         creds = NULL;
722         status = NT_STATUS_OK;
723  fail:
724         TALLOC_FREE(creds);
725         SAFE_FREE(username);
726         SAFE_FREE(netbios_domain);
727         SAFE_FREE(password);
728         TALLOC_FREE(frame);
729         return status;
730 }
731
732 static bool cm_is_ipc_credentials(struct cli_credentials *creds)
733 {
734         TALLOC_CTX *frame = talloc_stackframe();
735         char *ipc_account = NULL;
736         char *ipc_domain = NULL;
737         char *ipc_password = NULL;
738         const char *creds_account = NULL;
739         const char *creds_domain = NULL;
740         const char *creds_password = NULL;
741         bool ret = false;
742
743         cm_get_ipc_userpass(&ipc_account, &ipc_domain, &ipc_password);
744
745         creds_account = cli_credentials_get_username(creds);
746         creds_domain = cli_credentials_get_domain(creds);
747         creds_password = cli_credentials_get_password(creds);
748
749         if (!strequal(ipc_domain, creds_domain)) {
750                 goto done;
751         }
752
753         if (!strequal(ipc_account, creds_account)) {
754                 goto done;
755         }
756
757         if (!strcsequal(ipc_password, creds_password)) {
758                 goto done;
759         }
760
761         ret = true;
762  done:
763         SAFE_FREE(ipc_account);
764         SAFE_FREE(ipc_domain);
765         SAFE_FREE(ipc_password);
766         TALLOC_FREE(frame);
767         return ret;
768 }
769
770 static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
771                                      fstring dcname,
772                                      struct sockaddr_storage *dc_ss)
773 {
774         struct winbindd_domain *our_domain = NULL;
775         struct rpc_pipe_client *netlogon_pipe = NULL;
776         NTSTATUS result;
777         WERROR werr;
778         TALLOC_CTX *mem_ctx;
779         unsigned int orig_timeout;
780         const char *tmp = NULL;
781         const char *p;
782         struct dcerpc_binding_handle *b;
783
784         /* Hmmmm. We can only open one connection to the NETLOGON pipe at the
785          * moment.... */
786
787         if (IS_DC) {
788                 return False;
789         }
790
791         if (domain->primary) {
792                 return False;
793         }
794
795         our_domain = find_our_domain();
796
797         if ((mem_ctx = talloc_init("get_dc_name_via_netlogon")) == NULL) {
798                 return False;
799         }
800
801         result = cm_connect_netlogon(our_domain, &netlogon_pipe);
802         if (!NT_STATUS_IS_OK(result)) {
803                 talloc_destroy(mem_ctx);
804                 return False;
805         }
806
807         b = netlogon_pipe->binding_handle;
808
809         /* This call can take a long time - allow the server to time out.
810            35 seconds should do it. */
811
812         orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
813
814         if (our_domain->active_directory) {
815                 struct netr_DsRGetDCNameInfo *domain_info = NULL;
816
817                 result = dcerpc_netr_DsRGetDCName(b,
818                                                   mem_ctx,
819                                                   our_domain->dcname,
820                                                   domain->name,
821                                                   NULL,
822                                                   NULL,
823                                                   DS_RETURN_DNS_NAME,
824                                                   &domain_info,
825                                                   &werr);
826                 if (NT_STATUS_IS_OK(result) && W_ERROR_IS_OK(werr)) {
827                         tmp = talloc_strdup(
828                                 mem_ctx, domain_info->dc_unc);
829                         if (tmp == NULL) {
830                                 DEBUG(0, ("talloc_strdup failed\n"));
831                                 talloc_destroy(mem_ctx);
832                                 return false;
833                         }
834                         if (domain->alt_name == NULL) {
835                                 domain->alt_name = talloc_strdup(domain,
836                                                                  domain_info->domain_name);
837                                 if (domain->alt_name == NULL) {
838                                         DEBUG(0, ("talloc_strdup failed\n"));
839                                         talloc_destroy(mem_ctx);
840                                         return false;
841                                 }
842                         }
843                         if (domain->forest_name == NULL) {
844                                 domain->forest_name = talloc_strdup(domain,
845                                                                     domain_info->forest_name);
846                                 if (domain->forest_name == NULL) {
847                                         DEBUG(0, ("talloc_strdup failed\n"));
848                                         talloc_destroy(mem_ctx);
849                                         return false;
850                                 }
851                         }
852                 }
853         } else {
854                 result = dcerpc_netr_GetAnyDCName(b, mem_ctx,
855                                                   our_domain->dcname,
856                                                   domain->name,
857                                                   &tmp,
858                                                   &werr);
859         }
860
861         /* And restore our original timeout. */
862         rpccli_set_timeout(netlogon_pipe, orig_timeout);
863
864         if (!NT_STATUS_IS_OK(result)) {
865                 DEBUG(10,("dcerpc_netr_GetAnyDCName failed: %s\n",
866                         nt_errstr(result)));
867                 talloc_destroy(mem_ctx);
868                 return false;
869         }
870
871         if (!W_ERROR_IS_OK(werr)) {
872                 DEBUG(10,("dcerpc_netr_GetAnyDCName failed: %s\n",
873                            win_errstr(werr)));
874                 talloc_destroy(mem_ctx);
875                 return false;
876         }
877
878         /* dcerpc_netr_GetAnyDCName gives us a name with \\ */
879         p = strip_hostname(tmp);
880
881         fstrcpy(dcname, p);
882
883         talloc_destroy(mem_ctx);
884
885         DEBUG(10,("dcerpc_netr_GetAnyDCName returned %s\n", dcname));
886
887         if (!resolve_name(dcname, dc_ss, 0x20, true)) {
888                 return False;
889         }
890
891         return True;
892 }
893
894 /**
895  * Helper function to assemble trust password and account name
896  */
897 static NTSTATUS get_trust_credentials(struct winbindd_domain *domain,
898                                       TALLOC_CTX *mem_ctx,
899                                       bool netlogon,
900                                       struct cli_credentials **_creds)
901 {
902         const struct winbindd_domain *creds_domain = NULL;
903         struct cli_credentials *creds;
904         NTSTATUS status;
905         bool force_machine_account = false;
906
907         /* If we are a DC and this is not our own domain */
908
909         if (!domain->active_directory) {
910                 if (!netlogon) {
911                         /*
912                          * For non active directory domains
913                          * we can only use NTLMSSP for SMB.
914                          *
915                          * But the trust account is not allowed
916                          * to use SMB with NTLMSSP.
917                          */
918                         force_machine_account = true;
919                 }
920         }
921
922         if (IS_DC && !force_machine_account) {
923                 creds_domain = domain;
924         } else {
925                 creds_domain = find_our_domain();
926                 if (creds_domain == NULL) {
927                         return NT_STATUS_INVALID_SERVER_STATE;
928                 }
929         }
930
931         status = pdb_get_trust_credentials(creds_domain->name,
932                                            creds_domain->alt_name,
933                                            mem_ctx,
934                                            &creds);
935         if (!NT_STATUS_IS_OK(status)) {
936                 goto ipc_fallback;
937         }
938
939         if (domain->primary && lp_security() == SEC_ADS) {
940                 cli_credentials_set_kerberos_state(creds,
941                                                    CRED_AUTO_USE_KERBEROS);
942         } else if (domain->active_directory) {
943                 cli_credentials_set_kerberos_state(creds,
944                                                    CRED_MUST_USE_KERBEROS);
945         } else {
946                 cli_credentials_set_kerberos_state(creds,
947                                                    CRED_DONT_USE_KERBEROS);
948         }
949
950         if (creds_domain != domain) {
951                 /*
952                  * We can only use schannel against a direct trust
953                  */
954                 cli_credentials_set_secure_channel_type(creds,
955                                                         SEC_CHAN_NULL);
956         }
957
958         *_creds = creds;
959         return NT_STATUS_OK;
960
961  ipc_fallback:
962         if (netlogon) {
963                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
964         }
965
966         status = cm_get_ipc_credentials(mem_ctx, &creds);
967         if (!NT_STATUS_IS_OK(status)) {
968                 return status;
969         }
970
971         *_creds = creds;
972         return NT_STATUS_OK;
973 }
974
975 /************************************************************************
976  Given a fd with a just-connected TCP connection to a DC, open a connection
977  to the pipe.
978 ************************************************************************/
979
980 static NTSTATUS cm_prepare_connection(struct winbindd_domain *domain,
981                                       const int sockfd,
982                                       const char *controller,
983                                       struct cli_state **cli,
984                                       bool *retry)
985 {
986         bool try_ipc_auth = false;
987         const char *machine_password = NULL;
988         const char *machine_krb5_principal = NULL;
989         const char *machine_account = NULL;
990         const char *machine_domain = NULL;
991         int flags = 0;
992         struct cli_credentials *creds = NULL;
993         enum credentials_use_kerberos krb5_state;
994
995         struct named_mutex *mutex;
996
997         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
998
999         enum smb_signing_setting smb_sign_client_connections = lp_client_signing();
1000
1001         if (smb_sign_client_connections == SMB_SIGNING_DEFAULT) {
1002                 /*
1003                  * If we are connecting to our own AD domain, require
1004                  * smb signing to disrupt MITM attacks
1005                  */
1006                 if (domain->primary && lp_security() == SEC_ADS) {
1007                         smb_sign_client_connections = SMB_SIGNING_REQUIRED;
1008                 /*
1009                  * If we are in or are an AD domain and connecting to another
1010                  * AD domain in our forest
1011                  * then require smb signing to disrupt MITM attacks
1012                  */
1013                 } else if ((lp_security() == SEC_ADS ||
1014                             lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC)
1015                            && domain->active_directory
1016                            && (domain->domain_trust_attribs
1017                                & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST)) {
1018                         smb_sign_client_connections = SMB_SIGNING_REQUIRED;
1019                 }
1020         }
1021
1022         DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
1023                 controller, domain->name ));
1024
1025         *retry = True;
1026
1027         mutex = grab_named_mutex(talloc_tos(), controller,
1028                                  WINBIND_SERVER_MUTEX_WAIT_TIME);
1029         if (mutex == NULL) {
1030                 close(sockfd);
1031                 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
1032                          controller));
1033                 result = NT_STATUS_POSSIBLE_DEADLOCK;
1034                 goto done;
1035         }
1036
1037         flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1038
1039         *cli = cli_state_create(NULL, sockfd,
1040                                 controller, domain->alt_name,
1041                                 smb_sign_client_connections, flags);
1042         if (*cli == NULL) {
1043                 close(sockfd);
1044                 DEBUG(1, ("Could not cli_initialize\n"));
1045                 result = NT_STATUS_NO_MEMORY;
1046                 goto done;
1047         }
1048
1049         cli_set_timeout(*cli, 10000); /* 10 seconds */
1050
1051         result = smbXcli_negprot((*cli)->conn, (*cli)->timeout,
1052                                  lp_client_min_protocol(),
1053                                  lp_winbindd_max_protocol());
1054
1055         if (!NT_STATUS_IS_OK(result)) {
1056                 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
1057                 goto done;
1058         }
1059
1060         if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_NT1 &&
1061             smb1cli_conn_capabilities((*cli)->conn) & CAP_EXTENDED_SECURITY) {
1062                 try_ipc_auth = true;
1063         } else if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1064                 try_ipc_auth = true;
1065         } else if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1066                 /*
1067                  * If we are forcing on SMB signing, then we must
1068                  * require authentication unless this is a one-way
1069                  * trust, and we have no stored user/password
1070                  */
1071                 try_ipc_auth = true;
1072         }
1073
1074         if (try_ipc_auth) {
1075                 result = get_trust_credentials(domain, talloc_tos(), false, &creds);
1076                 if (!NT_STATUS_IS_OK(result)) {
1077                         DEBUG(1, ("get_trust_credentials(%s) failed: %s\n",
1078                                   domain->name, nt_errstr(result)));
1079                         goto done;
1080                 }
1081         } else {
1082                 /*
1083                  * Without SPNEGO or NTLMSSP (perhaps via SMB2) we
1084                  * would try and authentication with our machine
1085                  * account password and fail.  This is very rare in
1086                  * the modern world however
1087                  */
1088                 creds = cli_credentials_init_anon(talloc_tos());
1089                 if (creds == NULL) {
1090                         result = NT_STATUS_NO_MEMORY;
1091                         DEBUG(1, ("cli_credentials_init_anon(%s) failed: %s\n",
1092                                   domain->name, nt_errstr(result)));
1093                         goto done;
1094                 }
1095         }
1096
1097         krb5_state = cli_credentials_get_kerberos_state(creds);
1098
1099         machine_krb5_principal = cli_credentials_get_principal(creds,
1100                                                         talloc_tos());
1101         if (machine_krb5_principal == NULL) {
1102                 krb5_state = CRED_DONT_USE_KERBEROS;
1103         }
1104
1105         machine_account = cli_credentials_get_username(creds);
1106         machine_password = cli_credentials_get_password(creds);
1107         machine_domain = cli_credentials_get_domain(creds);
1108
1109         if (krb5_state != CRED_DONT_USE_KERBEROS) {
1110
1111                 /* Try a krb5 session */
1112
1113                 (*cli)->use_kerberos = True;
1114                 DEBUG(5, ("connecting to %s from %s with kerberos principal "
1115                           "[%s] and realm [%s]\n", controller, lp_netbios_name(),
1116                           machine_krb5_principal, domain->alt_name));
1117
1118                 winbindd_set_locator_kdc_envs(domain);
1119
1120                 result = cli_session_setup(*cli,
1121                                            machine_krb5_principal,
1122                                            machine_password,
1123                                            strlen(machine_password)+1,
1124                                            machine_password,
1125                                            strlen(machine_password)+1,
1126                                            machine_domain);
1127
1128                 if (NT_STATUS_IS_OK(result)) {
1129                         goto session_setup_done;
1130                 }
1131
1132                 DEBUG(4,("failed kerberos session setup with %s\n",
1133                          nt_errstr(result)));
1134         }
1135
1136         if (krb5_state != CRED_MUST_USE_KERBEROS) {
1137                 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
1138                 (*cli)->use_kerberos = False;
1139
1140                 DEBUG(5, ("connecting to %s from %s using NTLMSSP with username "
1141                           "[%s]\\[%s]\n",  controller, lp_netbios_name(),
1142                           machine_domain, machine_account));
1143
1144                 result = cli_session_setup(*cli,
1145                                            machine_account,
1146                                            machine_password,
1147                                            strlen(machine_password)+1,
1148                                            machine_password,
1149                                            strlen(machine_password)+1,
1150                                            machine_domain);
1151         }
1152
1153         if (NT_STATUS_IS_OK(result)) {
1154                 goto session_setup_done;
1155         }
1156
1157         /*
1158          * If we are not going to validiate the conneciton
1159          * with SMB signing, then allow us to fall back to
1160          * anonymous
1161          */
1162         if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1163             || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1164             || NT_STATUS_EQUAL(result, NT_STATUS_INVALID_ACCOUNT_NAME)
1165             || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1166         {
1167                 if (cli_credentials_is_anonymous(creds)) {
1168                         goto done;
1169                 }
1170
1171                 if (!cm_is_ipc_credentials(creds)) {
1172                         goto ipc_fallback;
1173                 }
1174
1175                 if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1176                         goto done;
1177                 }
1178
1179                 goto anon_fallback;
1180         }
1181
1182         DEBUG(4, ("authenticated session setup failed with %s\n",
1183                 nt_errstr(result)));
1184
1185         goto done;
1186
1187  ipc_fallback:
1188         result = cm_get_ipc_credentials(talloc_tos(), &creds);
1189         if (!NT_STATUS_IS_OK(result)) {
1190                 goto done;
1191         }
1192
1193         if (cli_credentials_is_anonymous(creds)) {
1194                 TALLOC_FREE(creds);
1195                 goto anon_fallback;
1196         }
1197
1198         machine_account = cli_credentials_get_username(creds);
1199         machine_password = cli_credentials_get_password(creds);
1200         machine_domain = cli_credentials_get_domain(creds);
1201
1202         /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the ipc creds. */
1203         (*cli)->use_kerberos = False;
1204
1205         DEBUG(5, ("connecting to %s from %s using NTLMSSP with username "
1206                   "[%s]\\[%s]\n",  controller, lp_netbios_name(),
1207                   machine_domain, machine_account));
1208
1209         result = cli_session_setup(*cli,
1210                                    machine_account,
1211                                    machine_password,
1212                                    strlen(machine_password)+1,
1213                                    machine_password,
1214                                    strlen(machine_password)+1,
1215                                    machine_domain);
1216
1217         if (NT_STATUS_IS_OK(result)) {
1218                 goto session_setup_done;
1219         }
1220
1221         /*
1222          * If we are not going to validiate the conneciton
1223          * with SMB signing, then allow us to fall back to
1224          * anonymous
1225          */
1226         if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1227             || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1228             || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1229         {
1230                 goto anon_fallback;
1231         }
1232
1233         DEBUG(4, ("authenticated session setup failed with %s\n",
1234                 nt_errstr(result)));
1235
1236         goto done;
1237
1238  anon_fallback:
1239
1240         if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1241                 goto done;
1242         }
1243
1244         /* Fall back to anonymous connection, this might fail later */
1245         DEBUG(10,("cm_prepare_connection: falling back to anonymous "
1246                 "connection for DC %s\n",
1247                 controller ));
1248
1249         (*cli)->use_kerberos = False;
1250
1251         result = cli_session_setup(*cli, "", "", 0, "", 0, "");
1252         if (NT_STATUS_IS_OK(result)) {
1253                 DEBUG(5, ("Connected anonymously\n"));
1254                 goto session_setup_done;
1255         }
1256
1257         /* We can't session setup */
1258         goto done;
1259
1260  session_setup_done:
1261
1262         /*
1263          * This should be a short term hack until
1264          * dynamic re-authentication is implemented.
1265          *
1266          * See Bug 9175 - winbindd doesn't recover from
1267          * NT_STATUS_NETWORK_SESSION_EXPIRED
1268          */
1269         if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1270                 smbXcli_session_set_disconnect_expired((*cli)->smb2.session);
1271         }
1272
1273         result = cli_tree_connect(*cli, "IPC$", "IPC", "", 0);
1274
1275         if (!NT_STATUS_IS_OK(result)) {
1276                 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
1277                 goto done;
1278         }
1279
1280         /* cache the server name for later connections */
1281
1282         saf_store(domain->name, controller);
1283         if (domain->alt_name && (*cli)->use_kerberos) {
1284                 saf_store(domain->alt_name, controller);
1285         }
1286
1287         winbindd_set_locator_kdc_envs(domain);
1288
1289         TALLOC_FREE(mutex);
1290         *retry = False;
1291
1292         result = NT_STATUS_OK;
1293
1294  done:
1295         TALLOC_FREE(mutex);
1296
1297         if (!NT_STATUS_IS_OK(result)) {
1298                 winbind_add_failed_connection_entry(domain, controller, result);
1299                 if ((*cli) != NULL) {
1300                         cli_shutdown(*cli);
1301                         *cli = NULL;
1302                 }
1303         }
1304
1305         return result;
1306 }
1307
1308 /*******************************************************************
1309  Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1310  array.
1311
1312  Keeps the list unique by not adding duplicate entries.
1313
1314  @param[in] mem_ctx talloc memory context to allocate from
1315  @param[in] domain_name domain of the DC
1316  @param[in] dcname name of the DC to add to the list
1317  @param[in] pss Internet address and port pair to add to the list
1318  @param[in,out] dcs array of dc_name_ip structures to add to
1319  @param[in,out] num_dcs number of dcs returned in the dcs array
1320  @return true if the list was added to, false otherwise
1321 *******************************************************************/
1322
1323 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1324                               const char *dcname, struct sockaddr_storage *pss,
1325                               struct dc_name_ip **dcs, int *num)
1326 {
1327         int i = 0;
1328
1329         if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1330                 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1331                 return False;
1332         }
1333
1334         /* Make sure there's no duplicates in the list */
1335         for (i=0; i<*num; i++)
1336                 if (sockaddr_equal(
1337                             (struct sockaddr *)(void *)&(*dcs)[i].ss,
1338                             (struct sockaddr *)(void *)pss))
1339                         return False;
1340
1341         *dcs = talloc_realloc(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1342
1343         if (*dcs == NULL)
1344                 return False;
1345
1346         fstrcpy((*dcs)[*num].name, dcname);
1347         (*dcs)[*num].ss = *pss;
1348         *num += 1;
1349         return True;
1350 }
1351
1352 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1353                                   struct sockaddr_storage *pss, uint16 port,
1354                                   struct sockaddr_storage **addrs, int *num)
1355 {
1356         *addrs = talloc_realloc(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1357
1358         if (*addrs == NULL) {
1359                 *num = 0;
1360                 return False;
1361         }
1362
1363         (*addrs)[*num] = *pss;
1364         set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1365
1366         *num += 1;
1367         return True;
1368 }
1369
1370 /*******************************************************************
1371  convert an ip to a name
1372 *******************************************************************/
1373
1374 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1375                 const struct winbindd_domain *domain,
1376                 struct sockaddr_storage *pss,
1377                 char **name)
1378 {
1379         struct ip_service ip_list;
1380         uint32_t nt_version = NETLOGON_NT_VERSION_1;
1381         NTSTATUS status;
1382         const char *dc_name;
1383         fstring nbtname;
1384 #ifdef HAVE_ADS
1385         bool is_ad_domain = false;
1386 #endif
1387         ip_list.ss = *pss;
1388         ip_list.port = 0;
1389
1390 #ifdef HAVE_ADS
1391         /* For active directory servers, try to get the ldap server name.
1392            None of these failures should be considered critical for now */
1393
1394         if ((lp_security() == SEC_ADS) && (domain->alt_name != NULL)) {
1395                 is_ad_domain = true;
1396         } else if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC) {
1397                 is_ad_domain = domain->active_directory;
1398         }
1399
1400         if (is_ad_domain) {
1401                 ADS_STRUCT *ads;
1402                 ADS_STATUS ads_status;
1403                 char addr[INET6_ADDRSTRLEN];
1404
1405                 print_sockaddr(addr, sizeof(addr), pss);
1406
1407                 ads = ads_init(domain->alt_name, domain->name, addr);
1408                 ads->auth.flags |= ADS_AUTH_NO_BIND;
1409
1410                 ads_status = ads_connect(ads);
1411                 if (ADS_ERR_OK(ads_status)) {
1412                         /* We got a cldap packet. */
1413                         *name = talloc_strdup(mem_ctx,
1414                                              ads->config.ldap_server_name);
1415                         if (*name == NULL) {
1416                                 return false;
1417                         }
1418                         namecache_store(*name, 0x20, 1, &ip_list);
1419
1420                         DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1421
1422                         if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1423                                 if (ads_closest_dc(ads)) {
1424                                         char *sitename = sitename_fetch(mem_ctx, ads->config.realm);
1425
1426                                         /* We're going to use this KDC for this realm/domain.
1427                                            If we are using sites, then force the krb5 libs
1428                                            to use this KDC. */
1429
1430                                         create_local_private_krb5_conf_for_domain(domain->alt_name,
1431                                                                         domain->name,
1432                                                                         sitename,
1433                                                                         pss);
1434
1435                                         TALLOC_FREE(sitename);
1436                                 } else {
1437                                         /* use an off site KDC */
1438                                         create_local_private_krb5_conf_for_domain(domain->alt_name,
1439                                                                         domain->name,
1440                                                                         NULL,
1441                                                                         pss);
1442                                 }
1443                                 winbindd_set_locator_kdc_envs(domain);
1444
1445                                 /* Ensure we contact this DC also. */
1446                                 saf_store(domain->name, *name);
1447                                 saf_store(domain->alt_name, *name);
1448                         }
1449
1450                         ads_destroy( &ads );
1451                         return True;
1452                 }
1453
1454                 ads_destroy( &ads );
1455                 return false;
1456         }
1457 #endif
1458
1459         status = nbt_getdc(winbind_messaging_context(), 10, pss, domain->name,
1460                            &domain->sid, nt_version, mem_ctx, &nt_version,
1461                            &dc_name, NULL);
1462         if (NT_STATUS_IS_OK(status)) {
1463                 *name = talloc_strdup(mem_ctx, dc_name);
1464                 if (*name == NULL) {
1465                         return false;
1466                 }
1467                 namecache_store(*name, 0x20, 1, &ip_list);
1468                 return True;
1469         }
1470
1471         /* try node status request */
1472
1473         if (name_status_find(domain->name, 0x1c, 0x20, pss, nbtname) ) {
1474                 namecache_store(nbtname, 0x20, 1, &ip_list);
1475
1476                 if (name != NULL) {
1477                         *name = talloc_strdup(mem_ctx, nbtname);
1478                         if (*name == NULL) {
1479                                 return false;
1480                         }
1481                 }
1482
1483                 return true;
1484         }
1485         return False;
1486 }
1487
1488 /*******************************************************************
1489  Retrieve a list of IP addresses for domain controllers.
1490
1491  The array is sorted in the preferred connection order.
1492
1493  @param[in] mem_ctx talloc memory context to allocate from
1494  @param[in] domain domain to retrieve DCs for
1495  @param[out] dcs array of dcs that will be returned
1496  @param[out] num_dcs number of dcs returned in the dcs array
1497  @return always true
1498 *******************************************************************/
1499
1500 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1501                     struct dc_name_ip **dcs, int *num_dcs)
1502 {
1503         fstring dcname;
1504         struct  sockaddr_storage ss;
1505         struct  ip_service *ip_list = NULL;
1506         int     iplist_size = 0;
1507         int     i;
1508         bool    is_our_domain;
1509         enum security_types sec = (enum security_types)lp_security();
1510
1511         is_our_domain = strequal(domain->name, lp_workgroup());
1512
1513         /* If not our domain, get the preferred DC, by asking our primary DC */
1514         if ( !is_our_domain
1515                 && get_dc_name_via_netlogon(domain, dcname, &ss)
1516                 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1517                        num_dcs) )
1518         {
1519                 char addr[INET6_ADDRSTRLEN];
1520                 print_sockaddr(addr, sizeof(addr), &ss);
1521                 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1522                            dcname, addr));
1523                 return True;
1524         }
1525
1526         if ((sec == SEC_ADS) && (domain->alt_name != NULL)) {
1527                 char *sitename = NULL;
1528
1529                 /* We need to make sure we know the local site before
1530                    doing any DNS queries, as this will restrict the
1531                    get_sorted_dc_list() call below to only fetching
1532                    DNS records for the correct site. */
1533
1534                 /* Find any DC to get the site record.
1535                    We deliberately don't care about the
1536                    return here. */
1537
1538                 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1539
1540                 sitename = sitename_fetch(mem_ctx, domain->alt_name);
1541                 if (sitename) {
1542
1543                         /* Do the site-specific AD dns lookup first. */
1544                         get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1545                                &iplist_size, True);
1546
1547                         /* Add ips to the DC array.  We don't look up the name
1548                            of the DC in this function, but we fill in the char*
1549                            of the ip now to make the failed connection cache
1550                            work */
1551                         for ( i=0; i<iplist_size; i++ ) {
1552                                 char addr[INET6_ADDRSTRLEN];
1553                                 print_sockaddr(addr, sizeof(addr),
1554                                                 &ip_list[i].ss);
1555                                 add_one_dc_unique(mem_ctx,
1556                                                 domain->name,
1557                                                 addr,
1558                                                 &ip_list[i].ss,
1559                                                 dcs,
1560                                                 num_dcs);
1561                         }
1562
1563                         SAFE_FREE(ip_list);
1564                         TALLOC_FREE(sitename);
1565                         iplist_size = 0;
1566                 }
1567
1568                 /* Now we add DCs from the main AD DNS lookup. */
1569                 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1570                         &iplist_size, True);
1571
1572                 for ( i=0; i<iplist_size; i++ ) {
1573                         char addr[INET6_ADDRSTRLEN];
1574                         print_sockaddr(addr, sizeof(addr),
1575                                         &ip_list[i].ss);
1576                         add_one_dc_unique(mem_ctx,
1577                                         domain->name,
1578                                         addr,
1579                                         &ip_list[i].ss,
1580                                         dcs,
1581                                         num_dcs);
1582                 }
1583
1584                 SAFE_FREE(ip_list);
1585                 iplist_size = 0;
1586         }
1587
1588         /* Try standard netbios queries if no ADS and fall back to DNS queries
1589          * if alt_name is available */
1590         if (*num_dcs == 0) {
1591                 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1592                        false);
1593                 if (iplist_size == 0) {
1594                         if (domain->alt_name != NULL) {
1595                                 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1596                                        &iplist_size, true);
1597                         }
1598                 }
1599
1600                 for ( i=0; i<iplist_size; i++ ) {
1601                         char addr[INET6_ADDRSTRLEN];
1602                         print_sockaddr(addr, sizeof(addr),
1603                                         &ip_list[i].ss);
1604                         add_one_dc_unique(mem_ctx,
1605                                         domain->name,
1606                                         addr,
1607                                         &ip_list[i].ss,
1608                                         dcs,
1609                                         num_dcs);
1610                 }
1611
1612                 SAFE_FREE(ip_list);
1613                 iplist_size = 0;
1614         }
1615
1616         return True;
1617 }
1618
1619 /*******************************************************************
1620  Find and make a connection to a DC in the given domain.
1621
1622  @param[in] mem_ctx talloc memory context to allocate from
1623  @param[in] domain domain to find a dc in
1624  @param[out] dcname NetBIOS or FQDN of DC that's connected to
1625  @param[out] pss DC Internet address and port
1626  @param[out] fd fd of the open socket connected to the newly found dc
1627  @return true when a DC connection is made, false otherwise
1628 *******************************************************************/
1629
1630 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1631                         struct winbindd_domain *domain,
1632                         char **dcname, struct sockaddr_storage *pss, int *fd)
1633 {
1634         struct dc_name_ip *dcs = NULL;
1635         int num_dcs = 0;
1636
1637         const char **dcnames = NULL;
1638         size_t num_dcnames = 0;
1639
1640         struct sockaddr_storage *addrs = NULL;
1641         int num_addrs = 0;
1642
1643         int i;
1644         size_t fd_index;
1645
1646         NTSTATUS status;
1647
1648         *fd = -1;
1649
1650  again:
1651         if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1652                 return False;
1653
1654         for (i=0; i<num_dcs; i++) {
1655
1656                 if (!add_string_to_array(mem_ctx, dcs[i].name,
1657                                     &dcnames, &num_dcnames)) {
1658                         return False;
1659                 }
1660                 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, TCP_SMB_PORT,
1661                                       &addrs, &num_addrs)) {
1662                         return False;
1663                 }
1664         }
1665
1666         if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1667                 return False;
1668
1669         if ((addrs == NULL) || (dcnames == NULL))
1670                 return False;
1671
1672         status = smbsock_any_connect(addrs, dcnames, NULL, NULL, NULL,
1673                                      num_addrs, 0, 10, fd, &fd_index, NULL);
1674         if (!NT_STATUS_IS_OK(status)) {
1675                 for (i=0; i<num_dcs; i++) {
1676                         char ab[INET6_ADDRSTRLEN];
1677                         print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1678                         DEBUG(10, ("find_new_dc: smbsock_any_connect failed for "
1679                                 "domain %s address %s. Error was %s\n",
1680                                    domain->name, ab, nt_errstr(status) ));
1681                         winbind_add_failed_connection_entry(domain,
1682                                 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1683                 }
1684                 return False;
1685         }
1686
1687         *pss = addrs[fd_index];
1688
1689         if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1690                 /* Ok, we've got a name for the DC */
1691                 *dcname = talloc_strdup(mem_ctx, dcnames[fd_index]);
1692                 if (*dcname == NULL) {
1693                         return false;
1694                 }
1695                 return true;
1696         }
1697
1698         /* Try to figure out the name */
1699         if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1700                 return True;
1701         }
1702
1703         /* We can not continue without the DC's name */
1704         winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1705                                     NT_STATUS_UNSUCCESSFUL);
1706
1707         /* Throw away all arrays as we're doing this again. */
1708         TALLOC_FREE(dcs);
1709         num_dcs = 0;
1710
1711         TALLOC_FREE(dcnames);
1712         num_dcnames = 0;
1713
1714         TALLOC_FREE(addrs);
1715         num_addrs = 0;
1716
1717         close(*fd);
1718         *fd = -1;
1719
1720         goto again;
1721 }
1722
1723 static char *current_dc_key(TALLOC_CTX *mem_ctx, const char *domain_name)
1724 {
1725         return talloc_asprintf_strupper_m(mem_ctx, "CURRENT_DCNAME/%s",
1726                                           domain_name);
1727 }
1728
1729 static void store_current_dc_in_gencache(const char *domain_name,
1730                                          const char *dc_name,
1731                                          struct cli_state *cli)
1732 {
1733         char addr[INET6_ADDRSTRLEN];
1734         char *key = NULL;
1735         char *value = NULL;
1736
1737         if (!cli_state_is_connected(cli)) {
1738                 return;
1739         }
1740
1741         print_sockaddr(addr, sizeof(addr),
1742                        smbXcli_conn_remote_sockaddr(cli->conn));
1743
1744         key = current_dc_key(talloc_tos(), domain_name);
1745         if (key == NULL) {
1746                 goto done;
1747         }
1748
1749         value = talloc_asprintf(talloc_tos(), "%s %s", addr, dc_name);
1750         if (value == NULL) {
1751                 goto done;
1752         }
1753
1754         gencache_set(key, value, 0x7fffffff);
1755 done:
1756         TALLOC_FREE(value);
1757         TALLOC_FREE(key);
1758 }
1759
1760 bool fetch_current_dc_from_gencache(TALLOC_CTX *mem_ctx,
1761                                     const char *domain_name,
1762                                     char **p_dc_name, char **p_dc_ip)
1763 {
1764         char *key, *p;
1765         char *value = NULL;
1766         bool ret = false;
1767         char *dc_name = NULL;
1768         char *dc_ip = NULL;
1769
1770         key = current_dc_key(talloc_tos(), domain_name);
1771         if (key == NULL) {
1772                 goto done;
1773         }
1774         if (!gencache_get(key, mem_ctx, &value, NULL)) {
1775                 goto done;
1776         }
1777         p = strchr(value, ' ');
1778         if (p == NULL) {
1779                 goto done;
1780         }
1781         dc_ip = talloc_strndup(mem_ctx, value, p - value);
1782         if (dc_ip == NULL) {
1783                 goto done;
1784         }
1785         dc_name = talloc_strdup(mem_ctx, p+1);
1786         if (dc_name == NULL) {
1787                 goto done;
1788         }
1789
1790         if (p_dc_ip != NULL) {
1791                 *p_dc_ip = dc_ip;
1792                 dc_ip = NULL;
1793         }
1794         if (p_dc_name != NULL) {
1795                 *p_dc_name = dc_name;
1796                 dc_name = NULL;
1797         }
1798         ret = true;
1799 done:
1800         TALLOC_FREE(dc_name);
1801         TALLOC_FREE(dc_ip);
1802         TALLOC_FREE(key);
1803         TALLOC_FREE(value);
1804         return ret;
1805 }
1806
1807 NTSTATUS wb_open_internal_pipe(TALLOC_CTX *mem_ctx,
1808                                const struct ndr_interface_table *table,
1809                                struct rpc_pipe_client **ret_pipe)
1810 {
1811         struct rpc_pipe_client *cli = NULL;
1812         const struct auth_session_info *session_info;
1813         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1814
1815
1816         session_info = get_session_info_system();
1817         SMB_ASSERT(session_info != NULL);
1818
1819         /* create a connection to the specified pipe */
1820         if (lp_parm_bool(-1, "winbindd", "use external pipes", false)) {
1821                 status = rpc_pipe_open_interface(mem_ctx,
1822                                                  table,
1823                                                  session_info,
1824                                                  NULL,
1825                                                  winbind_messaging_context(),
1826                                                  &cli);
1827         } else {
1828                 status = rpc_pipe_open_internal(mem_ctx,
1829                                                 &table->syntax_id,
1830                                                 session_info,
1831                                                 NULL,
1832                                                 winbind_messaging_context(),
1833                                                 &cli);
1834         }
1835         if (!NT_STATUS_IS_OK(status)) {
1836                 DEBUG(0, ("open_internal_pipe: Could not connect to %s pipe: %s\n",
1837                           table->name, nt_errstr(status)));
1838                 return status;
1839         }
1840
1841         if (ret_pipe) {
1842                 *ret_pipe = cli;
1843         }
1844
1845         return NT_STATUS_OK;
1846 }
1847
1848 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1849                                    struct winbindd_cm_conn *new_conn)
1850 {
1851         TALLOC_CTX *mem_ctx;
1852         NTSTATUS result;
1853         char *saf_servername;
1854         int retries;
1855
1856         if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1857                 set_domain_offline(domain);
1858                 return NT_STATUS_NO_MEMORY;
1859         }
1860
1861         saf_servername = saf_fetch(mem_ctx, domain->name );
1862
1863         /* we have to check the server affinity cache here since 
1864            later we select a DC based on response time and not preference */
1865
1866         /* Check the negative connection cache
1867            before talking to it. It going down may have
1868            triggered the reconnection. */
1869
1870         if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1871
1872                 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1873                         saf_servername, domain->name ));
1874
1875                 /* convert an ip address to a name */
1876                 if (is_ipaddress( saf_servername ) ) {
1877                         char *dcname = NULL;
1878                         struct sockaddr_storage ss;
1879
1880                         if (!interpret_string_addr(&ss, saf_servername,
1881                                                 AI_NUMERICHOST)) {
1882                                 TALLOC_FREE(mem_ctx);
1883                                 return NT_STATUS_UNSUCCESSFUL;
1884                         }
1885                         if (dcip_to_name(mem_ctx, domain, &ss, &dcname)) {
1886                                 domain->dcname = talloc_strdup(domain,
1887                                                                dcname);
1888                                 if (domain->dcname == NULL) {
1889                                         TALLOC_FREE(mem_ctx);
1890                                         return NT_STATUS_NO_MEMORY;
1891                                 }
1892                         } else {
1893                                 winbind_add_failed_connection_entry(
1894                                         domain, saf_servername,
1895                                         NT_STATUS_UNSUCCESSFUL);
1896                         }
1897                 } else {
1898                         domain->dcname = talloc_strdup(domain, saf_servername);
1899                         if (domain->dcname == NULL) {
1900                                 TALLOC_FREE(mem_ctx);
1901                                 return NT_STATUS_NO_MEMORY;
1902                         }
1903                 }
1904         }
1905
1906         for (retries = 0; retries < 3; retries++) {
1907                 int fd = -1;
1908                 bool retry = False;
1909                 char *dcname = NULL;
1910
1911                 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1912
1913                 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1914                         domain->dcname ? domain->dcname : "", domain->name ));
1915
1916                 if (domain->dcname != NULL
1917                         && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1918                         && (resolve_name(domain->dcname, &domain->dcaddr, 0x20, true)))
1919                 {
1920                         NTSTATUS status;
1921
1922                         status = smbsock_connect(&domain->dcaddr, 0,
1923                                                  NULL, -1, NULL, -1,
1924                                                  &fd, NULL, 10);
1925                         if (!NT_STATUS_IS_OK(status)) {
1926                                 fd = -1;
1927                         }
1928                 }
1929
1930                 if ((fd == -1) &&
1931                     !find_new_dc(mem_ctx, domain, &dcname, &domain->dcaddr, &fd))
1932                 {
1933                         /* This is the one place where we will
1934                            set the global winbindd offline state
1935                            to true, if a "WINBINDD_OFFLINE" entry
1936                            is found in the winbindd cache. */
1937                         set_global_winbindd_state_offline();
1938                         break;
1939                 }
1940                 if (dcname != NULL) {
1941                         talloc_free(domain->dcname);
1942
1943                         domain->dcname = talloc_move(domain, &dcname);
1944                         if (domain->dcname == NULL) {
1945                                 result = NT_STATUS_NO_MEMORY;
1946                                 break;
1947                         }
1948                 }
1949
1950                 new_conn->cli = NULL;
1951
1952                 result = cm_prepare_connection(domain, fd, domain->dcname,
1953                         &new_conn->cli, &retry);
1954                 if (!NT_STATUS_IS_OK(result)) {
1955                         /* Don't leak the smb connection socket */
1956                         close(fd);
1957                 }
1958
1959                 if (!retry)
1960                         break;
1961         }
1962
1963         if (NT_STATUS_IS_OK(result)) {
1964                 bool seal_pipes = true;
1965
1966                 winbindd_set_locator_kdc_envs(domain);
1967
1968                 if (domain->online == False) {
1969                         /* We're changing state from offline to online. */
1970                         set_global_winbindd_state_online();
1971                 }
1972                 set_domain_online(domain);
1973
1974                 /*
1975                  * Much as I hate global state, this seems to be the point
1976                  * where we can be certain that we have a proper connection to
1977                  * a DC. wbinfo --dc-info needs that information, store it in
1978                  * gencache with a looong timeout. This will need revisiting
1979                  * once we start to connect to multiple DCs, wbcDcInfo is
1980                  * already prepared for that.
1981                  */
1982                 store_current_dc_in_gencache(domain->name, domain->dcname,
1983                                              new_conn->cli);
1984
1985                 seal_pipes = lp_winbind_sealed_pipes();
1986                 seal_pipes = lp_parm_bool(-1, "winbind sealed pipes",
1987                                           domain->name,
1988                                           seal_pipes);
1989
1990                 if (seal_pipes) {
1991                         new_conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1992                 } else {
1993                         new_conn->auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
1994                 }
1995         } else {
1996                 /* Ensure we setup the retry handler. */
1997                 set_domain_offline(domain);
1998         }
1999
2000         talloc_destroy(mem_ctx);
2001         return result;
2002 }
2003
2004 /* Close down all open pipes on a connection. */
2005
2006 void invalidate_cm_connection(struct winbindd_domain *domain)
2007 {
2008         NTSTATUS result;
2009         struct winbindd_cm_conn *conn = &domain->conn;
2010
2011         /* We're closing down a possibly dead
2012            connection. Don't have impossibly long (10s) timeouts. */
2013
2014         if (conn->cli) {
2015                 cli_set_timeout(conn->cli, 1000); /* 1 second. */
2016         }
2017
2018         if (conn->samr_pipe != NULL) {
2019                 if (is_valid_policy_hnd(&conn->sam_connect_handle)) {
2020                         dcerpc_samr_Close(conn->samr_pipe->binding_handle,
2021                                           talloc_tos(),
2022                                           &conn->sam_connect_handle,
2023                                           &result);
2024                 }
2025                 TALLOC_FREE(conn->samr_pipe);
2026                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2027                 if (conn->cli) {
2028                         cli_set_timeout(conn->cli, 500);
2029                 }
2030         }
2031
2032         if (conn->lsa_pipe != NULL) {
2033                 if (is_valid_policy_hnd(&conn->lsa_policy)) {
2034                         dcerpc_lsa_Close(conn->lsa_pipe->binding_handle,
2035                                          talloc_tos(),
2036                                          &conn->lsa_policy,
2037                                          &result);
2038                 }
2039                 TALLOC_FREE(conn->lsa_pipe);
2040                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2041                 if (conn->cli) {
2042                         cli_set_timeout(conn->cli, 500);
2043                 }
2044         }
2045
2046         if (conn->lsa_pipe_tcp != NULL) {
2047                 if (is_valid_policy_hnd(&conn->lsa_policy)) {
2048                         dcerpc_lsa_Close(conn->lsa_pipe_tcp->binding_handle,
2049                                          talloc_tos(),
2050                                          &conn->lsa_policy,
2051                                          &result);
2052                 }
2053                 TALLOC_FREE(conn->lsa_pipe_tcp);
2054                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2055                 if (conn->cli) {
2056                         cli_set_timeout(conn->cli, 500);
2057                 }
2058         }
2059
2060         if (conn->netlogon_pipe != NULL) {
2061                 TALLOC_FREE(conn->netlogon_pipe);
2062                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2063                 if (conn->cli) {
2064                         cli_set_timeout(conn->cli, 500);
2065                 }
2066         }
2067
2068         conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
2069         conn->netlogon_force_reauth = false;
2070         conn->netlogon_flags = 0;
2071         TALLOC_FREE(conn->netlogon_creds);
2072
2073         if (conn->cli) {
2074                 cli_shutdown(conn->cli);
2075         }
2076
2077         conn->cli = NULL;
2078 }
2079
2080 void close_conns_after_fork(void)
2081 {
2082         struct winbindd_domain *domain;
2083         struct winbindd_cli_state *cli_state;
2084
2085         for (domain = domain_list(); domain; domain = domain->next) {
2086                 /*
2087                  * first close the low level SMB TCP connection
2088                  * so that we don't generate any SMBclose
2089                  * requests in invalidate_cm_connection()
2090                  */
2091                 if (cli_state_is_connected(domain->conn.cli)) {
2092                         smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
2093                 }
2094
2095                 invalidate_cm_connection(domain);
2096         }
2097
2098         for (cli_state = winbindd_client_list();
2099              cli_state != NULL;
2100              cli_state = cli_state->next) {
2101                 if (cli_state->sock >= 0) {
2102                         close(cli_state->sock);
2103                         cli_state->sock = -1;
2104                 }
2105         }
2106 }
2107
2108 static bool connection_ok(struct winbindd_domain *domain)
2109 {
2110         bool ok;
2111
2112         ok = cli_state_is_connected(domain->conn.cli);
2113         if (!ok) {
2114                 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
2115                           domain->dcname, domain->name));
2116                 return False;
2117         }
2118
2119         if (domain->online == False) {
2120                 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
2121                 return False;
2122         }
2123
2124         return True;
2125 }
2126
2127 /* Initialize a new connection up to the RPC BIND.
2128    Bypass online status check so always does network calls. */
2129
2130 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc)
2131 {
2132         NTSTATUS result;
2133         bool skip_connection = domain->internal;
2134         if (need_rw_dc && domain->rodc) {
2135                 skip_connection = false;
2136         }
2137
2138         /* Internal connections never use the network. */
2139         if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2140                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2141         }
2142
2143         /* Still ask the internal LSA and SAMR server about the local domain */
2144         if (skip_connection || connection_ok(domain)) {
2145                 if (!domain->initialized) {
2146                         set_dc_type_and_flags(domain);
2147                 }
2148                 return NT_STATUS_OK;
2149         }
2150
2151         invalidate_cm_connection(domain);
2152
2153         if (!domain->primary && !domain->initialized) {
2154                 /*
2155                  * Before we connect to a trust, work out if it is an
2156                  * AD domain by asking our own domain.
2157                  */
2158                 set_dc_type_and_flags_trustinfo(domain);
2159         }
2160
2161         result = cm_open_connection(domain, &domain->conn);
2162
2163         if (NT_STATUS_IS_OK(result) && !domain->initialized) {
2164                 set_dc_type_and_flags(domain);
2165         }
2166
2167         return result;
2168 }
2169
2170 NTSTATUS init_dc_connection(struct winbindd_domain *domain, bool need_rw_dc)
2171 {
2172         if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2173                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2174         }
2175
2176         if (domain->initialized && !domain->online) {
2177                 /* We check for online status elsewhere. */
2178                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2179         }
2180
2181         return init_dc_connection_network(domain, need_rw_dc);
2182 }
2183
2184 static NTSTATUS init_dc_connection_rpc(struct winbindd_domain *domain, bool need_rw_dc)
2185 {
2186         NTSTATUS status;
2187
2188         status = init_dc_connection(domain, need_rw_dc);
2189         if (!NT_STATUS_IS_OK(status)) {
2190                 return status;
2191         }
2192
2193         if (!domain->internal && domain->conn.cli == NULL) {
2194                 /* happens for trusted domains without inbound trust */
2195                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2196         }
2197
2198         return NT_STATUS_OK;
2199 }
2200
2201 /******************************************************************************
2202  Set the trust flags (direction and forest location) for a domain
2203 ******************************************************************************/
2204
2205 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
2206 {
2207         struct winbindd_domain *our_domain;
2208         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2209         WERROR werr;
2210         struct netr_DomainTrustList trusts;
2211         int i;
2212         uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
2213                         NETR_TRUST_FLAG_OUTBOUND |
2214                         NETR_TRUST_FLAG_INBOUND);
2215         struct rpc_pipe_client *cli;
2216         TALLOC_CTX *mem_ctx = NULL;
2217         struct dcerpc_binding_handle *b;
2218
2219         DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
2220
2221         /* Our primary domain doesn't need to worry about trust flags.
2222            Force it to go through the network setup */
2223         if ( domain->primary ) {                
2224                 return False;           
2225         }
2226
2227         mem_ctx = talloc_stackframe();
2228         our_domain = find_our_domain();
2229         if (our_domain->internal) {
2230                 result = init_dc_connection(our_domain, false);
2231                 if (!NT_STATUS_IS_OK(result)) {
2232                         DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2233                                  "Not able to make a connection to our domain: %s\n",
2234                                   nt_errstr(result)));
2235                         TALLOC_FREE(mem_ctx);
2236                         return false;
2237                 }
2238         }
2239
2240         /* This won't work unless our domain is AD */
2241         if ( !our_domain->active_directory ) {
2242                 TALLOC_FREE(mem_ctx);
2243                 return False;
2244         }
2245
2246         if (our_domain->internal) {
2247                 result = wb_open_internal_pipe(mem_ctx, &ndr_table_netlogon, &cli);
2248         } else if (!connection_ok(our_domain)) {
2249                 DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2250                          "No connection to our domain!\n"));
2251                 TALLOC_FREE(mem_ctx);
2252                 return False;
2253         } else {
2254                 result = cm_connect_netlogon(our_domain, &cli);
2255         }
2256
2257         if (!NT_STATUS_IS_OK(result)) {
2258                 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
2259                           "a connection to %s for PIPE_NETLOGON (%s)\n", 
2260                           domain->name, nt_errstr(result)));
2261                 TALLOC_FREE(mem_ctx);
2262                 return False;
2263         }
2264         b = cli->binding_handle;
2265
2266         /* Use DsEnumerateDomainTrusts to get us the trust direction and type. */
2267         result = dcerpc_netr_DsrEnumerateDomainTrusts(b, mem_ctx,
2268                                                       cli->desthost,
2269                                                       flags,
2270                                                       &trusts,
2271                                                       &werr);
2272         if (!NT_STATUS_IS_OK(result)) {
2273                 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2274                         "failed to query trusted domain list: %s\n",
2275                         nt_errstr(result)));
2276                 TALLOC_FREE(mem_ctx);
2277                 return false;
2278         }
2279         if (!W_ERROR_IS_OK(werr)) {
2280                 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2281                         "failed to query trusted domain list: %s\n",
2282                         win_errstr(werr)));
2283                 TALLOC_FREE(mem_ctx);
2284                 return false;
2285         }
2286
2287         /* Now find the domain name and get the flags */
2288
2289         for ( i=0; i<trusts.count; i++ ) {
2290                 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
2291                         domain->domain_flags          = trusts.array[i].trust_flags;
2292                         domain->domain_type           = trusts.array[i].trust_type;
2293                         domain->domain_trust_attribs  = trusts.array[i].trust_attributes;
2294
2295                         if ( domain->domain_type == LSA_TRUST_TYPE_UPLEVEL )
2296                                 domain->active_directory = True;
2297
2298                         /* This flag is only set if the domain is *our* 
2299                            primary domain and the primary domain is in
2300                            native mode */
2301
2302                         domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
2303
2304                         DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
2305                                   "native mode.\n", domain->name, 
2306                                   domain->native_mode ? "" : "NOT "));
2307
2308                         DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
2309                                  "running active directory.\n", domain->name, 
2310                                  domain->active_directory ? "" : "NOT "));
2311
2312                         domain->can_do_ncacn_ip_tcp = domain->active_directory;
2313
2314                         domain->initialized = True;
2315
2316                         break;
2317                 }               
2318         }
2319
2320         TALLOC_FREE(mem_ctx);
2321
2322         return domain->initialized;     
2323 }
2324
2325 /******************************************************************************
2326  We can 'sense' certain things about the DC by it's replies to certain
2327  questions.
2328
2329  This tells us if this particular remote server is Active Directory, and if it
2330  is native mode.
2331 ******************************************************************************/
2332
2333 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
2334 {
2335         NTSTATUS status, result;
2336         WERROR werr;
2337         TALLOC_CTX              *mem_ctx = NULL;
2338         struct rpc_pipe_client  *cli = NULL;
2339         struct policy_handle pol;
2340         union dssetup_DsRoleInfo info;
2341         union lsa_PolicyInformation *lsa_info = NULL;
2342
2343         if (!domain->internal && !connection_ok(domain)) {
2344                 return;
2345         }
2346
2347         mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
2348                               domain->name);
2349         if (!mem_ctx) {
2350                 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
2351                 return;
2352         }
2353
2354         DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
2355
2356         if (domain->internal) {
2357                 status = wb_open_internal_pipe(mem_ctx,
2358                                                &ndr_table_dssetup,
2359                                                &cli);
2360         } else {
2361                 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2362                                                   &ndr_table_dssetup,
2363                                                   &cli);
2364         }
2365
2366         if (!NT_STATUS_IS_OK(status)) {
2367                 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2368                           "PI_DSSETUP on domain %s: (%s)\n",
2369                           domain->name, nt_errstr(status)));
2370
2371                 /* if this is just a non-AD domain we need to continue
2372                  * identifying so that we can in the end return with
2373                  * domain->initialized = True - gd */
2374
2375                 goto no_dssetup;
2376         }
2377
2378         status = dcerpc_dssetup_DsRoleGetPrimaryDomainInformation(cli->binding_handle, mem_ctx,
2379                                                                   DS_ROLE_BASIC_INFORMATION,
2380                                                                   &info,
2381                                                                   &werr);
2382         TALLOC_FREE(cli);
2383
2384         if (NT_STATUS_IS_OK(status)) {
2385                 result = werror_to_ntstatus(werr);
2386         }
2387         if (!NT_STATUS_IS_OK(status)) {
2388                 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
2389                           "on domain %s failed: (%s)\n",
2390                           domain->name, nt_errstr(status)));
2391
2392                 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
2393                  * every opcode on the DSSETUP pipe, continue with
2394                  * no_dssetup mode here as well to get domain->initialized
2395                  * set - gd */
2396
2397                 if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) {
2398                         goto no_dssetup;
2399                 }
2400
2401                 TALLOC_FREE(mem_ctx);
2402                 return;
2403         }
2404
2405         if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
2406             !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
2407                 domain->native_mode = True;
2408         } else {
2409                 domain->native_mode = False;
2410         }
2411
2412 no_dssetup:
2413         if (domain->internal) {
2414                 status = wb_open_internal_pipe(mem_ctx,
2415                                                &ndr_table_lsarpc,
2416                                                &cli);
2417         } else {
2418                 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2419                                                   &ndr_table_lsarpc, &cli);
2420         }
2421         if (!NT_STATUS_IS_OK(status)) {
2422                 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2423                           "PI_LSARPC on domain %s: (%s)\n",
2424                           domain->name, nt_errstr(status)));
2425                 TALLOC_FREE(cli);
2426                 TALLOC_FREE(mem_ctx);
2427                 return;
2428         }
2429
2430         status = rpccli_lsa_open_policy2(cli, mem_ctx, True,
2431                                          SEC_FLAG_MAXIMUM_ALLOWED, &pol);
2432
2433         if (NT_STATUS_IS_OK(status)) {
2434                 /* This particular query is exactly what Win2k clients use 
2435                    to determine that the DC is active directory */
2436                 status = dcerpc_lsa_QueryInfoPolicy2(cli->binding_handle, mem_ctx,
2437                                                      &pol,
2438                                                      LSA_POLICY_INFO_DNS,
2439                                                      &lsa_info,
2440                                                      &result);
2441         }
2442
2443         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2444                 domain->active_directory = True;
2445
2446                 if (lsa_info->dns.name.string) {
2447                         if (!strequal(domain->name, lsa_info->dns.name.string))
2448                         {
2449                                 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2450                                           "for domain %s claimed it was a DC "
2451                                           "for domain %s, refusing to "
2452                                           "initialize\n",
2453                                           domain->name,
2454                                           lsa_info->dns.name.string));
2455                                 TALLOC_FREE(cli);
2456                                 TALLOC_FREE(mem_ctx);
2457                                 return;
2458                         }
2459                         talloc_free(domain->name);
2460                         domain->name = talloc_strdup(domain,
2461                                                      lsa_info->dns.name.string);
2462                         if (domain->name == NULL) {
2463                                 goto done;
2464                         }
2465                 }
2466
2467                 if (lsa_info->dns.dns_domain.string) {
2468                         if (domain->alt_name != NULL &&
2469                             !strequal(domain->alt_name,
2470                                       lsa_info->dns.dns_domain.string))
2471                         {
2472                                 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2473                                           "for domain %s (%s) claimed it was "
2474                                           "a DC for domain %s, refusing to "
2475                                           "initialize\n",
2476                                           domain->alt_name, domain->name,
2477                                           lsa_info->dns.dns_domain.string));
2478                                 TALLOC_FREE(cli);
2479                                 TALLOC_FREE(mem_ctx);
2480                                 return;
2481                         }
2482                         talloc_free(domain->alt_name);
2483                         domain->alt_name =
2484                                 talloc_strdup(domain,
2485                                               lsa_info->dns.dns_domain.string);
2486                         if (domain->alt_name == NULL) {
2487                                 goto done;
2488                         }
2489                 }
2490
2491                 /* See if we can set some domain trust flags about
2492                    ourself */
2493
2494                 if (lsa_info->dns.dns_forest.string) {
2495                         talloc_free(domain->forest_name);
2496                         domain->forest_name =
2497                                 talloc_strdup(domain,
2498                                               lsa_info->dns.dns_forest.string);
2499                         if (domain->forest_name == NULL) {
2500                                 goto done;
2501                         }
2502
2503                         if (strequal(domain->forest_name, domain->alt_name)) {
2504                                 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
2505                         }
2506                 }
2507
2508                 if (lsa_info->dns.sid) {
2509                         if (!is_null_sid(&domain->sid) &&
2510                             !dom_sid_equal(&domain->sid,
2511                                            lsa_info->dns.sid))
2512                         {
2513                                 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2514                                           "for domain %s (%s) claimed it was "
2515                                           "a DC for domain %s, refusing to "
2516                                           "initialize\n",
2517                                           dom_sid_string(talloc_tos(),
2518                                                          &domain->sid),
2519                                           domain->name,
2520                                           dom_sid_string(talloc_tos(),
2521                                                          lsa_info->dns.sid)));
2522                                 TALLOC_FREE(cli);
2523                                 TALLOC_FREE(mem_ctx);
2524                                 return;
2525                         }
2526                         sid_copy(&domain->sid, lsa_info->dns.sid);
2527                 }
2528         } else {
2529                 domain->active_directory = False;
2530
2531                 status = rpccli_lsa_open_policy(cli, mem_ctx, True,
2532                                                 SEC_FLAG_MAXIMUM_ALLOWED,
2533                                                 &pol);
2534
2535                 if (!NT_STATUS_IS_OK(status)) {
2536                         goto done;
2537                 }
2538
2539                 status = dcerpc_lsa_QueryInfoPolicy(cli->binding_handle, mem_ctx,
2540                                                     &pol,
2541                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
2542                                                     &lsa_info,
2543                                                     &result);
2544                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2545
2546                         if (lsa_info->account_domain.name.string) {
2547                                 if (!strequal(domain->name,
2548                                         lsa_info->account_domain.name.string))
2549                                 {
2550                                         DEBUG(1,
2551                                               ("set_dc_type_and_flags_connect: "
2552                                                "DC for domain %s claimed it was"
2553                                                " a DC for domain %s, refusing "
2554                                                "to initialize\n", domain->name,
2555                                                lsa_info->
2556                                                 account_domain.name.string));
2557                                         TALLOC_FREE(cli);
2558                                         TALLOC_FREE(mem_ctx);
2559                                         return;
2560                                 }
2561                                 talloc_free(domain->name);
2562                                 domain->name =
2563                                         talloc_strdup(domain,
2564                                                       lsa_info->account_domain.name.string);
2565                         }
2566
2567                         if (lsa_info->account_domain.sid) {
2568                                 if (!is_null_sid(&domain->sid) &&
2569                                     !dom_sid_equal(&domain->sid,
2570                                                 lsa_info->account_domain.sid))
2571                                 {
2572                                         DEBUG(1,
2573                                               ("set_dc_type_and_flags_connect: "
2574                                                "DC for domain %s (%s) claimed "
2575                                                "it was a DC for domain %s, "
2576                                                "refusing to initialize\n",
2577                                                dom_sid_string(talloc_tos(),
2578                                                               &domain->sid),
2579                                                domain->name,
2580                                                dom_sid_string(talloc_tos(),
2581                                                 lsa_info->account_domain.sid)));
2582                                         TALLOC_FREE(cli);
2583                                         TALLOC_FREE(mem_ctx);
2584                                         return;
2585                                 }
2586                                 sid_copy(&domain->sid, lsa_info->account_domain.sid);
2587                         }
2588                 }
2589         }
2590 done:
2591
2592         DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
2593                   domain->name, domain->native_mode ? "" : "NOT "));
2594
2595         DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
2596                   domain->name, domain->active_directory ? "" : "NOT "));
2597
2598         domain->can_do_ncacn_ip_tcp = domain->active_directory;
2599
2600         TALLOC_FREE(cli);
2601
2602         TALLOC_FREE(mem_ctx);
2603
2604         domain->initialized = True;
2605 }
2606
2607 /**********************************************************************
2608  Set the domain_flags (trust attributes, domain operating modes, etc... 
2609 ***********************************************************************/
2610
2611 static void set_dc_type_and_flags( struct winbindd_domain *domain )
2612 {
2613         /* we always have to contact our primary domain */
2614
2615         if ( domain->primary || domain->internal) {
2616                 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
2617                           "primary or internal domain\n"));
2618                 set_dc_type_and_flags_connect( domain );
2619                 return;         
2620         }
2621
2622         /* Use our DC to get the information if possible */
2623
2624         if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
2625                 /* Otherwise, fallback to contacting the 
2626                    domain directly */
2627                 set_dc_type_and_flags_connect( domain );
2628         }
2629
2630         return;
2631 }
2632
2633
2634
2635 /**********************************************************************
2636 ***********************************************************************/
2637
2638 static NTSTATUS cm_get_schannel_creds(struct winbindd_domain *domain,
2639                                    struct netlogon_creds_cli_context **ppdc)
2640 {
2641         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2642         struct rpc_pipe_client *netlogon_pipe;
2643
2644         *ppdc = NULL;
2645
2646         if ((!IS_DC) && (!domain->primary)) {
2647                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2648         }
2649
2650         if (domain->conn.netlogon_creds != NULL) {
2651                 if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2652                         return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2653                 }
2654                 *ppdc = domain->conn.netlogon_creds;
2655                 return NT_STATUS_OK;
2656         }
2657
2658         result = cm_connect_netlogon(domain, &netlogon_pipe);
2659         if (!NT_STATUS_IS_OK(result)) {
2660                 return result;
2661         }
2662
2663         if (domain->conn.netlogon_creds == NULL) {
2664                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2665         }
2666
2667         if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2668                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2669         }
2670
2671         *ppdc = domain->conn.netlogon_creds;
2672         return NT_STATUS_OK;
2673 }
2674
2675 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2676                         bool need_rw_dc,
2677                         struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2678 {
2679         struct winbindd_cm_conn *conn;
2680         NTSTATUS status, result;
2681         struct netlogon_creds_cli_context *p_creds;
2682         struct cli_credentials *creds = NULL;
2683
2684         if (sid_check_is_our_sam(&domain->sid)) {
2685                 if (domain->rodc == false || need_rw_dc == false) {
2686                         return open_internal_samr_conn(mem_ctx, domain, cli, sam_handle);
2687                 }
2688         }
2689
2690         status = init_dc_connection_rpc(domain, need_rw_dc);
2691         if (!NT_STATUS_IS_OK(status)) {
2692                 return status;
2693         }
2694
2695         conn = &domain->conn;
2696
2697         if (rpccli_is_connected(conn->samr_pipe)) {
2698                 goto done;
2699         }
2700
2701         TALLOC_FREE(conn->samr_pipe);
2702
2703         /*
2704          * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2705          * sign and sealed pipe using the machine account password by
2706          * preference. If we can't - try schannel, if that fails, try
2707          * anonymous.
2708          */
2709
2710         result = get_trust_credentials(domain, talloc_tos(), false, &creds);
2711         if (!NT_STATUS_IS_OK(result)) {
2712                 DEBUG(10, ("cm_connect_sam: No user available for "
2713                            "domain %s, trying schannel\n", domain->name));
2714                 goto schannel;
2715         }
2716
2717         if (cli_credentials_is_anonymous(creds)) {
2718                 goto anonymous;
2719         }
2720
2721         /*
2722          * We have an authenticated connection. Use a SPNEGO
2723          * authenticated SAMR pipe with sign & seal.
2724          */
2725         status = cli_rpc_pipe_open_with_creds(conn->cli,
2726                                               &ndr_table_samr,
2727                                               NCACN_NP,
2728                                               DCERPC_AUTH_TYPE_SPNEGO,
2729                                               conn->auth_level,
2730                                               smbXcli_conn_remote_name(conn->cli->conn),
2731                                               creds,
2732                                               &conn->samr_pipe);
2733         if (!NT_STATUS_IS_OK(status)) {
2734                 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2735                           "pipe for domain %s using NTLMSSP "
2736                           "authenticated pipe: user %s. Error was "
2737                           "%s\n", domain->name,
2738                           cli_credentials_get_unparsed_name(creds, talloc_tos()),
2739                           nt_errstr(status)));
2740                 goto schannel;
2741         }
2742
2743         DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2744                   "domain %s using NTLMSSP authenticated "
2745                   "pipe: user %s\n", domain->name,
2746                   cli_credentials_get_unparsed_name(creds, talloc_tos())));
2747
2748         status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2749                                       conn->samr_pipe->desthost,
2750                                       SEC_FLAG_MAXIMUM_ALLOWED,
2751                                       &conn->sam_connect_handle,
2752                                       &result);
2753         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2754                 goto open_domain;
2755         }
2756         if (NT_STATUS_IS_OK(status)) {
2757                 status = result;
2758         }
2759
2760         DEBUG(10,("cm_connect_sam: ntlmssp-sealed dcerpc_samr_Connect2 "
2761                   "failed for domain %s, error was %s. Trying schannel\n",
2762                   domain->name, nt_errstr(status) ));
2763         TALLOC_FREE(conn->samr_pipe);
2764
2765  schannel:
2766
2767         /* Fall back to schannel if it's a W2K pre-SP1 box. */
2768
2769         status = cm_get_schannel_creds(domain, &p_creds);
2770         if (!NT_STATUS_IS_OK(status)) {
2771                 /* If this call fails - conn->cli can now be NULL ! */
2772                 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2773                            "for domain %s (error %s), trying anon\n",
2774                         domain->name,
2775                         nt_errstr(status) ));
2776                 goto anonymous;
2777         }
2778         TALLOC_FREE(creds);
2779         result = get_trust_credentials(domain, talloc_tos(), true, &creds);
2780         if (!NT_STATUS_IS_OK(result)) {
2781                 DEBUG(10, ("cm_connect_sam: No user available for "
2782                            "domain %s (error %s), trying anon\n", domain->name,
2783                            nt_errstr(result)));
2784                 goto anonymous;
2785         }
2786         status = cli_rpc_pipe_open_schannel_with_creds
2787                 (conn->cli, &ndr_table_samr, NCACN_NP,
2788                  creds, p_creds, &conn->samr_pipe);
2789
2790         if (!NT_STATUS_IS_OK(status)) {
2791                 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2792                           "domain %s using schannel. Error was %s\n",
2793                           domain->name, nt_errstr(status) ));
2794                 goto anonymous;
2795         }
2796         DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2797                   "schannel.\n", domain->name ));
2798
2799         status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2800                                       conn->samr_pipe->desthost,
2801                                       SEC_FLAG_MAXIMUM_ALLOWED,
2802                                       &conn->sam_connect_handle,
2803                                       &result);
2804         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2805                 goto open_domain;
2806         }
2807         if (NT_STATUS_IS_OK(status)) {
2808                 status = result;
2809         }
2810         DEBUG(10,("cm_connect_sam: schannel-sealed dcerpc_samr_Connect2 failed "
2811                   "for domain %s, error was %s. Trying anonymous\n",
2812                   domain->name, nt_errstr(status) ));
2813         TALLOC_FREE(conn->samr_pipe);
2814
2815  anonymous:
2816
2817         /* Finally fall back to anonymous. */
2818         if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
2819                 status = NT_STATUS_DOWNGRADE_DETECTED;
2820                 DEBUG(1, ("Unwilling to make SAMR connection to domain %s"
2821                           "without connection level security, "
2822                           "must set 'winbind sealed pipes = false' and "
2823                           "'require strong key = false' to proceed: %s\n",
2824                           domain->name, nt_errstr(status)));
2825                 goto done;
2826         }
2827         status = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr,
2828                                           &conn->samr_pipe);
2829
2830         if (!NT_STATUS_IS_OK(status)) {
2831                 goto done;
2832         }
2833
2834         status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2835                                       conn->samr_pipe->desthost,
2836                                       SEC_FLAG_MAXIMUM_ALLOWED,
2837                                       &conn->sam_connect_handle,
2838                                       &result);
2839         if (!NT_STATUS_IS_OK(status)) {
2840                 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2841                           "for domain %s Error was %s\n",
2842                           domain->name, nt_errstr(status) ));
2843                 goto done;
2844         }
2845         if (!NT_STATUS_IS_OK(result)) {
2846                 status = result;
2847                 DEBUG(10,("cm_connect_sam: dcerpc_samr_Connect2 failed "
2848                           "for domain %s Error was %s\n",
2849                           domain->name, nt_errstr(result)));
2850                 goto done;
2851         }
2852
2853  open_domain:
2854         status = dcerpc_samr_OpenDomain(conn->samr_pipe->binding_handle,
2855                                         mem_ctx,
2856                                         &conn->sam_connect_handle,
2857                                         SEC_FLAG_MAXIMUM_ALLOWED,
2858                                         &domain->sid,
2859                                         &conn->sam_domain_handle,
2860                                         &result);
2861         if (!NT_STATUS_IS_OK(status)) {
2862                 goto done;
2863         }
2864
2865         status = result;
2866  done:
2867
2868         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
2869                 /*
2870                  * if we got access denied, we might just have no access rights
2871                  * to talk to the remote samr server server (e.g. when we are a
2872                  * PDC and we are connecting a w2k8 pdc via an interdomain
2873                  * trust). In that case do not invalidate the whole connection
2874                  * stack
2875                  */
2876                 TALLOC_FREE(conn->samr_pipe);
2877                 ZERO_STRUCT(conn->sam_domain_handle);
2878                 return status;
2879         } else if (!NT_STATUS_IS_OK(status)) {
2880                 invalidate_cm_connection(domain);
2881                 return status;
2882         }
2883
2884         *cli = conn->samr_pipe;
2885         *sam_handle = conn->sam_domain_handle;
2886         return status;
2887 }
2888
2889 /**********************************************************************
2890  open an schanneld ncacn_ip_tcp connection to LSA
2891 ***********************************************************************/
2892
2893 static NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2894                                    TALLOC_CTX *mem_ctx,
2895                                    struct rpc_pipe_client **cli)
2896 {
2897         struct winbindd_cm_conn *conn;
2898         struct netlogon_creds_cli_context *p_creds = NULL;
2899         struct cli_credentials *creds = NULL;
2900         NTSTATUS status;
2901
2902         DEBUG(10,("cm_connect_lsa_tcp\n"));
2903
2904         status = init_dc_connection_rpc(domain, false);
2905         if (!NT_STATUS_IS_OK(status)) {
2906                 return status;
2907         }
2908
2909         conn = &domain->conn;
2910
2911         if (conn->lsa_pipe_tcp &&
2912             conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2913             conn->lsa_pipe_tcp->auth->auth_level >= DCERPC_AUTH_LEVEL_INTEGRITY &&
2914             rpccli_is_connected(conn->lsa_pipe_tcp)) {
2915                 goto done;
2916         }
2917
2918         TALLOC_FREE(conn->lsa_pipe_tcp);
2919
2920         status = cm_get_schannel_creds(domain, &p_creds);
2921         if (!NT_STATUS_IS_OK(status)) {
2922                 goto done;
2923         }
2924
2925         status = get_trust_credentials(domain, talloc_tos(), true, &creds);
2926         if (!NT_STATUS_IS_OK(status)) {
2927                 goto done;
2928         }
2929
2930         status = cli_rpc_pipe_open_schannel_with_creds(conn->cli,
2931                                                        &ndr_table_lsarpc,
2932                                                        NCACN_IP_TCP,
2933                                                        creds,
2934                                                        p_creds,
2935                                                        &conn->lsa_pipe_tcp);
2936         if (!NT_STATUS_IS_OK(status)) {
2937                 DEBUG(10,("cli_rpc_pipe_open_schannel_with_key failed: %s\n",
2938                         nt_errstr(status)));
2939                 goto done;
2940         }
2941
2942  done:
2943         if (!NT_STATUS_IS_OK(status)) {
2944                 TALLOC_FREE(conn->lsa_pipe_tcp);
2945                 return status;
2946         }
2947
2948         *cli = conn->lsa_pipe_tcp;
2949
2950         return status;
2951 }
2952
2953 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2954                         struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2955 {
2956         struct winbindd_cm_conn *conn;
2957         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2958         struct netlogon_creds_cli_context *p_creds;
2959         struct cli_credentials *creds = NULL;
2960
2961         result = init_dc_connection_rpc(domain, false);
2962         if (!NT_STATUS_IS_OK(result))
2963                 return result;
2964
2965         conn = &domain->conn;
2966
2967         if (rpccli_is_connected(conn->lsa_pipe)) {
2968                 goto done;
2969         }
2970
2971         TALLOC_FREE(conn->lsa_pipe);
2972
2973         result = get_trust_credentials(domain, talloc_tos(), false, &creds);
2974         if (!NT_STATUS_IS_OK(result)) {
2975                 DEBUG(10, ("cm_connect_lsa: No user available for "
2976                            "domain %s, trying schannel\n", domain->name));
2977                 goto schannel;
2978         }
2979
2980         if (cli_credentials_is_anonymous(creds)) {
2981                 goto anonymous;
2982         }
2983
2984         /*
2985          * We have an authenticated connection. Use a SPNEGO
2986          * authenticated LSA pipe with sign & seal.
2987          */
2988         result = cli_rpc_pipe_open_with_creds
2989                 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
2990                  DCERPC_AUTH_TYPE_SPNEGO,
2991                  conn->auth_level,
2992                  smbXcli_conn_remote_name(conn->cli->conn),
2993                  creds,
2994                  &conn->lsa_pipe);
2995         if (!NT_STATUS_IS_OK(result)) {
2996                 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2997                           "domain %s using NTLMSSP authenticated pipe: user "
2998                           "%s. Error was %s. Trying schannel.\n",
2999                           domain->name,
3000                           cli_credentials_get_unparsed_name(creds, talloc_tos()),
3001                           nt_errstr(result)));
3002                 goto schannel;
3003         }
3004
3005         DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
3006                   "NTLMSSP authenticated pipe: user %s\n",
3007                   domain->name, cli_credentials_get_unparsed_name(creds, talloc_tos())));
3008
3009         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3010                                         SEC_FLAG_MAXIMUM_ALLOWED,
3011                                         &conn->lsa_policy);
3012         if (NT_STATUS_IS_OK(result)) {
3013                 goto done;
3014         }
3015
3016         DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
3017                   "schannel\n"));
3018
3019         TALLOC_FREE(conn->lsa_pipe);
3020
3021  schannel:
3022
3023         /* Fall back to schannel if it's a W2K pre-SP1 box. */
3024
3025         result = cm_get_schannel_creds(domain, &p_creds);
3026         if (!NT_STATUS_IS_OK(result)) {
3027                 /* If this call fails - conn->cli can now be NULL ! */
3028                 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
3029                            "for domain %s (error %s), trying anon\n",
3030                         domain->name,
3031                         nt_errstr(result) ));
3032                 goto anonymous;
3033         }
3034
3035         TALLOC_FREE(creds);
3036         result = get_trust_credentials(domain, talloc_tos(), true, &creds);
3037         if (!NT_STATUS_IS_OK(result)) {
3038                 DEBUG(10, ("cm_connect_lsa: No user available for "
3039                            "domain %s (error %s), trying anon\n", domain->name,
3040                            nt_errstr(result)));
3041                 goto anonymous;
3042         }
3043         result = cli_rpc_pipe_open_schannel_with_creds
3044                 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
3045                  creds, p_creds, &conn->lsa_pipe);
3046
3047         if (!NT_STATUS_IS_OK(result)) {
3048                 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
3049                           "domain %s using schannel. Error was %s\n",
3050                           domain->name, nt_errstr(result) ));
3051                 goto anonymous;
3052         }
3053         DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
3054                   "schannel.\n", domain->name ));
3055
3056         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3057                                         SEC_FLAG_MAXIMUM_ALLOWED,
3058                                         &conn->lsa_policy);
3059         if (NT_STATUS_IS_OK(result)) {
3060                 goto done;
3061         }
3062
3063         DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
3064                   "anonymous\n"));
3065
3066         TALLOC_FREE(conn->lsa_pipe);
3067
3068  anonymous:
3069
3070         if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3071                 result = NT_STATUS_DOWNGRADE_DETECTED;
3072                 DEBUG(1, ("Unwilling to make LSA connection to domain %s"
3073                           "without connection level security, "
3074                           "must set 'winbind sealed pipes = false' and "
3075                           "'require strong key = false' to proceed: %s\n",
3076                           domain->name, nt_errstr(result)));
3077                 goto done;
3078         }
3079
3080         result = cli_rpc_pipe_open_noauth(conn->cli,
3081                                           &ndr_table_lsarpc,
3082                                           &conn->lsa_pipe);
3083         if (!NT_STATUS_IS_OK(result)) {
3084                 goto done;
3085         }
3086
3087         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3088                                         SEC_FLAG_MAXIMUM_ALLOWED,
3089                                         &conn->lsa_policy);
3090  done:
3091         if (!NT_STATUS_IS_OK(result)) {
3092                 invalidate_cm_connection(domain);
3093                 return result;
3094         }
3095
3096         *cli = conn->lsa_pipe;
3097         *lsa_policy = conn->lsa_policy;
3098         return result;
3099 }
3100
3101 /****************************************************************************
3102 Open a LSA connection to a DC, suiteable for LSA lookup calls.
3103 ****************************************************************************/
3104
3105 NTSTATUS cm_connect_lsat(struct winbindd_domain *domain,
3106                          TALLOC_CTX *mem_ctx,
3107                          struct rpc_pipe_client **cli,
3108                          struct policy_handle *lsa_policy)
3109 {
3110         NTSTATUS status;
3111
3112         if (domain->can_do_ncacn_ip_tcp) {
3113                 status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3114                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3115                     NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3116                     NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3117                         invalidate_cm_connection(domain);
3118                         status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3119                 }
3120                 if (NT_STATUS_IS_OK(status)) {
3121                         return status;
3122                 }
3123
3124                 /*
3125                  * we tried twice to connect via ncan_ip_tcp and schannel and
3126                  * failed - maybe it is a trusted domain we can't connect to ?
3127                  * do not try tcp next time - gd
3128                  *
3129                  * This also prevents NETLOGON over TCP
3130                  */
3131                 domain->can_do_ncacn_ip_tcp = false;
3132         }
3133
3134         status = cm_connect_lsa(domain, mem_ctx, cli, lsa_policy);
3135
3136         return status;
3137 }
3138
3139 /****************************************************************************
3140  Open the netlogon pipe to this DC. Use schannel if specified in client conf.
3141  session key stored in conn->netlogon_pipe->dc->sess_key.
3142 ****************************************************************************/
3143
3144 static NTSTATUS cm_connect_netlogon_transport(struct winbindd_domain *domain,
3145                                               enum dcerpc_transport_t transport,
3146                                               struct rpc_pipe_client **cli)
3147 {
3148         struct messaging_context *msg_ctx = winbind_messaging_context();
3149         struct winbindd_cm_conn *conn;
3150         NTSTATUS result;
3151         enum netr_SchannelType sec_chan_type;
3152         struct netlogon_creds_CredentialState *netlogon_creds = NULL;
3153         struct cli_credentials *creds = NULL;
3154
3155         *cli = NULL;
3156
3157         result = init_dc_connection_rpc(domain, domain->rodc);
3158         if (!NT_STATUS_IS_OK(result)) {
3159                 return result;
3160         }
3161
3162         conn = &domain->conn;
3163
3164         if (rpccli_is_connected(conn->netlogon_pipe)) {
3165                 *cli = conn->netlogon_pipe;
3166                 return NT_STATUS_OK;
3167         }
3168
3169         TALLOC_FREE(conn->netlogon_pipe);
3170         conn->netlogon_flags = 0;
3171         TALLOC_FREE(conn->netlogon_creds);
3172
3173         result = get_trust_credentials(domain, talloc_tos(), true, &creds);
3174         if (!NT_STATUS_IS_OK(result)) {
3175                 DEBUG(10, ("cm_connect_sam: No user available for "
3176                            "domain %s when trying schannel\n", domain->name));
3177                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3178         }
3179
3180         if (cli_credentials_is_anonymous(creds)) {
3181                 DEBUG(1, ("get_trust_credential only gave anonymous for %s, unable to make get NETLOGON credentials\n",
3182                           domain->name));
3183                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3184         }
3185
3186         sec_chan_type = cli_credentials_get_secure_channel_type(creds);
3187         if (sec_chan_type == SEC_CHAN_NULL) {
3188                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3189                 goto no_schannel;
3190         }
3191
3192         result = rpccli_create_netlogon_creds_with_creds(creds,
3193                                                          domain->dcname,
3194                                                          msg_ctx,
3195                                                          domain,
3196                                                          &conn->netlogon_creds);
3197         if (!NT_STATUS_IS_OK(result)) {
3198                 DEBUG(1, ("rpccli_create_netlogon_creds failed for %s, "
3199                           "unable to create NETLOGON credentials: %s\n",
3200                           domain->name, nt_errstr(result)));
3201                 return result;
3202         }
3203
3204         result = rpccli_setup_netlogon_creds_with_creds(conn->cli, transport,
3205                                                 conn->netlogon_creds,
3206                                                 conn->netlogon_force_reauth,
3207                                                 creds);
3208         conn->netlogon_force_reauth = false;
3209         if (!NT_STATUS_IS_OK(result)) {
3210                 DEBUG(1, ("rpccli_setup_netlogon_creds failed for %s, "
3211                           "unable to setup NETLOGON credentials: %s\n",
3212                           domain->name, nt_errstr(result)));
3213                 return result;
3214         }
3215
3216         result = netlogon_creds_cli_get(conn->netlogon_creds,
3217                                         talloc_tos(),
3218                                         &netlogon_creds);
3219         if (!NT_STATUS_IS_OK(result)) {
3220                 DEBUG(1, ("netlogon_creds_cli_get failed for %s, "
3221                           "unable to get NETLOGON credentials: %s\n",
3222                           domain->name, nt_errstr(result)));
3223                 return result;
3224         }
3225         conn->netlogon_flags = netlogon_creds->negotiate_flags;
3226         TALLOC_FREE(netlogon_creds);
3227
3228  no_schannel:
3229         if (!(conn->netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
3230                 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3231                         result = NT_STATUS_DOWNGRADE_DETECTED;
3232                         DEBUG(1, ("Unwilling to make connection to domain %s"
3233                                   "without connection level security, "
3234                                   "must set 'winbind sealed pipes = false' and "
3235                                   "'require strong key = false' to proceed: %s\n",
3236                                   domain->name, nt_errstr(result)));
3237                         invalidate_cm_connection(domain);
3238                         return result;
3239                 }
3240                 result = cli_rpc_pipe_open_noauth_transport(conn->cli,
3241                                                             transport,
3242                                                             &ndr_table_netlogon,
3243                                                             &conn->netlogon_pipe);
3244                 if (!NT_STATUS_IS_OK(result)) {
3245                         invalidate_cm_connection(domain);
3246                         return result;
3247                 }
3248
3249                 *cli = conn->netlogon_pipe;
3250                 return NT_STATUS_OK;
3251         }
3252
3253         /* Using the credentials from the first pipe, open a signed and sealed
3254            second netlogon pipe. The session key is stored in the schannel
3255            part of the new pipe auth struct.
3256         */
3257
3258         result = cli_rpc_pipe_open_schannel_with_creds(
3259                 conn->cli, &ndr_table_netlogon, transport,
3260                 creds,
3261                 conn->netlogon_creds,
3262                 &conn->netlogon_pipe);
3263         if (!NT_STATUS_IS_OK(result)) {
3264                 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
3265                           "was %s\n", nt_errstr(result)));
3266
3267                 invalidate_cm_connection(domain);
3268                 return result;
3269         }
3270
3271         *cli = conn->netlogon_pipe;
3272         return NT_STATUS_OK;
3273 }
3274
3275 /****************************************************************************
3276 Open a LSA connection to a DC, suiteable for LSA lookup calls.
3277 ****************************************************************************/
3278
3279 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
3280                              struct rpc_pipe_client **cli)
3281 {
3282         NTSTATUS status;
3283
3284         status = init_dc_connection_rpc(domain, domain->rodc);
3285         if (!NT_STATUS_IS_OK(status)) {
3286                 return status;
3287         }
3288
3289         if (domain->active_directory && domain->can_do_ncacn_ip_tcp) {
3290                 status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3291                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3292                     NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3293                     NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3294                         invalidate_cm_connection(domain);
3295                         status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3296                 }
3297                 if (NT_STATUS_IS_OK(status)) {
3298                         return status;
3299                 }
3300
3301                 /*
3302                  * we tried twice to connect via ncan_ip_tcp and schannel and
3303                  * failed - maybe it is a trusted domain we can't connect to ?
3304                  * do not try tcp next time - gd
3305                  *
3306                  * This also prevents LSA over TCP
3307                  */
3308                 domain->can_do_ncacn_ip_tcp = false;
3309         }
3310
3311         status = cm_connect_netlogon_transport(domain, NCACN_NP, cli);
3312
3313         return status;
3314 }
3315
3316 void winbind_msg_ip_dropped(struct messaging_context *msg_ctx,
3317                             void *private_data,
3318                             uint32_t msg_type,
3319                             struct server_id server_id,
3320                             DATA_BLOB *data)
3321 {
3322         struct winbindd_domain *domain;
3323         char *freeit = NULL;
3324         char *addr;
3325
3326         if ((data == NULL)
3327             || (data->data == NULL)
3328             || (data->length == 0)
3329             || (data->data[data->length-1] != '\0')) {
3330                 DEBUG(1, ("invalid msg_ip_dropped message: not a valid "
3331                           "string\n"));
3332                 return;
3333         }
3334
3335         addr = (char *)data->data;
3336         DEBUG(10, ("IP %s dropped\n", addr));
3337
3338         if (!is_ipaddress(addr)) {
3339                 char *slash;
3340                 /*
3341                  * Some code sends us ip addresses with the /netmask
3342                  * suffix
3343                  */
3344                 slash = strchr(addr, '/');
3345                 if (slash == NULL) {
3346                         DEBUG(1, ("invalid msg_ip_dropped message: %s",
3347                                   addr));
3348                         return;
3349                 }
3350                 freeit = talloc_strndup(talloc_tos(), addr, slash-addr);
3351                 if (freeit == NULL) {
3352                         DEBUG(1, ("talloc failed\n"));
3353                         return;
3354                 }
3355                 addr = freeit;
3356                 DEBUG(10, ("Stripped /netmask to IP %s\n", addr));
3357         }
3358
3359         for (domain = domain_list(); domain != NULL; domain = domain->next) {
3360                 char sockaddr[INET6_ADDRSTRLEN];
3361
3362                 if (!cli_state_is_connected(domain->conn.cli)) {
3363                         continue;
3364                 }
3365
3366                 print_sockaddr(sockaddr, sizeof(sockaddr),
3367                                smbXcli_conn_local_sockaddr(domain->conn.cli->conn));
3368
3369                 if (strequal(sockaddr, addr)) {
3370                         smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
3371                 }
3372         }
3373         TALLOC_FREE(freeit);
3374 }