s3:winbindd: fix anon fallback in cm_prepare_connection()
[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
906         /* If we are a DC and this is not our own domain */
907
908         if (IS_DC && netlogon) {
909                 creds_domain = domain;
910         } else {
911                 creds_domain = find_our_domain();
912                 if (creds_domain == NULL) {
913                         return NT_STATUS_INVALID_SERVER_STATE;
914                 }
915         }
916
917         status = pdb_get_trust_credentials(creds_domain->name,
918                                            creds_domain->alt_name,
919                                            mem_ctx,
920                                            &creds);
921         if (!NT_STATUS_IS_OK(status)) {
922                 goto ipc_fallback;
923         }
924
925         if (lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC) {
926                 cli_credentials_set_kerberos_state(creds,
927                                                    CRED_MUST_USE_KERBEROS);
928         }
929
930         if (domain->primary && lp_security() == SEC_ADS) {
931                 cli_credentials_set_kerberos_state(creds,
932                                                    CRED_AUTO_USE_KERBEROS);
933         } else if (!domain->active_directory) {
934                 cli_credentials_set_kerberos_state(creds,
935                                                    CRED_DONT_USE_KERBEROS);
936         }
937
938         if (creds_domain != domain) {
939                 /*
940                  * We can only use schannel against a direct trust
941                  */
942                 cli_credentials_set_secure_channel_type(creds,
943                                                         SEC_CHAN_NULL);
944         }
945
946         *_creds = creds;
947         return NT_STATUS_OK;
948
949  ipc_fallback:
950         if (netlogon) {
951                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
952         }
953
954         status = cm_get_ipc_credentials(mem_ctx, &creds);
955         if (!NT_STATUS_IS_OK(status)) {
956                 return status;
957         }
958
959         *_creds = creds;
960         return NT_STATUS_OK;
961 }
962
963 /************************************************************************
964  Given a fd with a just-connected TCP connection to a DC, open a connection
965  to the pipe.
966 ************************************************************************/
967
968 static NTSTATUS cm_prepare_connection(struct winbindd_domain *domain,
969                                       const int sockfd,
970                                       const char *controller,
971                                       struct cli_state **cli,
972                                       bool *retry)
973 {
974         bool try_ipc_auth = false;
975         const char *machine_password = NULL;
976         const char *machine_krb5_principal = NULL;
977         const char *machine_account = NULL;
978         const char *machine_domain = NULL;
979         int flags = 0;
980         struct cli_credentials *creds = NULL;
981         enum credentials_use_kerberos krb5_state;
982
983         struct named_mutex *mutex;
984
985         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
986
987         enum smb_signing_setting smb_sign_client_connections = lp_client_signing();
988
989         if (smb_sign_client_connections == SMB_SIGNING_DEFAULT) {
990                 /*
991                  * If we are connecting to our own AD domain, require
992                  * smb signing to disrupt MITM attacks
993                  */
994                 if (domain->primary && lp_security() == SEC_ADS) {
995                         smb_sign_client_connections = SMB_SIGNING_REQUIRED;
996                 /*
997                  * If we are in or are an AD domain and connecting to another
998                  * AD domain in our forest
999                  * then require smb signing to disrupt MITM attacks
1000                  */
1001                 } else if ((lp_security() == SEC_ADS ||
1002                             lp_server_role() == ROLE_ACTIVE_DIRECTORY_DC)
1003                            && domain->active_directory
1004                            && (domain->domain_trust_attribs
1005                                & LSA_TRUST_ATTRIBUTE_WITHIN_FOREST)) {
1006                         smb_sign_client_connections = SMB_SIGNING_REQUIRED;
1007                 }
1008         }
1009
1010         DEBUG(10,("cm_prepare_connection: connecting to DC %s for domain %s\n",
1011                 controller, domain->name ));
1012
1013         *retry = True;
1014
1015         mutex = grab_named_mutex(talloc_tos(), controller,
1016                                  WINBIND_SERVER_MUTEX_WAIT_TIME);
1017         if (mutex == NULL) {
1018                 close(sockfd);
1019                 DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
1020                          controller));
1021                 result = NT_STATUS_POSSIBLE_DEADLOCK;
1022                 goto done;
1023         }
1024
1025         flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1026
1027         *cli = cli_state_create(NULL, sockfd,
1028                                 controller, domain->alt_name,
1029                                 smb_sign_client_connections, flags);
1030         if (*cli == NULL) {
1031                 close(sockfd);
1032                 DEBUG(1, ("Could not cli_initialize\n"));
1033                 result = NT_STATUS_NO_MEMORY;
1034                 goto done;
1035         }
1036
1037         cli_set_timeout(*cli, 10000); /* 10 seconds */
1038
1039         result = smbXcli_negprot((*cli)->conn, (*cli)->timeout,
1040                                  lp_client_min_protocol(),
1041                                  lp_winbindd_max_protocol());
1042
1043         if (!NT_STATUS_IS_OK(result)) {
1044                 DEBUG(1, ("cli_negprot failed: %s\n", nt_errstr(result)));
1045                 goto done;
1046         }
1047
1048         if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_NT1 &&
1049             smb1cli_conn_capabilities((*cli)->conn) & CAP_EXTENDED_SECURITY) {
1050                 try_ipc_auth = true;
1051         } else if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1052                 try_ipc_auth = true;
1053         } else if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1054                 /*
1055                  * If we are forcing on SMB signing, then we must
1056                  * require authentication unless this is a one-way
1057                  * trust, and we have no stored user/password
1058                  */
1059                 try_ipc_auth = true;
1060         }
1061
1062         if (try_ipc_auth) {
1063                 result = get_trust_credentials(domain, talloc_tos(), false, &creds);
1064                 if (!NT_STATUS_IS_OK(result)) {
1065                         DEBUG(1, ("get_trust_credentials(%s) failed: %s\n",
1066                                   domain->name, nt_errstr(result)));
1067                         goto done;
1068                 }
1069         } else {
1070                 /*
1071                  * Without SPNEGO or NTLMSSP (perhaps via SMB2) we
1072                  * would try and authentication with our machine
1073                  * account password and fail.  This is very rare in
1074                  * the modern world however
1075                  */
1076                 creds = cli_credentials_init_anon(talloc_tos());
1077                 if (creds == NULL) {
1078                         result = NT_STATUS_NO_MEMORY;
1079                         DEBUG(1, ("cli_credentials_init_anon(%s) failed: %s\n",
1080                                   domain->name, nt_errstr(result)));
1081                         goto done;
1082                 }
1083         }
1084
1085         krb5_state = cli_credentials_get_kerberos_state(creds);
1086
1087         machine_krb5_principal = cli_credentials_get_principal(creds,
1088                                                         talloc_tos());
1089         if (machine_krb5_principal == NULL) {
1090                 krb5_state = CRED_DONT_USE_KERBEROS;
1091         }
1092
1093         machine_account = cli_credentials_get_username(creds);
1094         machine_password = cli_credentials_get_password(creds);
1095         machine_domain = cli_credentials_get_domain(creds);
1096
1097         if (krb5_state != CRED_DONT_USE_KERBEROS) {
1098
1099                 /* Try a krb5 session */
1100
1101                 (*cli)->use_kerberos = True;
1102                 DEBUG(5, ("connecting to %s from %s with kerberos principal "
1103                           "[%s] and realm [%s]\n", controller, lp_netbios_name(),
1104                           machine_krb5_principal, domain->alt_name));
1105
1106                 winbindd_set_locator_kdc_envs(domain);
1107
1108                 result = cli_session_setup(*cli,
1109                                            machine_krb5_principal,
1110                                            machine_password,
1111                                            strlen(machine_password)+1,
1112                                            machine_password,
1113                                            strlen(machine_password)+1,
1114                                            machine_domain);
1115
1116                 if (NT_STATUS_IS_OK(result)) {
1117                         goto session_setup_done;
1118                 }
1119
1120                 DEBUG(4,("failed kerberos session setup with %s\n",
1121                          nt_errstr(result)));
1122         }
1123
1124         if (krb5_state != CRED_MUST_USE_KERBEROS) {
1125                 /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the machine account. */
1126                 (*cli)->use_kerberos = False;
1127
1128                 DEBUG(5, ("connecting to %s from %s using NTLMSSP with username "
1129                           "[%s]\\[%s]\n",  controller, lp_netbios_name(),
1130                           machine_domain, machine_account));
1131
1132                 result = cli_session_setup(*cli,
1133                                            machine_account,
1134                                            machine_password,
1135                                            strlen(machine_password)+1,
1136                                            machine_password,
1137                                            strlen(machine_password)+1,
1138                                            machine_domain);
1139         }
1140
1141         if (NT_STATUS_IS_OK(result)) {
1142                 goto session_setup_done;
1143         }
1144
1145         /*
1146          * If we are not going to validiate the conneciton
1147          * with SMB signing, then allow us to fall back to
1148          * anonymous
1149          */
1150         if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1151             || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1152             || NT_STATUS_EQUAL(result, NT_STATUS_INVALID_ACCOUNT_NAME)
1153             || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1154         {
1155                 if (cli_credentials_is_anonymous(creds)) {
1156                         goto done;
1157                 }
1158
1159                 if (!cm_is_ipc_credentials(creds)) {
1160                         goto ipc_fallback;
1161                 }
1162
1163                 if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1164                         goto done;
1165                 }
1166
1167                 goto anon_fallback;
1168         }
1169
1170         DEBUG(4, ("authenticated session setup failed with %s\n",
1171                 nt_errstr(result)));
1172
1173         goto done;
1174
1175  ipc_fallback:
1176         result = cm_get_ipc_credentials(talloc_tos(), &creds);
1177         if (!NT_STATUS_IS_OK(result)) {
1178                 goto done;
1179         }
1180
1181         if (cli_credentials_is_anonymous(creds)) {
1182                 TALLOC_FREE(creds);
1183                 goto anon_fallback;
1184         }
1185
1186         machine_account = cli_credentials_get_username(creds);
1187         machine_password = cli_credentials_get_password(creds);
1188         machine_domain = cli_credentials_get_domain(creds);
1189
1190         /* Fall back to non-kerberos session setup using NTLMSSP SPNEGO with the ipc creds. */
1191         (*cli)->use_kerberos = False;
1192
1193         DEBUG(5, ("connecting to %s from %s using NTLMSSP with username "
1194                   "[%s]\\[%s]\n",  controller, lp_netbios_name(),
1195                   machine_domain, machine_account));
1196
1197         result = cli_session_setup(*cli,
1198                                    machine_account,
1199                                    machine_password,
1200                                    strlen(machine_password)+1,
1201                                    machine_password,
1202                                    strlen(machine_password)+1,
1203                                    machine_domain);
1204
1205         if (NT_STATUS_IS_OK(result)) {
1206                 goto session_setup_done;
1207         }
1208
1209         /*
1210          * If we are not going to validiate the conneciton
1211          * with SMB signing, then allow us to fall back to
1212          * anonymous
1213          */
1214         if (NT_STATUS_EQUAL(result, NT_STATUS_NOLOGON_WORKSTATION_TRUST_ACCOUNT)
1215             || NT_STATUS_EQUAL(result, NT_STATUS_TRUSTED_DOMAIN_FAILURE)
1216             || NT_STATUS_EQUAL(result, NT_STATUS_LOGON_FAILURE))
1217         {
1218                 goto anon_fallback;
1219         }
1220
1221         DEBUG(4, ("authenticated session setup failed with %s\n",
1222                 nt_errstr(result)));
1223
1224         goto done;
1225
1226  anon_fallback:
1227
1228         if (smb_sign_client_connections == SMB_SIGNING_REQUIRED) {
1229                 goto done;
1230         }
1231
1232         /* Fall back to anonymous connection, this might fail later */
1233         DEBUG(10,("cm_prepare_connection: falling back to anonymous "
1234                 "connection for DC %s\n",
1235                 controller ));
1236
1237         (*cli)->use_kerberos = False;
1238
1239         result = cli_session_setup(*cli, "", "", 0, "", 0, "");
1240         if (NT_STATUS_IS_OK(result)) {
1241                 DEBUG(5, ("Connected anonymously\n"));
1242                 goto session_setup_done;
1243         }
1244
1245         /* We can't session setup */
1246         goto done;
1247
1248  session_setup_done:
1249
1250         /*
1251          * This should be a short term hack until
1252          * dynamic re-authentication is implemented.
1253          *
1254          * See Bug 9175 - winbindd doesn't recover from
1255          * NT_STATUS_NETWORK_SESSION_EXPIRED
1256          */
1257         if (smbXcli_conn_protocol((*cli)->conn) >= PROTOCOL_SMB2_02) {
1258                 smbXcli_session_set_disconnect_expired((*cli)->smb2.session);
1259         }
1260
1261         result = cli_tree_connect(*cli, "IPC$", "IPC", "", 0);
1262
1263         if (!NT_STATUS_IS_OK(result)) {
1264                 DEBUG(1,("failed tcon_X with %s\n", nt_errstr(result)));
1265                 goto done;
1266         }
1267
1268         /* cache the server name for later connections */
1269
1270         saf_store(domain->name, controller);
1271         if (domain->alt_name && (*cli)->use_kerberos) {
1272                 saf_store(domain->alt_name, controller);
1273         }
1274
1275         winbindd_set_locator_kdc_envs(domain);
1276
1277         TALLOC_FREE(mutex);
1278         *retry = False;
1279
1280         result = NT_STATUS_OK;
1281
1282  done:
1283         TALLOC_FREE(mutex);
1284
1285         if (!NT_STATUS_IS_OK(result)) {
1286                 winbind_add_failed_connection_entry(domain, controller, result);
1287                 if ((*cli) != NULL) {
1288                         cli_shutdown(*cli);
1289                         *cli = NULL;
1290                 }
1291         }
1292
1293         return result;
1294 }
1295
1296 /*******************************************************************
1297  Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
1298  array.
1299
1300  Keeps the list unique by not adding duplicate entries.
1301
1302  @param[in] mem_ctx talloc memory context to allocate from
1303  @param[in] domain_name domain of the DC
1304  @param[in] dcname name of the DC to add to the list
1305  @param[in] pss Internet address and port pair to add to the list
1306  @param[in,out] dcs array of dc_name_ip structures to add to
1307  @param[in,out] num_dcs number of dcs returned in the dcs array
1308  @return true if the list was added to, false otherwise
1309 *******************************************************************/
1310
1311 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
1312                               const char *dcname, struct sockaddr_storage *pss,
1313                               struct dc_name_ip **dcs, int *num)
1314 {
1315         int i = 0;
1316
1317         if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
1318                 DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
1319                 return False;
1320         }
1321
1322         /* Make sure there's no duplicates in the list */
1323         for (i=0; i<*num; i++)
1324                 if (sockaddr_equal(
1325                             (struct sockaddr *)(void *)&(*dcs)[i].ss,
1326                             (struct sockaddr *)(void *)pss))
1327                         return False;
1328
1329         *dcs = talloc_realloc(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
1330
1331         if (*dcs == NULL)
1332                 return False;
1333
1334         fstrcpy((*dcs)[*num].name, dcname);
1335         (*dcs)[*num].ss = *pss;
1336         *num += 1;
1337         return True;
1338 }
1339
1340 static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
1341                                   struct sockaddr_storage *pss, uint16 port,
1342                                   struct sockaddr_storage **addrs, int *num)
1343 {
1344         *addrs = talloc_realloc(mem_ctx, *addrs, struct sockaddr_storage, (*num)+1);
1345
1346         if (*addrs == NULL) {
1347                 *num = 0;
1348                 return False;
1349         }
1350
1351         (*addrs)[*num] = *pss;
1352         set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
1353
1354         *num += 1;
1355         return True;
1356 }
1357
1358 /*******************************************************************
1359  convert an ip to a name
1360 *******************************************************************/
1361
1362 static bool dcip_to_name(TALLOC_CTX *mem_ctx,
1363                 const struct winbindd_domain *domain,
1364                 struct sockaddr_storage *pss,
1365                 char **name)
1366 {
1367         struct ip_service ip_list;
1368         uint32_t nt_version = NETLOGON_NT_VERSION_1;
1369         NTSTATUS status;
1370         const char *dc_name;
1371         fstring nbtname;
1372
1373         ip_list.ss = *pss;
1374         ip_list.port = 0;
1375
1376 #ifdef HAVE_ADS
1377         /* For active directory servers, try to get the ldap server name.
1378            None of these failures should be considered critical for now */
1379
1380         if ((lp_security() == SEC_ADS) && (domain->alt_name != NULL)) {
1381                 ADS_STRUCT *ads;
1382                 ADS_STATUS ads_status;
1383                 char addr[INET6_ADDRSTRLEN];
1384
1385                 print_sockaddr(addr, sizeof(addr), pss);
1386
1387                 ads = ads_init(domain->alt_name, domain->name, addr);
1388                 ads->auth.flags |= ADS_AUTH_NO_BIND;
1389
1390                 ads_status = ads_connect(ads);
1391                 if (ADS_ERR_OK(ads_status)) {
1392                         /* We got a cldap packet. */
1393                         *name = talloc_strdup(mem_ctx,
1394                                              ads->config.ldap_server_name);
1395                         if (*name == NULL) {
1396                                 return false;
1397                         }
1398                         namecache_store(*name, 0x20, 1, &ip_list);
1399
1400                         DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
1401
1402                         if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
1403                                 if (ads_closest_dc(ads)) {
1404                                         char *sitename = sitename_fetch(mem_ctx, ads->config.realm);
1405
1406                                         /* We're going to use this KDC for this realm/domain.
1407                                            If we are using sites, then force the krb5 libs
1408                                            to use this KDC. */
1409
1410                                         create_local_private_krb5_conf_for_domain(domain->alt_name,
1411                                                                         domain->name,
1412                                                                         sitename,
1413                                                                         pss);
1414
1415                                         TALLOC_FREE(sitename);
1416                                 } else {
1417                                         /* use an off site KDC */
1418                                         create_local_private_krb5_conf_for_domain(domain->alt_name,
1419                                                                         domain->name,
1420                                                                         NULL,
1421                                                                         pss);
1422                                 }
1423                                 winbindd_set_locator_kdc_envs(domain);
1424
1425                                 /* Ensure we contact this DC also. */
1426                                 saf_store(domain->name, *name);
1427                                 saf_store(domain->alt_name, *name);
1428                         }
1429
1430                         ads_destroy( &ads );
1431                         return True;
1432                 }
1433
1434                 ads_destroy( &ads );
1435                 return false;
1436         }
1437 #endif
1438
1439         status = nbt_getdc(winbind_messaging_context(), 10, pss, domain->name,
1440                            &domain->sid, nt_version, mem_ctx, &nt_version,
1441                            &dc_name, NULL);
1442         if (NT_STATUS_IS_OK(status)) {
1443                 *name = talloc_strdup(mem_ctx, dc_name);
1444                 if (*name == NULL) {
1445                         return false;
1446                 }
1447                 namecache_store(*name, 0x20, 1, &ip_list);
1448                 return True;
1449         }
1450
1451         /* try node status request */
1452
1453         if (name_status_find(domain->name, 0x1c, 0x20, pss, nbtname) ) {
1454                 namecache_store(nbtname, 0x20, 1, &ip_list);
1455
1456                 if (name != NULL) {
1457                         *name = talloc_strdup(mem_ctx, nbtname);
1458                         if (*name == NULL) {
1459                                 return false;
1460                         }
1461                 }
1462
1463                 return true;
1464         }
1465         return False;
1466 }
1467
1468 /*******************************************************************
1469  Retrieve a list of IP addresses for domain controllers.
1470
1471  The array is sorted in the preferred connection order.
1472
1473  @param[in] mem_ctx talloc memory context to allocate from
1474  @param[in] domain domain to retrieve DCs for
1475  @param[out] dcs array of dcs that will be returned
1476  @param[out] num_dcs number of dcs returned in the dcs array
1477  @return always true
1478 *******************************************************************/
1479
1480 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
1481                     struct dc_name_ip **dcs, int *num_dcs)
1482 {
1483         fstring dcname;
1484         struct  sockaddr_storage ss;
1485         struct  ip_service *ip_list = NULL;
1486         int     iplist_size = 0;
1487         int     i;
1488         bool    is_our_domain;
1489         enum security_types sec = (enum security_types)lp_security();
1490
1491         is_our_domain = strequal(domain->name, lp_workgroup());
1492
1493         /* If not our domain, get the preferred DC, by asking our primary DC */
1494         if ( !is_our_domain
1495                 && get_dc_name_via_netlogon(domain, dcname, &ss)
1496                 && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
1497                        num_dcs) )
1498         {
1499                 char addr[INET6_ADDRSTRLEN];
1500                 print_sockaddr(addr, sizeof(addr), &ss);
1501                 DEBUG(10, ("Retrieved DC %s at %s via netlogon\n",
1502                            dcname, addr));
1503                 return True;
1504         }
1505
1506         if ((sec == SEC_ADS) && (domain->alt_name != NULL)) {
1507                 char *sitename = NULL;
1508
1509                 /* We need to make sure we know the local site before
1510                    doing any DNS queries, as this will restrict the
1511                    get_sorted_dc_list() call below to only fetching
1512                    DNS records for the correct site. */
1513
1514                 /* Find any DC to get the site record.
1515                    We deliberately don't care about the
1516                    return here. */
1517
1518                 get_dc_name(domain->name, domain->alt_name, dcname, &ss);
1519
1520                 sitename = sitename_fetch(mem_ctx, domain->alt_name);
1521                 if (sitename) {
1522
1523                         /* Do the site-specific AD dns lookup first. */
1524                         get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
1525                                &iplist_size, True);
1526
1527                         /* Add ips to the DC array.  We don't look up the name
1528                            of the DC in this function, but we fill in the char*
1529                            of the ip now to make the failed connection cache
1530                            work */
1531                         for ( i=0; i<iplist_size; i++ ) {
1532                                 char addr[INET6_ADDRSTRLEN];
1533                                 print_sockaddr(addr, sizeof(addr),
1534                                                 &ip_list[i].ss);
1535                                 add_one_dc_unique(mem_ctx,
1536                                                 domain->name,
1537                                                 addr,
1538                                                 &ip_list[i].ss,
1539                                                 dcs,
1540                                                 num_dcs);
1541                         }
1542
1543                         SAFE_FREE(ip_list);
1544                         TALLOC_FREE(sitename);
1545                         iplist_size = 0;
1546                 }
1547
1548                 /* Now we add DCs from the main AD DNS lookup. */
1549                 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1550                         &iplist_size, True);
1551
1552                 for ( i=0; i<iplist_size; i++ ) {
1553                         char addr[INET6_ADDRSTRLEN];
1554                         print_sockaddr(addr, sizeof(addr),
1555                                         &ip_list[i].ss);
1556                         add_one_dc_unique(mem_ctx,
1557                                         domain->name,
1558                                         addr,
1559                                         &ip_list[i].ss,
1560                                         dcs,
1561                                         num_dcs);
1562                 }
1563
1564                 SAFE_FREE(ip_list);
1565                 iplist_size = 0;
1566         }
1567
1568         /* Try standard netbios queries if no ADS and fall back to DNS queries
1569          * if alt_name is available */
1570         if (*num_dcs == 0) {
1571                 get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
1572                        false);
1573                 if (iplist_size == 0) {
1574                         if (domain->alt_name != NULL) {
1575                                 get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
1576                                        &iplist_size, true);
1577                         }
1578                 }
1579
1580                 for ( i=0; i<iplist_size; i++ ) {
1581                         char addr[INET6_ADDRSTRLEN];
1582                         print_sockaddr(addr, sizeof(addr),
1583                                         &ip_list[i].ss);
1584                         add_one_dc_unique(mem_ctx,
1585                                         domain->name,
1586                                         addr,
1587                                         &ip_list[i].ss,
1588                                         dcs,
1589                                         num_dcs);
1590                 }
1591
1592                 SAFE_FREE(ip_list);
1593                 iplist_size = 0;
1594         }
1595
1596         return True;
1597 }
1598
1599 /*******************************************************************
1600  Find and make a connection to a DC in the given domain.
1601
1602  @param[in] mem_ctx talloc memory context to allocate from
1603  @param[in] domain domain to find a dc in
1604  @param[out] dcname NetBIOS or FQDN of DC that's connected to
1605  @param[out] pss DC Internet address and port
1606  @param[out] fd fd of the open socket connected to the newly found dc
1607  @return true when a DC connection is made, false otherwise
1608 *******************************************************************/
1609
1610 static bool find_new_dc(TALLOC_CTX *mem_ctx,
1611                         struct winbindd_domain *domain,
1612                         char **dcname, struct sockaddr_storage *pss, int *fd)
1613 {
1614         struct dc_name_ip *dcs = NULL;
1615         int num_dcs = 0;
1616
1617         const char **dcnames = NULL;
1618         size_t num_dcnames = 0;
1619
1620         struct sockaddr_storage *addrs = NULL;
1621         int num_addrs = 0;
1622
1623         int i;
1624         size_t fd_index;
1625
1626         NTSTATUS status;
1627
1628         *fd = -1;
1629
1630  again:
1631         if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
1632                 return False;
1633
1634         for (i=0; i<num_dcs; i++) {
1635
1636                 if (!add_string_to_array(mem_ctx, dcs[i].name,
1637                                     &dcnames, &num_dcnames)) {
1638                         return False;
1639                 }
1640                 if (!add_sockaddr_to_array(mem_ctx, &dcs[i].ss, TCP_SMB_PORT,
1641                                       &addrs, &num_addrs)) {
1642                         return False;
1643                 }
1644         }
1645
1646         if ((num_dcnames == 0) || (num_dcnames != num_addrs))
1647                 return False;
1648
1649         if ((addrs == NULL) || (dcnames == NULL))
1650                 return False;
1651
1652         status = smbsock_any_connect(addrs, dcnames, NULL, NULL, NULL,
1653                                      num_addrs, 0, 10, fd, &fd_index, NULL);
1654         if (!NT_STATUS_IS_OK(status)) {
1655                 for (i=0; i<num_dcs; i++) {
1656                         char ab[INET6_ADDRSTRLEN];
1657                         print_sockaddr(ab, sizeof(ab), &dcs[i].ss);
1658                         DEBUG(10, ("find_new_dc: smbsock_any_connect failed for "
1659                                 "domain %s address %s. Error was %s\n",
1660                                    domain->name, ab, nt_errstr(status) ));
1661                         winbind_add_failed_connection_entry(domain,
1662                                 dcs[i].name, NT_STATUS_UNSUCCESSFUL);
1663                 }
1664                 return False;
1665         }
1666
1667         *pss = addrs[fd_index];
1668
1669         if (*dcnames[fd_index] != '\0' && !is_ipaddress(dcnames[fd_index])) {
1670                 /* Ok, we've got a name for the DC */
1671                 *dcname = talloc_strdup(mem_ctx, dcnames[fd_index]);
1672                 if (*dcname == NULL) {
1673                         return false;
1674                 }
1675                 return true;
1676         }
1677
1678         /* Try to figure out the name */
1679         if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
1680                 return True;
1681         }
1682
1683         /* We can not continue without the DC's name */
1684         winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
1685                                     NT_STATUS_UNSUCCESSFUL);
1686
1687         /* Throw away all arrays as we're doing this again. */
1688         TALLOC_FREE(dcs);
1689         num_dcs = 0;
1690
1691         TALLOC_FREE(dcnames);
1692         num_dcnames = 0;
1693
1694         TALLOC_FREE(addrs);
1695         num_addrs = 0;
1696
1697         close(*fd);
1698         *fd = -1;
1699
1700         goto again;
1701 }
1702
1703 static char *current_dc_key(TALLOC_CTX *mem_ctx, const char *domain_name)
1704 {
1705         return talloc_asprintf_strupper_m(mem_ctx, "CURRENT_DCNAME/%s",
1706                                           domain_name);
1707 }
1708
1709 static void store_current_dc_in_gencache(const char *domain_name,
1710                                          const char *dc_name,
1711                                          struct cli_state *cli)
1712 {
1713         char addr[INET6_ADDRSTRLEN];
1714         char *key = NULL;
1715         char *value = NULL;
1716
1717         if (!cli_state_is_connected(cli)) {
1718                 return;
1719         }
1720
1721         print_sockaddr(addr, sizeof(addr),
1722                        smbXcli_conn_remote_sockaddr(cli->conn));
1723
1724         key = current_dc_key(talloc_tos(), domain_name);
1725         if (key == NULL) {
1726                 goto done;
1727         }
1728
1729         value = talloc_asprintf(talloc_tos(), "%s %s", addr, dc_name);
1730         if (value == NULL) {
1731                 goto done;
1732         }
1733
1734         gencache_set(key, value, 0x7fffffff);
1735 done:
1736         TALLOC_FREE(value);
1737         TALLOC_FREE(key);
1738 }
1739
1740 bool fetch_current_dc_from_gencache(TALLOC_CTX *mem_ctx,
1741                                     const char *domain_name,
1742                                     char **p_dc_name, char **p_dc_ip)
1743 {
1744         char *key, *p;
1745         char *value = NULL;
1746         bool ret = false;
1747         char *dc_name = NULL;
1748         char *dc_ip = NULL;
1749
1750         key = current_dc_key(talloc_tos(), domain_name);
1751         if (key == NULL) {
1752                 goto done;
1753         }
1754         if (!gencache_get(key, mem_ctx, &value, NULL)) {
1755                 goto done;
1756         }
1757         p = strchr(value, ' ');
1758         if (p == NULL) {
1759                 goto done;
1760         }
1761         dc_ip = talloc_strndup(mem_ctx, value, p - value);
1762         if (dc_ip == NULL) {
1763                 goto done;
1764         }
1765         dc_name = talloc_strdup(mem_ctx, p+1);
1766         if (dc_name == NULL) {
1767                 goto done;
1768         }
1769
1770         if (p_dc_ip != NULL) {
1771                 *p_dc_ip = dc_ip;
1772                 dc_ip = NULL;
1773         }
1774         if (p_dc_name != NULL) {
1775                 *p_dc_name = dc_name;
1776                 dc_name = NULL;
1777         }
1778         ret = true;
1779 done:
1780         TALLOC_FREE(dc_name);
1781         TALLOC_FREE(dc_ip);
1782         TALLOC_FREE(key);
1783         TALLOC_FREE(value);
1784         return ret;
1785 }
1786
1787 NTSTATUS wb_open_internal_pipe(TALLOC_CTX *mem_ctx,
1788                                const struct ndr_interface_table *table,
1789                                struct rpc_pipe_client **ret_pipe)
1790 {
1791         struct rpc_pipe_client *cli = NULL;
1792         const struct auth_session_info *session_info;
1793         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1794
1795
1796         session_info = get_session_info_system();
1797         SMB_ASSERT(session_info != NULL);
1798
1799         /* create a connection to the specified pipe */
1800         if (lp_parm_bool(-1, "winbindd", "use external pipes", false)) {
1801                 status = rpc_pipe_open_interface(mem_ctx,
1802                                                  table,
1803                                                  session_info,
1804                                                  NULL,
1805                                                  winbind_messaging_context(),
1806                                                  &cli);
1807         } else {
1808                 status = rpc_pipe_open_internal(mem_ctx,
1809                                                 &table->syntax_id,
1810                                                 session_info,
1811                                                 NULL,
1812                                                 winbind_messaging_context(),
1813                                                 &cli);
1814         }
1815         if (!NT_STATUS_IS_OK(status)) {
1816                 DEBUG(0, ("open_internal_pipe: Could not connect to %s pipe: %s\n",
1817                           table->name, nt_errstr(status)));
1818                 return status;
1819         }
1820
1821         if (ret_pipe) {
1822                 *ret_pipe = cli;
1823         }
1824
1825         return NT_STATUS_OK;
1826 }
1827
1828 static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
1829                                    struct winbindd_cm_conn *new_conn)
1830 {
1831         TALLOC_CTX *mem_ctx;
1832         NTSTATUS result;
1833         char *saf_servername;
1834         int retries;
1835
1836         if ((mem_ctx = talloc_init("cm_open_connection")) == NULL) {
1837                 set_domain_offline(domain);
1838                 return NT_STATUS_NO_MEMORY;
1839         }
1840
1841         saf_servername = saf_fetch(mem_ctx, domain->name );
1842
1843         /* we have to check the server affinity cache here since 
1844            later we select a DC based on response time and not preference */
1845
1846         /* Check the negative connection cache
1847            before talking to it. It going down may have
1848            triggered the reconnection. */
1849
1850         if ( saf_servername && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, saf_servername))) {
1851
1852                 DEBUG(10,("cm_open_connection: saf_servername is '%s' for domain %s\n",
1853                         saf_servername, domain->name ));
1854
1855                 /* convert an ip address to a name */
1856                 if (is_ipaddress( saf_servername ) ) {
1857                         char *dcname = NULL;
1858                         struct sockaddr_storage ss;
1859
1860                         if (!interpret_string_addr(&ss, saf_servername,
1861                                                 AI_NUMERICHOST)) {
1862                                 TALLOC_FREE(mem_ctx);
1863                                 return NT_STATUS_UNSUCCESSFUL;
1864                         }
1865                         if (dcip_to_name(mem_ctx, domain, &ss, &dcname)) {
1866                                 domain->dcname = talloc_strdup(domain,
1867                                                                dcname);
1868                                 if (domain->dcname == NULL) {
1869                                         TALLOC_FREE(mem_ctx);
1870                                         return NT_STATUS_NO_MEMORY;
1871                                 }
1872                         } else {
1873                                 winbind_add_failed_connection_entry(
1874                                         domain, saf_servername,
1875                                         NT_STATUS_UNSUCCESSFUL);
1876                         }
1877                 } else {
1878                         domain->dcname = talloc_strdup(domain, saf_servername);
1879                         if (domain->dcname == NULL) {
1880                                 TALLOC_FREE(mem_ctx);
1881                                 return NT_STATUS_NO_MEMORY;
1882                         }
1883                 }
1884         }
1885
1886         for (retries = 0; retries < 3; retries++) {
1887                 int fd = -1;
1888                 bool retry = False;
1889                 char *dcname = NULL;
1890
1891                 result = NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
1892
1893                 DEBUG(10,("cm_open_connection: dcname is '%s' for domain %s\n",
1894                         domain->dcname ? domain->dcname : "", domain->name ));
1895
1896                 if (domain->dcname != NULL
1897                         && NT_STATUS_IS_OK(check_negative_conn_cache( domain->name, domain->dcname))
1898                         && (resolve_name(domain->dcname, &domain->dcaddr, 0x20, true)))
1899                 {
1900                         NTSTATUS status;
1901
1902                         status = smbsock_connect(&domain->dcaddr, 0,
1903                                                  NULL, -1, NULL, -1,
1904                                                  &fd, NULL, 10);
1905                         if (!NT_STATUS_IS_OK(status)) {
1906                                 fd = -1;
1907                         }
1908                 }
1909
1910                 if ((fd == -1) &&
1911                     !find_new_dc(mem_ctx, domain, &dcname, &domain->dcaddr, &fd))
1912                 {
1913                         /* This is the one place where we will
1914                            set the global winbindd offline state
1915                            to true, if a "WINBINDD_OFFLINE" entry
1916                            is found in the winbindd cache. */
1917                         set_global_winbindd_state_offline();
1918                         break;
1919                 }
1920                 if (dcname != NULL) {
1921                         talloc_free(domain->dcname);
1922
1923                         domain->dcname = talloc_move(domain, &dcname);
1924                         if (domain->dcname == NULL) {
1925                                 result = NT_STATUS_NO_MEMORY;
1926                                 break;
1927                         }
1928                 }
1929
1930                 new_conn->cli = NULL;
1931
1932                 result = cm_prepare_connection(domain, fd, domain->dcname,
1933                         &new_conn->cli, &retry);
1934                 if (!NT_STATUS_IS_OK(result)) {
1935                         /* Don't leak the smb connection socket */
1936                         close(fd);
1937                 }
1938
1939                 if (!retry)
1940                         break;
1941         }
1942
1943         if (NT_STATUS_IS_OK(result)) {
1944                 bool seal_pipes = true;
1945
1946                 winbindd_set_locator_kdc_envs(domain);
1947
1948                 if (domain->online == False) {
1949                         /* We're changing state from offline to online. */
1950                         set_global_winbindd_state_online();
1951                 }
1952                 set_domain_online(domain);
1953
1954                 /*
1955                  * Much as I hate global state, this seems to be the point
1956                  * where we can be certain that we have a proper connection to
1957                  * a DC. wbinfo --dc-info needs that information, store it in
1958                  * gencache with a looong timeout. This will need revisiting
1959                  * once we start to connect to multiple DCs, wbcDcInfo is
1960                  * already prepared for that.
1961                  */
1962                 store_current_dc_in_gencache(domain->name, domain->dcname,
1963                                              new_conn->cli);
1964
1965                 seal_pipes = lp_winbind_sealed_pipes();
1966                 seal_pipes = lp_parm_bool(-1, "winbind sealed pipes",
1967                                           domain->name,
1968                                           seal_pipes);
1969
1970                 if (seal_pipes) {
1971                         new_conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1972                 } else {
1973                         new_conn->auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
1974                 }
1975         } else {
1976                 /* Ensure we setup the retry handler. */
1977                 set_domain_offline(domain);
1978         }
1979
1980         talloc_destroy(mem_ctx);
1981         return result;
1982 }
1983
1984 /* Close down all open pipes on a connection. */
1985
1986 void invalidate_cm_connection(struct winbindd_domain *domain)
1987 {
1988         NTSTATUS result;
1989         struct winbindd_cm_conn *conn = &domain->conn;
1990
1991         /* We're closing down a possibly dead
1992            connection. Don't have impossibly long (10s) timeouts. */
1993
1994         if (conn->cli) {
1995                 cli_set_timeout(conn->cli, 1000); /* 1 second. */
1996         }
1997
1998         if (conn->samr_pipe != NULL) {
1999                 if (is_valid_policy_hnd(&conn->sam_connect_handle)) {
2000                         dcerpc_samr_Close(conn->samr_pipe->binding_handle,
2001                                           talloc_tos(),
2002                                           &conn->sam_connect_handle,
2003                                           &result);
2004                 }
2005                 TALLOC_FREE(conn->samr_pipe);
2006                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2007                 if (conn->cli) {
2008                         cli_set_timeout(conn->cli, 500);
2009                 }
2010         }
2011
2012         if (conn->lsa_pipe != NULL) {
2013                 if (is_valid_policy_hnd(&conn->lsa_policy)) {
2014                         dcerpc_lsa_Close(conn->lsa_pipe->binding_handle,
2015                                          talloc_tos(),
2016                                          &conn->lsa_policy,
2017                                          &result);
2018                 }
2019                 TALLOC_FREE(conn->lsa_pipe);
2020                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2021                 if (conn->cli) {
2022                         cli_set_timeout(conn->cli, 500);
2023                 }
2024         }
2025
2026         if (conn->lsa_pipe_tcp != NULL) {
2027                 if (is_valid_policy_hnd(&conn->lsa_policy)) {
2028                         dcerpc_lsa_Close(conn->lsa_pipe_tcp->binding_handle,
2029                                          talloc_tos(),
2030                                          &conn->lsa_policy,
2031                                          &result);
2032                 }
2033                 TALLOC_FREE(conn->lsa_pipe_tcp);
2034                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2035                 if (conn->cli) {
2036                         cli_set_timeout(conn->cli, 500);
2037                 }
2038         }
2039
2040         if (conn->netlogon_pipe != NULL) {
2041                 TALLOC_FREE(conn->netlogon_pipe);
2042                 /* Ok, it must be dead. Drop timeout to 0.5 sec. */
2043                 if (conn->cli) {
2044                         cli_set_timeout(conn->cli, 500);
2045                 }
2046         }
2047
2048         conn->auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
2049         conn->netlogon_force_reauth = false;
2050         conn->netlogon_flags = 0;
2051         TALLOC_FREE(conn->netlogon_creds);
2052
2053         if (conn->cli) {
2054                 cli_shutdown(conn->cli);
2055         }
2056
2057         conn->cli = NULL;
2058 }
2059
2060 void close_conns_after_fork(void)
2061 {
2062         struct winbindd_domain *domain;
2063         struct winbindd_cli_state *cli_state;
2064
2065         for (domain = domain_list(); domain; domain = domain->next) {
2066                 /*
2067                  * first close the low level SMB TCP connection
2068                  * so that we don't generate any SMBclose
2069                  * requests in invalidate_cm_connection()
2070                  */
2071                 if (cli_state_is_connected(domain->conn.cli)) {
2072                         smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
2073                 }
2074
2075                 invalidate_cm_connection(domain);
2076         }
2077
2078         for (cli_state = winbindd_client_list();
2079              cli_state != NULL;
2080              cli_state = cli_state->next) {
2081                 if (cli_state->sock >= 0) {
2082                         close(cli_state->sock);
2083                         cli_state->sock = -1;
2084                 }
2085         }
2086 }
2087
2088 static bool connection_ok(struct winbindd_domain *domain)
2089 {
2090         bool ok;
2091
2092         ok = cli_state_is_connected(domain->conn.cli);
2093         if (!ok) {
2094                 DEBUG(3, ("connection_ok: Connection to %s for domain %s is not connected\n",
2095                           domain->dcname, domain->name));
2096                 return False;
2097         }
2098
2099         if (domain->online == False) {
2100                 DEBUG(3, ("connection_ok: Domain %s is offline\n", domain->name));
2101                 return False;
2102         }
2103
2104         return True;
2105 }
2106
2107 /* Initialize a new connection up to the RPC BIND.
2108    Bypass online status check so always does network calls. */
2109
2110 static NTSTATUS init_dc_connection_network(struct winbindd_domain *domain, bool need_rw_dc)
2111 {
2112         NTSTATUS result;
2113         bool skip_connection = domain->internal;
2114         if (need_rw_dc && domain->rodc) {
2115                 skip_connection = false;
2116         }
2117
2118         /* Internal connections never use the network. */
2119         if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2120                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2121         }
2122
2123         /* Still ask the internal LSA and SAMR server about the local domain */
2124         if (skip_connection || connection_ok(domain)) {
2125                 if (!domain->initialized) {
2126                         set_dc_type_and_flags(domain);
2127                 }
2128                 return NT_STATUS_OK;
2129         }
2130
2131         invalidate_cm_connection(domain);
2132
2133         if (!domain->primary && !domain->initialized) {
2134                 /*
2135                  * Before we connect to a trust, work out if it is an
2136                  * AD domain by asking our own domain.
2137                  */
2138                 set_dc_type_and_flags_trustinfo(domain);
2139         }
2140
2141         result = cm_open_connection(domain, &domain->conn);
2142
2143         if (NT_STATUS_IS_OK(result) && !domain->initialized) {
2144                 set_dc_type_and_flags(domain);
2145         }
2146
2147         return result;
2148 }
2149
2150 NTSTATUS init_dc_connection(struct winbindd_domain *domain, bool need_rw_dc)
2151 {
2152         if (dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
2153                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
2154         }
2155
2156         if (domain->initialized && !domain->online) {
2157                 /* We check for online status elsewhere. */
2158                 return NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND;
2159         }
2160
2161         return init_dc_connection_network(domain, need_rw_dc);
2162 }
2163
2164 static NTSTATUS init_dc_connection_rpc(struct winbindd_domain *domain, bool need_rw_dc)
2165 {
2166         NTSTATUS status;
2167
2168         status = init_dc_connection(domain, need_rw_dc);
2169         if (!NT_STATUS_IS_OK(status)) {
2170                 return status;
2171         }
2172
2173         if (!domain->internal && domain->conn.cli == NULL) {
2174                 /* happens for trusted domains without inbound trust */
2175                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2176         }
2177
2178         return NT_STATUS_OK;
2179 }
2180
2181 /******************************************************************************
2182  Set the trust flags (direction and forest location) for a domain
2183 ******************************************************************************/
2184
2185 static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
2186 {
2187         struct winbindd_domain *our_domain;
2188         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2189         WERROR werr;
2190         struct netr_DomainTrustList trusts;
2191         int i;
2192         uint32 flags = (NETR_TRUST_FLAG_IN_FOREST |
2193                         NETR_TRUST_FLAG_OUTBOUND |
2194                         NETR_TRUST_FLAG_INBOUND);
2195         struct rpc_pipe_client *cli;
2196         TALLOC_CTX *mem_ctx = NULL;
2197         struct dcerpc_binding_handle *b;
2198
2199         DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
2200
2201         /* Our primary domain doesn't need to worry about trust flags.
2202            Force it to go through the network setup */
2203         if ( domain->primary ) {                
2204                 return False;           
2205         }
2206
2207         mem_ctx = talloc_stackframe();
2208         our_domain = find_our_domain();
2209         if (our_domain->internal) {
2210                 result = init_dc_connection(our_domain, false);
2211                 if (!NT_STATUS_IS_OK(result)) {
2212                         DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2213                                  "Not able to make a connection to our domain: %s\n",
2214                                   nt_errstr(result)));
2215                         TALLOC_FREE(mem_ctx);
2216                         return false;
2217                 }
2218         }
2219
2220         /* This won't work unless our domain is AD */
2221         if ( !our_domain->active_directory ) {
2222                 TALLOC_FREE(mem_ctx);
2223                 return False;
2224         }
2225
2226         if (our_domain->internal) {
2227                 result = wb_open_internal_pipe(mem_ctx, &ndr_table_netlogon, &cli);
2228         } else if (!connection_ok(our_domain)) {
2229                 DEBUG(3,("set_dc_type_and_flags_trustinfo: "
2230                          "No connection to our domain!\n"));
2231                 TALLOC_FREE(mem_ctx);
2232                 return False;
2233         } else {
2234                 result = cm_connect_netlogon(our_domain, &cli);
2235         }
2236
2237         if (!NT_STATUS_IS_OK(result)) {
2238                 DEBUG(5, ("set_dc_type_and_flags_trustinfo: Could not open "
2239                           "a connection to %s for PIPE_NETLOGON (%s)\n", 
2240                           domain->name, nt_errstr(result)));
2241                 TALLOC_FREE(mem_ctx);
2242                 return False;
2243         }
2244         b = cli->binding_handle;
2245
2246         /* Use DsEnumerateDomainTrusts to get us the trust direction and type. */
2247         result = dcerpc_netr_DsrEnumerateDomainTrusts(b, mem_ctx,
2248                                                       cli->desthost,
2249                                                       flags,
2250                                                       &trusts,
2251                                                       &werr);
2252         if (!NT_STATUS_IS_OK(result)) {
2253                 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2254                         "failed to query trusted domain list: %s\n",
2255                         nt_errstr(result)));
2256                 TALLOC_FREE(mem_ctx);
2257                 return false;
2258         }
2259         if (!W_ERROR_IS_OK(werr)) {
2260                 DEBUG(0,("set_dc_type_and_flags_trustinfo: "
2261                         "failed to query trusted domain list: %s\n",
2262                         win_errstr(werr)));
2263                 TALLOC_FREE(mem_ctx);
2264                 return false;
2265         }
2266
2267         /* Now find the domain name and get the flags */
2268
2269         for ( i=0; i<trusts.count; i++ ) {
2270                 if ( strequal( domain->name, trusts.array[i].netbios_name) ) {
2271                         domain->domain_flags          = trusts.array[i].trust_flags;
2272                         domain->domain_type           = trusts.array[i].trust_type;
2273                         domain->domain_trust_attribs  = trusts.array[i].trust_attributes;
2274
2275                         if ( domain->domain_type == LSA_TRUST_TYPE_UPLEVEL )
2276                                 domain->active_directory = True;
2277
2278                         /* This flag is only set if the domain is *our* 
2279                            primary domain and the primary domain is in
2280                            native mode */
2281
2282                         domain->native_mode = (domain->domain_flags & NETR_TRUST_FLAG_NATIVE);
2283
2284                         DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s is %sin "
2285                                   "native mode.\n", domain->name, 
2286                                   domain->native_mode ? "" : "NOT "));
2287
2288                         DEBUG(5,("set_dc_type_and_flags_trustinfo: domain %s is %s"
2289                                  "running active directory.\n", domain->name, 
2290                                  domain->active_directory ? "" : "NOT "));
2291
2292                         domain->can_do_ncacn_ip_tcp = domain->active_directory;
2293
2294                         domain->initialized = True;
2295
2296                         break;
2297                 }               
2298         }
2299
2300         TALLOC_FREE(mem_ctx);
2301
2302         return domain->initialized;     
2303 }
2304
2305 /******************************************************************************
2306  We can 'sense' certain things about the DC by it's replies to certain
2307  questions.
2308
2309  This tells us if this particular remote server is Active Directory, and if it
2310  is native mode.
2311 ******************************************************************************/
2312
2313 static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
2314 {
2315         NTSTATUS status, result;
2316         WERROR werr;
2317         TALLOC_CTX              *mem_ctx = NULL;
2318         struct rpc_pipe_client  *cli = NULL;
2319         struct policy_handle pol;
2320         union dssetup_DsRoleInfo info;
2321         union lsa_PolicyInformation *lsa_info = NULL;
2322
2323         if (!domain->internal && !connection_ok(domain)) {
2324                 return;
2325         }
2326
2327         mem_ctx = talloc_init("set_dc_type_and_flags on domain %s\n",
2328                               domain->name);
2329         if (!mem_ctx) {
2330                 DEBUG(1, ("set_dc_type_and_flags_connect: talloc_init() failed\n"));
2331                 return;
2332         }
2333
2334         DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
2335
2336         if (domain->internal) {
2337                 status = wb_open_internal_pipe(mem_ctx,
2338                                                &ndr_table_dssetup,
2339                                                &cli);
2340         } else {
2341                 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2342                                                   &ndr_table_dssetup,
2343                                                   &cli);
2344         }
2345
2346         if (!NT_STATUS_IS_OK(status)) {
2347                 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2348                           "PI_DSSETUP on domain %s: (%s)\n",
2349                           domain->name, nt_errstr(status)));
2350
2351                 /* if this is just a non-AD domain we need to continue
2352                  * identifying so that we can in the end return with
2353                  * domain->initialized = True - gd */
2354
2355                 goto no_dssetup;
2356         }
2357
2358         status = dcerpc_dssetup_DsRoleGetPrimaryDomainInformation(cli->binding_handle, mem_ctx,
2359                                                                   DS_ROLE_BASIC_INFORMATION,
2360                                                                   &info,
2361                                                                   &werr);
2362         TALLOC_FREE(cli);
2363
2364         if (NT_STATUS_IS_OK(status)) {
2365                 result = werror_to_ntstatus(werr);
2366         }
2367         if (!NT_STATUS_IS_OK(status)) {
2368                 DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
2369                           "on domain %s failed: (%s)\n",
2370                           domain->name, nt_errstr(status)));
2371
2372                 /* older samba3 DCs will return DCERPC_FAULT_OP_RNG_ERROR for
2373                  * every opcode on the DSSETUP pipe, continue with
2374                  * no_dssetup mode here as well to get domain->initialized
2375                  * set - gd */
2376
2377                 if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_PROCNUM_OUT_OF_RANGE)) {
2378                         goto no_dssetup;
2379                 }
2380
2381                 TALLOC_FREE(mem_ctx);
2382                 return;
2383         }
2384
2385         if ((info.basic.flags & DS_ROLE_PRIMARY_DS_RUNNING) &&
2386             !(info.basic.flags & DS_ROLE_PRIMARY_DS_MIXED_MODE)) {
2387                 domain->native_mode = True;
2388         } else {
2389                 domain->native_mode = False;
2390         }
2391
2392 no_dssetup:
2393         if (domain->internal) {
2394                 status = wb_open_internal_pipe(mem_ctx,
2395                                                &ndr_table_lsarpc,
2396                                                &cli);
2397         } else {
2398                 status = cli_rpc_pipe_open_noauth(domain->conn.cli,
2399                                                   &ndr_table_lsarpc, &cli);
2400         }
2401         if (!NT_STATUS_IS_OK(status)) {
2402                 DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
2403                           "PI_LSARPC on domain %s: (%s)\n",
2404                           domain->name, nt_errstr(status)));
2405                 TALLOC_FREE(cli);
2406                 TALLOC_FREE(mem_ctx);
2407                 return;
2408         }
2409
2410         status = rpccli_lsa_open_policy2(cli, mem_ctx, True,
2411                                          SEC_FLAG_MAXIMUM_ALLOWED, &pol);
2412
2413         if (NT_STATUS_IS_OK(status)) {
2414                 /* This particular query is exactly what Win2k clients use 
2415                    to determine that the DC is active directory */
2416                 status = dcerpc_lsa_QueryInfoPolicy2(cli->binding_handle, mem_ctx,
2417                                                      &pol,
2418                                                      LSA_POLICY_INFO_DNS,
2419                                                      &lsa_info,
2420                                                      &result);
2421         }
2422
2423         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2424                 domain->active_directory = True;
2425
2426                 if (lsa_info->dns.name.string) {
2427                         if (!strequal(domain->name, lsa_info->dns.name.string))
2428                         {
2429                                 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2430                                           "for domain %s claimed it was a DC "
2431                                           "for domain %s, refusing to "
2432                                           "initialize\n",
2433                                           domain->name,
2434                                           lsa_info->dns.name.string));
2435                                 TALLOC_FREE(cli);
2436                                 TALLOC_FREE(mem_ctx);
2437                                 return;
2438                         }
2439                         talloc_free(domain->name);
2440                         domain->name = talloc_strdup(domain,
2441                                                      lsa_info->dns.name.string);
2442                         if (domain->name == NULL) {
2443                                 goto done;
2444                         }
2445                 }
2446
2447                 if (lsa_info->dns.dns_domain.string) {
2448                         if (domain->alt_name != NULL &&
2449                             !strequal(domain->alt_name,
2450                                       lsa_info->dns.dns_domain.string))
2451                         {
2452                                 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2453                                           "for domain %s (%s) claimed it was "
2454                                           "a DC for domain %s, refusing to "
2455                                           "initialize\n",
2456                                           domain->alt_name, domain->name,
2457                                           lsa_info->dns.dns_domain.string));
2458                                 TALLOC_FREE(cli);
2459                                 TALLOC_FREE(mem_ctx);
2460                                 return;
2461                         }
2462                         talloc_free(domain->alt_name);
2463                         domain->alt_name =
2464                                 talloc_strdup(domain,
2465                                               lsa_info->dns.dns_domain.string);
2466                         if (domain->alt_name == NULL) {
2467                                 goto done;
2468                         }
2469                 }
2470
2471                 /* See if we can set some domain trust flags about
2472                    ourself */
2473
2474                 if (lsa_info->dns.dns_forest.string) {
2475                         talloc_free(domain->forest_name);
2476                         domain->forest_name =
2477                                 talloc_strdup(domain,
2478                                               lsa_info->dns.dns_forest.string);
2479                         if (domain->forest_name == NULL) {
2480                                 goto done;
2481                         }
2482
2483                         if (strequal(domain->forest_name, domain->alt_name)) {
2484                                 domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
2485                         }
2486                 }
2487
2488                 if (lsa_info->dns.sid) {
2489                         if (!is_null_sid(&domain->sid) &&
2490                             !dom_sid_equal(&domain->sid,
2491                                            lsa_info->dns.sid))
2492                         {
2493                                 DEBUG(1, ("set_dc_type_and_flags_connect: DC "
2494                                           "for domain %s (%s) claimed it was "
2495                                           "a DC for domain %s, refusing to "
2496                                           "initialize\n",
2497                                           dom_sid_string(talloc_tos(),
2498                                                          &domain->sid),
2499                                           domain->name,
2500                                           dom_sid_string(talloc_tos(),
2501                                                          lsa_info->dns.sid)));
2502                                 TALLOC_FREE(cli);
2503                                 TALLOC_FREE(mem_ctx);
2504                                 return;
2505                         }
2506                         sid_copy(&domain->sid, lsa_info->dns.sid);
2507                 }
2508         } else {
2509                 domain->active_directory = False;
2510
2511                 status = rpccli_lsa_open_policy(cli, mem_ctx, True,
2512                                                 SEC_FLAG_MAXIMUM_ALLOWED,
2513                                                 &pol);
2514
2515                 if (!NT_STATUS_IS_OK(status)) {
2516                         goto done;
2517                 }
2518
2519                 status = dcerpc_lsa_QueryInfoPolicy(cli->binding_handle, mem_ctx,
2520                                                     &pol,
2521                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
2522                                                     &lsa_info,
2523                                                     &result);
2524                 if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2525
2526                         if (lsa_info->account_domain.name.string) {
2527                                 if (!strequal(domain->name,
2528                                         lsa_info->account_domain.name.string))
2529                                 {
2530                                         DEBUG(1,
2531                                               ("set_dc_type_and_flags_connect: "
2532                                                "DC for domain %s claimed it was"
2533                                                " a DC for domain %s, refusing "
2534                                                "to initialize\n", domain->name,
2535                                                lsa_info->
2536                                                 account_domain.name.string));
2537                                         TALLOC_FREE(cli);
2538                                         TALLOC_FREE(mem_ctx);
2539                                         return;
2540                                 }
2541                                 talloc_free(domain->name);
2542                                 domain->name =
2543                                         talloc_strdup(domain,
2544                                                       lsa_info->account_domain.name.string);
2545                         }
2546
2547                         if (lsa_info->account_domain.sid) {
2548                                 if (!is_null_sid(&domain->sid) &&
2549                                     !dom_sid_equal(&domain->sid,
2550                                                 lsa_info->account_domain.sid))
2551                                 {
2552                                         DEBUG(1,
2553                                               ("set_dc_type_and_flags_connect: "
2554                                                "DC for domain %s (%s) claimed "
2555                                                "it was a DC for domain %s, "
2556                                                "refusing to initialize\n",
2557                                                dom_sid_string(talloc_tos(),
2558                                                               &domain->sid),
2559                                                domain->name,
2560                                                dom_sid_string(talloc_tos(),
2561                                                 lsa_info->account_domain.sid)));
2562                                         TALLOC_FREE(cli);
2563                                         TALLOC_FREE(mem_ctx);
2564                                         return;
2565                                 }
2566                                 sid_copy(&domain->sid, lsa_info->account_domain.sid);
2567                         }
2568                 }
2569         }
2570 done:
2571
2572         DEBUG(5, ("set_dc_type_and_flags_connect: domain %s is %sin native mode.\n",
2573                   domain->name, domain->native_mode ? "" : "NOT "));
2574
2575         DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
2576                   domain->name, domain->active_directory ? "" : "NOT "));
2577
2578         domain->can_do_ncacn_ip_tcp = domain->active_directory;
2579
2580         TALLOC_FREE(cli);
2581
2582         TALLOC_FREE(mem_ctx);
2583
2584         domain->initialized = True;
2585 }
2586
2587 /**********************************************************************
2588  Set the domain_flags (trust attributes, domain operating modes, etc... 
2589 ***********************************************************************/
2590
2591 static void set_dc_type_and_flags( struct winbindd_domain *domain )
2592 {
2593         /* we always have to contact our primary domain */
2594
2595         if ( domain->primary || domain->internal) {
2596                 DEBUG(10,("set_dc_type_and_flags: setting up flags for "
2597                           "primary or internal domain\n"));
2598                 set_dc_type_and_flags_connect( domain );
2599                 return;         
2600         }
2601
2602         /* Use our DC to get the information if possible */
2603
2604         if ( !set_dc_type_and_flags_trustinfo( domain ) ) {
2605                 /* Otherwise, fallback to contacting the 
2606                    domain directly */
2607                 set_dc_type_and_flags_connect( domain );
2608         }
2609
2610         return;
2611 }
2612
2613
2614
2615 /**********************************************************************
2616 ***********************************************************************/
2617
2618 static NTSTATUS cm_get_schannel_creds(struct winbindd_domain *domain,
2619                                    struct netlogon_creds_cli_context **ppdc)
2620 {
2621         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2622         struct rpc_pipe_client *netlogon_pipe;
2623
2624         *ppdc = NULL;
2625
2626         if ((!IS_DC) && (!domain->primary)) {
2627                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2628         }
2629
2630         if (domain->conn.netlogon_creds != NULL) {
2631                 if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2632                         return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2633                 }
2634                 *ppdc = domain->conn.netlogon_creds;
2635                 return NT_STATUS_OK;
2636         }
2637
2638         result = cm_connect_netlogon(domain, &netlogon_pipe);
2639         if (!NT_STATUS_IS_OK(result)) {
2640                 return result;
2641         }
2642
2643         if (domain->conn.netlogon_creds == NULL) {
2644                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2645         }
2646
2647         if (!(domain->conn.netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
2648                 return NT_STATUS_TRUSTED_DOMAIN_FAILURE;
2649         }
2650
2651         *ppdc = domain->conn.netlogon_creds;
2652         return NT_STATUS_OK;
2653 }
2654
2655 NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2656                         bool need_rw_dc,
2657                         struct rpc_pipe_client **cli, struct policy_handle *sam_handle)
2658 {
2659         struct winbindd_cm_conn *conn;
2660         NTSTATUS status, result;
2661         struct netlogon_creds_cli_context *p_creds;
2662         struct cli_credentials *creds = NULL;
2663
2664         if (sid_check_is_our_sam(&domain->sid)) {
2665                 if (domain->rodc == false || need_rw_dc == false) {
2666                         return open_internal_samr_conn(mem_ctx, domain, cli, sam_handle);
2667                 }
2668         }
2669
2670         status = init_dc_connection_rpc(domain, need_rw_dc);
2671         if (!NT_STATUS_IS_OK(status)) {
2672                 return status;
2673         }
2674
2675         conn = &domain->conn;
2676
2677         if (rpccli_is_connected(conn->samr_pipe)) {
2678                 goto done;
2679         }
2680
2681         TALLOC_FREE(conn->samr_pipe);
2682
2683         /*
2684          * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
2685          * sign and sealed pipe using the machine account password by
2686          * preference. If we can't - try schannel, if that fails, try
2687          * anonymous.
2688          */
2689
2690         result = get_trust_credentials(domain, talloc_tos(), false, &creds);
2691         if (!NT_STATUS_IS_OK(result)) {
2692                 DEBUG(10, ("cm_connect_sam: No no user available for "
2693                            "domain %s, trying schannel\n", domain->name));
2694                 goto schannel;
2695         }
2696
2697         if (cli_credentials_is_anonymous(creds)) {
2698                 goto anonymous;
2699         }
2700
2701         /*
2702          * We have an authenticated connection. Use a SPNEGO
2703          * authenticated SAMR pipe with sign & seal.
2704          */
2705         status = cli_rpc_pipe_open_with_creds(conn->cli,
2706                                               &ndr_table_samr,
2707                                               NCACN_NP,
2708                                               DCERPC_AUTH_TYPE_SPNEGO,
2709                                               conn->auth_level,
2710                                               smbXcli_conn_remote_name(conn->cli->conn),
2711                                               creds,
2712                                               &conn->samr_pipe);
2713         if (!NT_STATUS_IS_OK(status)) {
2714                 DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
2715                           "pipe for domain %s using NTLMSSP "
2716                           "authenticated pipe: user %s. Error was "
2717                           "%s\n", domain->name,
2718                           cli_credentials_get_unparsed_name(creds, talloc_tos()),
2719                           nt_errstr(status)));
2720                 goto schannel;
2721         }
2722
2723         DEBUG(10,("cm_connect_sam: connected to SAMR pipe for "
2724                   "domain %s using NTLMSSP authenticated "
2725                   "pipe: user %s\n", domain->name,
2726                   cli_credentials_get_unparsed_name(creds, talloc_tos())));
2727
2728         status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2729                                       conn->samr_pipe->desthost,
2730                                       SEC_FLAG_MAXIMUM_ALLOWED,
2731                                       &conn->sam_connect_handle,
2732                                       &result);
2733         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2734                 goto open_domain;
2735         }
2736         if (NT_STATUS_IS_OK(status)) {
2737                 status = result;
2738         }
2739
2740         DEBUG(10,("cm_connect_sam: ntlmssp-sealed dcerpc_samr_Connect2 "
2741                   "failed for domain %s, error was %s. Trying schannel\n",
2742                   domain->name, nt_errstr(status) ));
2743         TALLOC_FREE(conn->samr_pipe);
2744
2745  schannel:
2746
2747         /* Fall back to schannel if it's a W2K pre-SP1 box. */
2748
2749         status = cm_get_schannel_creds(domain, &p_creds);
2750         if (!NT_STATUS_IS_OK(status)) {
2751                 /* If this call fails - conn->cli can now be NULL ! */
2752                 DEBUG(10, ("cm_connect_sam: Could not get schannel auth info "
2753                            "for domain %s (error %s), trying anon\n",
2754                         domain->name,
2755                         nt_errstr(status) ));
2756                 goto anonymous;
2757         }
2758         status = cli_rpc_pipe_open_schannel_with_key
2759                 (conn->cli, &ndr_table_samr, NCACN_NP,
2760                  domain->name, p_creds, &conn->samr_pipe);
2761
2762         if (!NT_STATUS_IS_OK(status)) {
2763                 DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
2764                           "domain %s using schannel. Error was %s\n",
2765                           domain->name, nt_errstr(status) ));
2766                 goto anonymous;
2767         }
2768         DEBUG(10,("cm_connect_sam: connected to SAMR pipe for domain %s using "
2769                   "schannel.\n", domain->name ));
2770
2771         status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2772                                       conn->samr_pipe->desthost,
2773                                       SEC_FLAG_MAXIMUM_ALLOWED,
2774                                       &conn->sam_connect_handle,
2775                                       &result);
2776         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
2777                 goto open_domain;
2778         }
2779         if (NT_STATUS_IS_OK(status)) {
2780                 status = result;
2781         }
2782         DEBUG(10,("cm_connect_sam: schannel-sealed dcerpc_samr_Connect2 failed "
2783                   "for domain %s, error was %s. Trying anonymous\n",
2784                   domain->name, nt_errstr(status) ));
2785         TALLOC_FREE(conn->samr_pipe);
2786
2787  anonymous:
2788
2789         /* Finally fall back to anonymous. */
2790         if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
2791                 status = NT_STATUS_DOWNGRADE_DETECTED;
2792                 DEBUG(1, ("Unwilling to make SAMR connection to domain %s"
2793                           "without connection level security, "
2794                           "must set 'winbind sealed pipes = false' and "
2795                           "'require strong key = false' to proceed: %s\n",
2796                           domain->name, nt_errstr(status)));
2797                 goto done;
2798         }
2799         status = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr,
2800                                           &conn->samr_pipe);
2801
2802         if (!NT_STATUS_IS_OK(status)) {
2803                 goto done;
2804         }
2805
2806         status = dcerpc_samr_Connect2(conn->samr_pipe->binding_handle, mem_ctx,
2807                                       conn->samr_pipe->desthost,
2808                                       SEC_FLAG_MAXIMUM_ALLOWED,
2809                                       &conn->sam_connect_handle,
2810                                       &result);
2811         if (!NT_STATUS_IS_OK(status)) {
2812                 DEBUG(10,("cm_connect_sam: rpccli_samr_Connect2 failed "
2813                           "for domain %s Error was %s\n",
2814                           domain->name, nt_errstr(status) ));
2815                 goto done;
2816         }
2817         if (!NT_STATUS_IS_OK(result)) {
2818                 status = result;
2819                 DEBUG(10,("cm_connect_sam: dcerpc_samr_Connect2 failed "
2820                           "for domain %s Error was %s\n",
2821                           domain->name, nt_errstr(result)));
2822                 goto done;
2823         }
2824
2825  open_domain:
2826         status = dcerpc_samr_OpenDomain(conn->samr_pipe->binding_handle,
2827                                         mem_ctx,
2828                                         &conn->sam_connect_handle,
2829                                         SEC_FLAG_MAXIMUM_ALLOWED,
2830                                         &domain->sid,
2831                                         &conn->sam_domain_handle,
2832                                         &result);
2833         if (!NT_STATUS_IS_OK(status)) {
2834                 goto done;
2835         }
2836
2837         status = result;
2838  done:
2839
2840         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
2841                 /*
2842                  * if we got access denied, we might just have no access rights
2843                  * to talk to the remote samr server server (e.g. when we are a
2844                  * PDC and we are connecting a w2k8 pdc via an interdomain
2845                  * trust). In that case do not invalidate the whole connection
2846                  * stack
2847                  */
2848                 TALLOC_FREE(conn->samr_pipe);
2849                 ZERO_STRUCT(conn->sam_domain_handle);
2850                 return status;
2851         } else if (!NT_STATUS_IS_OK(status)) {
2852                 invalidate_cm_connection(domain);
2853                 return status;
2854         }
2855
2856         *cli = conn->samr_pipe;
2857         *sam_handle = conn->sam_domain_handle;
2858         return status;
2859 }
2860
2861 /**********************************************************************
2862  open an schanneld ncacn_ip_tcp connection to LSA
2863 ***********************************************************************/
2864
2865 static NTSTATUS cm_connect_lsa_tcp(struct winbindd_domain *domain,
2866                                    TALLOC_CTX *mem_ctx,
2867                                    struct rpc_pipe_client **cli)
2868 {
2869         struct winbindd_cm_conn *conn;
2870         struct netlogon_creds_cli_context *creds;
2871         NTSTATUS status;
2872
2873         DEBUG(10,("cm_connect_lsa_tcp\n"));
2874
2875         status = init_dc_connection_rpc(domain, false);
2876         if (!NT_STATUS_IS_OK(status)) {
2877                 return status;
2878         }
2879
2880         conn = &domain->conn;
2881
2882         if (conn->lsa_pipe_tcp &&
2883             conn->lsa_pipe_tcp->transport->transport == NCACN_IP_TCP &&
2884             conn->lsa_pipe_tcp->auth->auth_level >= DCERPC_AUTH_LEVEL_INTEGRITY &&
2885             rpccli_is_connected(conn->lsa_pipe_tcp)) {
2886                 goto done;
2887         }
2888
2889         TALLOC_FREE(conn->lsa_pipe_tcp);
2890
2891         status = cm_get_schannel_creds(domain, &creds);
2892         if (!NT_STATUS_IS_OK(status)) {
2893                 goto done;
2894         }
2895
2896         status = cli_rpc_pipe_open_schannel_with_key(conn->cli,
2897                                                      &ndr_table_lsarpc,
2898                                                      NCACN_IP_TCP,
2899                                                      domain->name,
2900                                                      creds,
2901                                                      &conn->lsa_pipe_tcp);
2902         if (!NT_STATUS_IS_OK(status)) {
2903                 DEBUG(10,("cli_rpc_pipe_open_schannel_with_key failed: %s\n",
2904                         nt_errstr(status)));
2905                 goto done;
2906         }
2907
2908  done:
2909         if (!NT_STATUS_IS_OK(status)) {
2910                 TALLOC_FREE(conn->lsa_pipe_tcp);
2911                 return status;
2912         }
2913
2914         *cli = conn->lsa_pipe_tcp;
2915
2916         return status;
2917 }
2918
2919 NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
2920                         struct rpc_pipe_client **cli, struct policy_handle *lsa_policy)
2921 {
2922         struct winbindd_cm_conn *conn;
2923         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2924         struct netlogon_creds_cli_context *p_creds;
2925         struct cli_credentials *creds = NULL;
2926
2927         result = init_dc_connection_rpc(domain, false);
2928         if (!NT_STATUS_IS_OK(result))
2929                 return result;
2930
2931         conn = &domain->conn;
2932
2933         if (rpccli_is_connected(conn->lsa_pipe)) {
2934                 goto done;
2935         }
2936
2937         TALLOC_FREE(conn->lsa_pipe);
2938
2939         result = get_trust_credentials(domain, talloc_tos(), false, &creds);
2940         if (!NT_STATUS_IS_OK(result)) {
2941                 DEBUG(10, ("cm_connect_sam: No no user available for "
2942                            "domain %s, trying schannel\n", domain->name));
2943                 goto schannel;
2944         }
2945
2946         if (cli_credentials_is_anonymous(creds)) {
2947                 goto anonymous;
2948         }
2949
2950         /*
2951          * We have an authenticated connection. Use a SPNEGO
2952          * authenticated LSA pipe with sign & seal.
2953          */
2954         result = cli_rpc_pipe_open_with_creds
2955                 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
2956                  DCERPC_AUTH_TYPE_SPNEGO,
2957                  conn->auth_level,
2958                  smbXcli_conn_remote_name(conn->cli->conn),
2959                  creds,
2960                  &conn->lsa_pipe);
2961         if (!NT_STATUS_IS_OK(result)) {
2962                 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
2963                           "domain %s using NTLMSSP authenticated pipe: user "
2964                           "%s. Error was %s. Trying schannel.\n",
2965                           domain->name,
2966                           cli_credentials_get_unparsed_name(creds, talloc_tos()),
2967                           nt_errstr(result)));
2968                 goto schannel;
2969         }
2970
2971         DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
2972                   "NTLMSSP authenticated pipe: user %s\n",
2973                   domain->name, cli_credentials_get_unparsed_name(creds, talloc_tos())));
2974
2975         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
2976                                         SEC_FLAG_MAXIMUM_ALLOWED,
2977                                         &conn->lsa_policy);
2978         if (NT_STATUS_IS_OK(result)) {
2979                 goto done;
2980         }
2981
2982         DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
2983                   "schannel\n"));
2984
2985         TALLOC_FREE(conn->lsa_pipe);
2986
2987  schannel:
2988
2989         /* Fall back to schannel if it's a W2K pre-SP1 box. */
2990
2991         result = cm_get_schannel_creds(domain, &p_creds);
2992         if (!NT_STATUS_IS_OK(result)) {
2993                 /* If this call fails - conn->cli can now be NULL ! */
2994                 DEBUG(10, ("cm_connect_lsa: Could not get schannel auth info "
2995                            "for domain %s (error %s), trying anon\n",
2996                         domain->name,
2997                         nt_errstr(result) ));
2998                 goto anonymous;
2999         }
3000         result = cli_rpc_pipe_open_schannel_with_key
3001                 (conn->cli, &ndr_table_lsarpc, NCACN_NP,
3002                  domain->name, p_creds, &conn->lsa_pipe);
3003
3004         if (!NT_STATUS_IS_OK(result)) {
3005                 DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
3006                           "domain %s using schannel. Error was %s\n",
3007                           domain->name, nt_errstr(result) ));
3008                 goto anonymous;
3009         }
3010         DEBUG(10,("cm_connect_lsa: connected to LSA pipe for domain %s using "
3011                   "schannel.\n", domain->name ));
3012
3013         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3014                                         SEC_FLAG_MAXIMUM_ALLOWED,
3015                                         &conn->lsa_policy);
3016         if (NT_STATUS_IS_OK(result)) {
3017                 goto done;
3018         }
3019
3020         DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
3021                   "anonymous\n"));
3022
3023         TALLOC_FREE(conn->lsa_pipe);
3024
3025  anonymous:
3026
3027         if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3028                 result = NT_STATUS_DOWNGRADE_DETECTED;
3029                 DEBUG(1, ("Unwilling to make LSA connection to domain %s"
3030                           "without connection level security, "
3031                           "must set 'winbind sealed pipes = false' and "
3032                           "'require strong key = false' to proceed: %s\n",
3033                           domain->name, nt_errstr(result)));
3034                 goto done;
3035         }
3036
3037         result = cli_rpc_pipe_open_noauth(conn->cli,
3038                                           &ndr_table_lsarpc,
3039                                           &conn->lsa_pipe);
3040         if (!NT_STATUS_IS_OK(result)) {
3041                 goto done;
3042         }
3043
3044         result = rpccli_lsa_open_policy(conn->lsa_pipe, mem_ctx, True,
3045                                         SEC_FLAG_MAXIMUM_ALLOWED,
3046                                         &conn->lsa_policy);
3047  done:
3048         if (!NT_STATUS_IS_OK(result)) {
3049                 invalidate_cm_connection(domain);
3050                 return result;
3051         }
3052
3053         *cli = conn->lsa_pipe;
3054         *lsa_policy = conn->lsa_policy;
3055         return result;
3056 }
3057
3058 /****************************************************************************
3059 Open a LSA connection to a DC, suiteable for LSA lookup calls.
3060 ****************************************************************************/
3061
3062 NTSTATUS cm_connect_lsat(struct winbindd_domain *domain,
3063                          TALLOC_CTX *mem_ctx,
3064                          struct rpc_pipe_client **cli,
3065                          struct policy_handle *lsa_policy)
3066 {
3067         NTSTATUS status;
3068
3069         if (domain->can_do_ncacn_ip_tcp) {
3070                 status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3071                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3072                     NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3073                     NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3074                         invalidate_cm_connection(domain);
3075                         status = cm_connect_lsa_tcp(domain, mem_ctx, cli);
3076                 }
3077                 if (NT_STATUS_IS_OK(status)) {
3078                         return status;
3079                 }
3080
3081                 /*
3082                  * we tried twice to connect via ncan_ip_tcp and schannel and
3083                  * failed - maybe it is a trusted domain we can't connect to ?
3084                  * do not try tcp next time - gd
3085                  *
3086                  * This also prevents NETLOGON over TCP
3087                  */
3088                 domain->can_do_ncacn_ip_tcp = false;
3089         }
3090
3091         status = cm_connect_lsa(domain, mem_ctx, cli, lsa_policy);
3092
3093         return status;
3094 }
3095
3096 /****************************************************************************
3097  Open the netlogon pipe to this DC. Use schannel if specified in client conf.
3098  session key stored in conn->netlogon_pipe->dc->sess_key.
3099 ****************************************************************************/
3100
3101 static NTSTATUS cm_connect_netlogon_transport(struct winbindd_domain *domain,
3102                                               enum dcerpc_transport_t transport,
3103                                               struct rpc_pipe_client **cli)
3104 {
3105         struct messaging_context *msg_ctx = winbind_messaging_context();
3106         struct winbindd_cm_conn *conn;
3107         NTSTATUS result;
3108         enum netr_SchannelType sec_chan_type;
3109         const char *account_name;
3110         const char *domain_name;
3111         const struct samr_Password *current_nt_hash = NULL;
3112         const struct samr_Password *previous_nt_hash = NULL;
3113         struct netlogon_creds_CredentialState *netlogon_creds = NULL;
3114         struct cli_credentials *creds = NULL;
3115
3116         *cli = NULL;
3117
3118         result = init_dc_connection_rpc(domain, true);
3119         if (!NT_STATUS_IS_OK(result)) {
3120                 return result;
3121         }
3122
3123         conn = &domain->conn;
3124
3125         if (rpccli_is_connected(conn->netlogon_pipe)) {
3126                 *cli = conn->netlogon_pipe;
3127                 return NT_STATUS_OK;
3128         }
3129
3130         TALLOC_FREE(conn->netlogon_pipe);
3131         conn->netlogon_flags = 0;
3132         TALLOC_FREE(conn->netlogon_creds);
3133
3134         result = get_trust_credentials(domain, talloc_tos(), true, &creds);
3135         if (!NT_STATUS_IS_OK(result)) {
3136                 DEBUG(10, ("cm_connect_sam: No no user available for "
3137                            "domain %s when trying schannel\n", domain->name));
3138                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3139         }
3140
3141         if (cli_credentials_is_anonymous(creds)) {
3142                 DEBUG(1, ("get_trust_credential only gave anonymous for %s, unable to make get NETLOGON credentials\n",
3143                           domain->name));
3144                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3145         }
3146
3147         sec_chan_type = cli_credentials_get_secure_channel_type(creds);
3148         if (sec_chan_type == SEC_CHAN_NULL) {
3149                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
3150                 goto no_schannel;
3151         }
3152
3153         account_name = cli_credentials_get_username(creds);
3154         domain_name = cli_credentials_get_domain(creds);
3155         current_nt_hash = cli_credentials_get_nt_hash(creds, talloc_tos());
3156         if (current_nt_hash == NULL) {
3157                 return NT_STATUS_NO_MEMORY;
3158         }
3159
3160         result = rpccli_create_netlogon_creds(domain->dcname,
3161                                               domain_name,
3162                                               account_name,
3163                                               sec_chan_type,
3164                                               msg_ctx,
3165                                               domain,
3166                                               &conn->netlogon_creds);
3167         if (!NT_STATUS_IS_OK(result)) {
3168                 DEBUG(1, ("rpccli_create_netlogon_creds failed for %s, "
3169                           "unable to create NETLOGON credentials: %s\n",
3170                           domain->name, nt_errstr(result)));
3171                 return result;
3172         }
3173
3174         result = rpccli_setup_netlogon_creds(conn->cli, transport,
3175                                              conn->netlogon_creds,
3176                                              conn->netlogon_force_reauth,
3177                                              *current_nt_hash,
3178                                              previous_nt_hash);
3179         conn->netlogon_force_reauth = false;
3180         if (!NT_STATUS_IS_OK(result)) {
3181                 DEBUG(1, ("rpccli_setup_netlogon_creds failed for %s, "
3182                           "unable to setup NETLOGON credentials: %s\n",
3183                           domain->name, nt_errstr(result)));
3184                 return result;
3185         }
3186
3187         result = netlogon_creds_cli_get(conn->netlogon_creds,
3188                                         talloc_tos(),
3189                                         &netlogon_creds);
3190         if (!NT_STATUS_IS_OK(result)) {
3191                 DEBUG(1, ("netlogon_creds_cli_get failed for %s, "
3192                           "unable to get NETLOGON credentials: %s\n",
3193                           domain->name, nt_errstr(result)));
3194                 return result;
3195         }
3196         conn->netlogon_flags = netlogon_creds->negotiate_flags;
3197         TALLOC_FREE(netlogon_creds);
3198
3199  no_schannel:
3200         if (!(conn->netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
3201                 if (lp_winbind_sealed_pipes() || lp_require_strong_key()) {
3202                         result = NT_STATUS_DOWNGRADE_DETECTED;
3203                         DEBUG(1, ("Unwilling to make connection to domain %s"
3204                                   "without connection level security, "
3205                                   "must set 'winbind sealed pipes = false' and "
3206                                   "'require strong key = false' to proceed: %s\n",
3207                                   domain->name, nt_errstr(result)));
3208                         invalidate_cm_connection(domain);
3209                         return result;
3210                 }
3211                 result = cli_rpc_pipe_open_noauth_transport(conn->cli,
3212                                                             transport,
3213                                                             &ndr_table_netlogon,
3214                                                             &conn->netlogon_pipe);
3215                 if (!NT_STATUS_IS_OK(result)) {
3216                         invalidate_cm_connection(domain);
3217                         return result;
3218                 }
3219
3220                 *cli = conn->netlogon_pipe;
3221                 return NT_STATUS_OK;
3222         }
3223
3224         /* Using the credentials from the first pipe, open a signed and sealed
3225            second netlogon pipe. The session key is stored in the schannel
3226            part of the new pipe auth struct.
3227         */
3228
3229         result = cli_rpc_pipe_open_schannel_with_key(
3230                 conn->cli, &ndr_table_netlogon, transport,
3231                 domain->name,
3232                 conn->netlogon_creds,
3233                 &conn->netlogon_pipe);
3234         if (!NT_STATUS_IS_OK(result)) {
3235                 DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
3236                           "was %s\n", nt_errstr(result)));
3237
3238                 invalidate_cm_connection(domain);
3239                 return result;
3240         }
3241
3242         *cli = conn->netlogon_pipe;
3243         return NT_STATUS_OK;
3244 }
3245
3246 /****************************************************************************
3247 Open a LSA connection to a DC, suiteable for LSA lookup calls.
3248 ****************************************************************************/
3249
3250 NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
3251                              struct rpc_pipe_client **cli)
3252 {
3253         NTSTATUS status;
3254
3255         if (domain->active_directory && domain->can_do_ncacn_ip_tcp) {
3256                 status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3257                 if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) ||
3258                     NT_STATUS_EQUAL(status, NT_STATUS_RPC_SEC_PKG_ERROR) ||
3259                     NT_STATUS_EQUAL(status, NT_STATUS_NETWORK_ACCESS_DENIED)) {
3260                         invalidate_cm_connection(domain);
3261                         status = cm_connect_netlogon_transport(domain, NCACN_IP_TCP, cli);
3262                 }
3263                 if (NT_STATUS_IS_OK(status)) {
3264                         return status;
3265                 }
3266
3267                 /*
3268                  * we tried twice to connect via ncan_ip_tcp and schannel and
3269                  * failed - maybe it is a trusted domain we can't connect to ?
3270                  * do not try tcp next time - gd
3271                  *
3272                  * This also prevents LSA over TCP
3273                  */
3274                 domain->can_do_ncacn_ip_tcp = false;
3275         }
3276
3277         status = cm_connect_netlogon_transport(domain, NCACN_NP, cli);
3278
3279         return status;
3280 }
3281
3282 void winbind_msg_ip_dropped(struct messaging_context *msg_ctx,
3283                             void *private_data,
3284                             uint32_t msg_type,
3285                             struct server_id server_id,
3286                             DATA_BLOB *data)
3287 {
3288         struct winbindd_domain *domain;
3289         char *freeit = NULL;
3290         char *addr;
3291
3292         if ((data == NULL)
3293             || (data->data == NULL)
3294             || (data->length == 0)
3295             || (data->data[data->length-1] != '\0')) {
3296                 DEBUG(1, ("invalid msg_ip_dropped message: not a valid "
3297                           "string\n"));
3298                 return;
3299         }
3300
3301         addr = (char *)data->data;
3302         DEBUG(10, ("IP %s dropped\n", addr));
3303
3304         if (!is_ipaddress(addr)) {
3305                 char *slash;
3306                 /*
3307                  * Some code sends us ip addresses with the /netmask
3308                  * suffix
3309                  */
3310                 slash = strchr(addr, '/');
3311                 if (slash == NULL) {
3312                         DEBUG(1, ("invalid msg_ip_dropped message: %s",
3313                                   addr));
3314                         return;
3315                 }
3316                 freeit = talloc_strndup(talloc_tos(), addr, slash-addr);
3317                 if (freeit == NULL) {
3318                         DEBUG(1, ("talloc failed\n"));
3319                         return;
3320                 }
3321                 addr = freeit;
3322                 DEBUG(10, ("Stripped /netmask to IP %s\n", addr));
3323         }
3324
3325         for (domain = domain_list(); domain != NULL; domain = domain->next) {
3326                 char sockaddr[INET6_ADDRSTRLEN];
3327
3328                 if (!cli_state_is_connected(domain->conn.cli)) {
3329                         continue;
3330                 }
3331
3332                 print_sockaddr(sockaddr, sizeof(sockaddr),
3333                                smbXcli_conn_local_sockaddr(domain->conn.cli->conn));
3334
3335                 if (strequal(sockaddr, addr)) {
3336                         smbXcli_conn_disconnect(domain->conn.cli->conn, NT_STATUS_OK);
3337                 }
3338         }
3339         TALLOC_FREE(freeit);
3340 }