s3: Change sockaddr util function names for consistency
[samba.git] / source3 / winbindd / winbindd_cm.c
index 17afd1e3eb52d30c331b9871e33bec48add364c7..5f592fc6b7785b0d75533c2717c7d0e248e9026a 100644 (file)
@@ -8,17 +8,17 @@
    Copyright (C) Gerald (Jerry) Carter     2003-2005.
    Copyright (C) Volker Lendecke           2004-2005
    Copyright (C) Jeremy Allison                   2006
-   
+
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
-   
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.         See the
    GNU General Public License for more details.
-   
+
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
    We need to manage connections to domain controllers without having to
    mess up the main winbindd code with other issues.  The aim of the
    connection manager is to:
-  
+
        - make connections to domain controllers and cache them
        - re-establish connections when networks or servers go down
        - centralise the policy on connection timeouts, domain controller
         selection etc
        - manage re-entrancy for when winbindd becomes able to handle
         multiple outstanding rpc requests
-  
+
    Why not have connection management as part of the rpc layer like tng?
    Good question.  This code may morph into libsmb/rpc_cache.c or something
    like that but at the moment it's simply staying as part of winbind. I
@@ -171,20 +171,33 @@ static bool fork_child_dc_connect(struct winbindd_domain *domain)
        struct dc_name_ip *dcs = NULL;
        int num_dcs = 0;
        TALLOC_CTX *mem_ctx = NULL;
-       pid_t child_pid;
        pid_t parent_pid = sys_getpid();
 
        /* Stop zombies */
        CatchChild();
 
-       child_pid = sys_fork();
+       if (domain->dc_probe_pid != (pid_t)-1) {
+               /*
+                * We might already have a DC probe
+                * child working, check.
+                */
+               if (process_exists_by_pid(domain->dc_probe_pid)) {
+                       DEBUG(10,("fork_child_dc_connect: pid %u already "
+                               "checking for DC's.\n",
+                               (unsigned int)domain->dc_probe_pid));
+                       return true;
+               }
+               domain->dc_probe_pid = (pid_t)-1;
+       }
+
+       domain->dc_probe_pid = sys_fork();
 
-       if (child_pid == -1) {
+       if (domain->dc_probe_pid == (pid_t)-1) {
                DEBUG(0, ("fork_child_dc_connect: Could not fork: %s\n", strerror(errno)));
                return False;
        }
 
-       if (child_pid != 0) {
+       if (domain->dc_probe_pid != (pid_t)0) {
                /* Parent */
                messaging_register(winbind_messaging_context(), NULL,
                                   MSG_WINBIND_TRY_TO_GO_ONLINE,
@@ -199,19 +212,23 @@ static bool fork_child_dc_connect(struct winbindd_domain *domain)
 
        /* Leave messages blocked - we will never process one. */
 
-       /* tdb needs special fork handling */
-       if (tdb_reopen_all(1) == -1) {
-               DEBUG(0,("tdb_reopen_all failed.\n"));
+       if (!reinit_after_fork(winbind_messaging_context(), true)) {
+               DEBUG(0,("reinit_after_fork() failed\n"));
+               messaging_send_buf(winbind_messaging_context(),
+                                  pid_to_procid(parent_pid),
+                                  MSG_WINBIND_FAILED_TO_GO_ONLINE,
+                                  (uint8 *)domain->name,
+                                  strlen(domain->name)+1);
                _exit(0);
        }
 
        close_conns_after_fork();
 
        if (!override_logfile) {
-               char *logfile;
-               if (asprintf(&logfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) > 0) {
-                       lp_set_logfile(logfile);
-                       SAFE_FREE(logfile);
+               char *lfile;
+               if (asprintf(&lfile, "%s/log.winbindd-dc-connect", get_dyn_LOGFILEBASE()) > 0) {
+                       lp_set_logfile(lfile);
+                       SAFE_FREE(lfile);
                        reopen_logs();
                }
        }
@@ -219,6 +236,11 @@ static bool fork_child_dc_connect(struct winbindd_domain *domain)
        mem_ctx = talloc_init("fork_child_dc_connect");
        if (!mem_ctx) {
                DEBUG(0,("talloc_init failed.\n"));
+               messaging_send_buf(winbind_messaging_context(),
+                                  pid_to_procid(parent_pid),
+                                  MSG_WINBIND_FAILED_TO_GO_ONLINE,
+                                  (uint8 *)domain->name,
+                                  strlen(domain->name)+1);
                _exit(0);
        }
 
@@ -292,12 +314,12 @@ static void check_domain_online_handler(struct event_context *ctx,
 
 static void calc_new_online_timeout_check(struct winbindd_domain *domain)
 {
-       int wbc = lp_winbind_cache_time();
+       int wbr = lp_winbind_reconnect_delay();
 
        if (domain->startup) {
                domain->check_online_timeout = 10;
-       } else if (domain->check_online_timeout < wbc) {
-               domain->check_online_timeout = wbc;
+       } else if (domain->check_online_timeout < wbr) {
+               domain->check_online_timeout = wbr;
        }
 }
 
@@ -337,7 +359,7 @@ void set_domain_offline(struct winbindd_domain *domain)
        }
 
        /* If we're in statup mode, check again in 10 seconds, not in
-          lp_winbind_cache_time() seconds (which is 5 mins by default). */
+          lp_winbind_reconnect_delay() seconds (which is 30 seconds by default). */
 
        calc_new_online_timeout_check(domain);
 
@@ -361,7 +383,7 @@ void set_domain_offline(struct winbindd_domain *domain)
 
        if ( domain->primary ) {
                struct winbindd_child *idmap = idmap_child();
-               
+
                if ( idmap->pid != 0 ) {
                        messaging_send_buf(winbind_messaging_context(),
                                           pid_to_procid(idmap->pid), 
@@ -440,7 +462,7 @@ static void set_domain_online(struct winbindd_domain *domain)
 
        if ( domain->primary ) {
                struct winbindd_child *idmap = idmap_child();
-               
+
                if ( idmap->pid != 0 ) {
                        messaging_send_buf(winbind_messaging_context(),
                                           pid_to_procid(idmap->pid), 
@@ -531,7 +553,7 @@ void winbind_add_failed_connection_entry(const struct winbindd_domain *domain,
    an authenticated connection if DCs have the RestrictAnonymous registry
    entry set > 0, or the "Additional restrictions for anonymous
    connections" set in the win2k Local Security Policy. 
-   
+
    Caller to free() result in domain, username, password
 */
 
@@ -540,12 +562,12 @@ static void cm_get_ipc_userpass(char **username, char **domain, char **password)
        *username = (char *)secrets_fetch(SECRETS_AUTH_USER, NULL);
        *domain = (char *)secrets_fetch(SECRETS_AUTH_DOMAIN, NULL);
        *password = (char *)secrets_fetch(SECRETS_AUTH_PASSWORD, NULL);
-       
+
        if (*username && **username) {
 
                if (!*domain || !**domain)
                        *domain = smb_xstrdup(lp_workgroup());
-               
+
                if (!*password || !**password)
                        *password = smb_xstrdup("");
 
@@ -599,22 +621,23 @@ static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
        /* This call can take a long time - allow the server to time out.
           35 seconds should do it. */
 
-       orig_timeout = cli_set_timeout(netlogon_pipe->cli, 35000);
+       orig_timeout = rpccli_set_timeout(netlogon_pipe, 35000);
 
        if (our_domain->active_directory) {
-               struct DS_DOMAIN_CONTROLLER_INFO *domain_info = NULL;
-
-               werr = rpccli_netlogon_dsr_getdcname(netlogon_pipe,
-                                                    mem_ctx,
-                                                    our_domain->dcname,
-                                                    domain->name,
-                                                    NULL,
-                                                    NULL,
-                                                    DS_RETURN_DNS_NAME,
-                                                    &domain_info);
+               struct netr_DsRGetDCNameInfo *domain_info = NULL;
+
+               result = rpccli_netr_DsRGetDCName(netlogon_pipe,
+                                                 mem_ctx,
+                                                 our_domain->dcname,
+                                                 domain->name,
+                                                 NULL,
+                                                 NULL,
+                                                 DS_RETURN_DNS_NAME,
+                                                 &domain_info,
+                                                 &werr);
                if (W_ERROR_IS_OK(werr)) {
                        tmp = talloc_strdup(
-                               mem_ctx, domain_info->domain_controller_name);
+                               mem_ctx, domain_info->dc_unc);
                        if (tmp == NULL) {
                                DEBUG(0, ("talloc_strdup failed\n"));
                                talloc_destroy(mem_ctx);
@@ -626,7 +649,7 @@ static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
                        }
                        if (strlen(domain->forest_name) == 0) {
                                fstrcpy(domain->forest_name,
-                                       domain_info->dns_forest_name);
+                                       domain_info->forest_name);
                        }
                }
        } else {
@@ -638,7 +661,7 @@ static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
        }
 
        /* And restore our original timeout. */
-       cli_set_timeout(netlogon_pipe->cli, orig_timeout);
+       rpccli_set_timeout(netlogon_pipe, orig_timeout);
 
        if (!NT_STATUS_IS_OK(result)) {
                DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
@@ -649,19 +672,13 @@ static bool get_dc_name_via_netlogon(struct winbindd_domain *domain,
 
        if (!W_ERROR_IS_OK(werr)) {
                DEBUG(10,("rpccli_netr_GetAnyDCName failed: %s\n",
-                          dos_errstr(werr)));
+                          win_errstr(werr)));
                talloc_destroy(mem_ctx);
                return false;
        }
 
        /* rpccli_netr_GetAnyDCName gives us a name with \\ */
-       p = tmp;
-       if (*p == '\\') {
-               p+=1;
-       }
-       if (*p == '\\') {
-               p+=1;
-       }
+       p = strip_hostname(tmp);
 
        fstrcpy(dcname, p);
 
@@ -686,7 +703,7 @@ static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
 {
        const char *account_name;
        const char *name = NULL;
-       
+
        /* If we are a DC and this is not our own domain */
 
        if (IS_DC) {
@@ -696,10 +713,10 @@ static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
 
                if (!our_domain)
                        return NT_STATUS_INVALID_SERVER_STATE;          
-               
+
                name = our_domain->name;                
        }       
-       
+
        if (!get_trust_pw_clear(name, machine_password,
                                &account_name, NULL))
        {
@@ -712,12 +729,18 @@ static NTSTATUS get_trust_creds(const struct winbindd_domain *domain,
                return NT_STATUS_NO_MEMORY;
        }
 
-       /* this is at least correct when domain is our domain,
-        * which is the only case, when this is currently used: */
+       /* For now assume our machine account only exists in our domain */
+
        if (machine_krb5_principal != NULL)
        {
+               struct winbindd_domain *our_domain = find_our_domain();
+
+               if (!our_domain) {
+                       return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;                       
+               }
+
                if (asprintf(machine_krb5_principal, "%s$@%s",
-                            account_name, domain->alt_name) == -1)
+                            account_name, our_domain->alt_name) == -1)
                {
                        return NT_STATUS_NO_MEMORY;
                }
@@ -746,7 +769,7 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
        char *ipc_domain = NULL;
        char *ipc_password = NULL;
 
-       bool got_mutex;
+       struct named_mutex *mutex;
 
        NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
 
@@ -760,10 +783,9 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
 
        *retry = True;
 
-       got_mutex = secrets_named_mutex(controller,
-                                       WINBIND_SERVER_MUTEX_WAIT_TIME);
-
-       if (!got_mutex) {
+       mutex = grab_named_mutex(talloc_tos(), controller,
+                                WINBIND_SERVER_MUTEX_WAIT_TIME);
+       if (mutex == NULL) {
                DEBUG(0,("cm_prepare_connection: mutex grab failed for %s\n",
                         controller));
                result = NT_STATUS_POSSIBLE_DEADLOCK;
@@ -815,7 +837,7 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
                goto done;
        }
 
-       if (!is_trusted_domain_situation(domain->name) &&
+       if (!is_dc_trusted_domain_situation(domain->name) &&
            (*cli)->protocol >= PROTOCOL_NT1 &&
            (*cli)->capabilities & CAP_EXTENDED_SECURITY)
        {
@@ -825,7 +847,7 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
                                         &machine_account,
                                         &machine_krb5_principal);
                if (!NT_STATUS_IS_OK(result)) {
-                       goto done;
+                       goto anon_fallback;
                }
 
                if (lp_security() == SEC_ADS) {
@@ -834,14 +856,15 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
 
                        (*cli)->use_kerberos = True;
                        DEBUG(5, ("connecting to %s from %s with kerberos principal "
-                                 "[%s]\n", controller, global_myname(),
-                                 machine_krb5_principal));
+                                 "[%s] and realm [%s]\n", controller, global_myname(),
+                                 machine_krb5_principal, domain->alt_name));
 
                        winbindd_set_locator_kdc_envs(domain);
 
                        ads_status = cli_session_setup_spnego(*cli,
                                                              machine_krb5_principal, 
-                                                             machine_password, 
+                                                             machine_password,
+                                                             lp_workgroup(),
                                                              domain->name);
 
                        if (!ADS_ERR_OK(ads_status)) {
@@ -852,7 +875,7 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
                        result = ads_ntstatus(ads_status);
                        if (NT_STATUS_IS_OK(result)) {
                                /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
-                               cli_init_creds(*cli, machine_account, domain->name, machine_password);
+                               cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
                                goto session_setup_done;
                        }
                }
@@ -862,12 +885,13 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
 
                DEBUG(5, ("connecting to %s from %s with username "
                          "[%s]\\[%s]\n",  controller, global_myname(),
-                         domain->name, machine_account));
+                         lp_workgroup(), machine_account));
 
                ads_status = cli_session_setup_spnego(*cli,
                                                      machine_account, 
                                                      machine_password, 
-                                                     domain->name);
+                                                     lp_workgroup(),
+                                                     NULL);
                if (!ADS_ERR_OK(ads_status)) {
                        DEBUG(4, ("authenticated session setup failed with %s\n",
                                ads_errstr(ads_status)));
@@ -876,7 +900,7 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
                result = ads_ntstatus(ads_status);
                if (NT_STATUS_IS_OK(result)) {
                        /* Ensure creds are stored for NTLMSSP authenticated pipe access. */
-                       cli_init_creds(*cli, machine_account, domain->name, machine_password);
+                       cli_init_creds(*cli, machine_account, lp_workgroup(), machine_password);
                        goto session_setup_done;
                }
        }
@@ -910,7 +934,12 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
                }
        }
 
+ anon_fallback:
+
        /* Fall back to anonymous connection, this might fail later */
+       DEBUG(10,("cm_prepare_connection: falling back to anonymous "
+               "connection for DC %s\n",
+               controller ));
 
        if (NT_STATUS_IS_OK(cli_session_setup(*cli, "", NULL, 0,
                                              NULL, 0, ""))) {
@@ -951,8 +980,7 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
                goto done;
        }
 
-       secrets_named_mutex_release(controller);
-       got_mutex = False;
+       TALLOC_FREE(mutex);
        *retry = False;
 
        /* set the domain if empty; needed for schannel connections */
@@ -963,10 +991,7 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
        result = NT_STATUS_OK;
 
  done:
-       if (got_mutex) {
-               secrets_named_mutex_release(controller);
-       }
-
+       TALLOC_FREE(mutex);
        SAFE_FREE(machine_account);
        SAFE_FREE(machine_password);
        SAFE_FREE(machine_krb5_principal);
@@ -985,15 +1010,37 @@ static NTSTATUS cm_prepare_connection(const struct winbindd_domain *domain,
        return result;
 }
 
+/*******************************************************************
+ Add a dcname and sockaddr_storage pair to the end of a dc_name_ip
+ array.
+
+ Keeps the list unique by not adding duplicate entries.
+
+ @param[in] mem_ctx talloc memory context to allocate from
+ @param[in] domain_name domain of the DC
+ @param[in] dcname name of the DC to add to the list
+ @param[in] pss Internet address and port pair to add to the list
+ @param[in,out] dcs array of dc_name_ip structures to add to
+ @param[in,out] num_dcs number of dcs returned in the dcs array
+ @return true if the list was added to, false otherwise
+*******************************************************************/
+
 static bool add_one_dc_unique(TALLOC_CTX *mem_ctx, const char *domain_name,
                              const char *dcname, struct sockaddr_storage *pss,
                              struct dc_name_ip **dcs, int *num)
 {
+       int i = 0;
+
        if (!NT_STATUS_IS_OK(check_negative_conn_cache(domain_name, dcname))) {
                DEBUG(10, ("DC %s was in the negative conn cache\n", dcname));
                return False;
        }
 
+       /* Make sure there's no duplicates in the list */
+       for (i=0; i<*num; i++)
+               if (sockaddr_equal((struct sockaddr *)&(*dcs)[i].ss, (struct sockaddr *)pss))
+                       return False;
+
        *dcs = TALLOC_REALLOC_ARRAY(mem_ctx, *dcs, struct dc_name_ip, (*num)+1);
 
        if (*dcs == NULL)
@@ -1017,179 +1064,23 @@ static bool add_sockaddr_to_array(TALLOC_CTX *mem_ctx,
        }
 
        (*addrs)[*num] = *pss;
-       set_sockaddr_port(&(*addrs)[*num], port);
+       set_sockaddr_port((struct sockaddr *)&(*addrs)[*num], port);
 
        *num += 1;
        return True;
 }
 
-static void mailslot_name(struct in_addr dc_ip, fstring name)
-{
-       fstr_sprintf(name, "\\MAILSLOT\\NET\\GETDC%X", dc_ip.s_addr);
-}
-
-static bool send_getdc_request(struct sockaddr_storage *dc_ss,
-                              const char *domain_name,
-                              const DOM_SID *sid)
-{
-       char outbuf[1024];
-       struct in_addr dc_ip;
-       char *p;
-       fstring my_acct_name;
-       fstring my_mailslot;
-       size_t sid_size;
-
-       if (dc_ss->ss_family != AF_INET) {
-               return false;
-       }
-
-       dc_ip = ((struct sockaddr_in *)dc_ss)->sin_addr;
-       mailslot_name(dc_ip, my_mailslot);
-
-       memset(outbuf, '\0', sizeof(outbuf));
-
-       p = outbuf;
-
-       SCVAL(p, 0, SAMLOGON);
-       p++;
-
-       SCVAL(p, 0, 0); /* Count pointer ... */
-       p++;
-
-       SIVAL(p, 0, 0); /* The sender's token ... */
-       p += 2;
-
-       p += dos_PutUniCode(p, global_myname(),
-                       sizeof(outbuf) - PTR_DIFF(p, outbuf), True);
-       fstr_sprintf(my_acct_name, "%s$", global_myname());
-       p += dos_PutUniCode(p, my_acct_name,
-                       sizeof(outbuf) - PTR_DIFF(p, outbuf), True);
-
-       if (strlen(my_mailslot)+1 > sizeof(outbuf) - PTR_DIFF(p, outbuf)) {
-               return false;
-       }
-
-       memcpy(p, my_mailslot, strlen(my_mailslot)+1);
-       p += strlen(my_mailslot)+1;
-
-       if (sizeof(outbuf) - PTR_DIFF(p, outbuf) < 8) {
-               return false;
-       }
-
-       SIVAL(p, 0, 0x80);
-       p+=4;
-
-       sid_size = ndr_size_dom_sid(sid, 0);
-
-       SIVAL(p, 0, sid_size);
-       p+=4;
-
-       p = ALIGN4(p, outbuf);
-       if (PTR_DIFF(p, outbuf) > sizeof(outbuf)) {
-               return false;
-       }
-
-       if (sid_size + 8 > sizeof(outbuf) - PTR_DIFF(p, outbuf)) {
-               return false;
-       }
-       sid_linearize(p, sizeof(outbuf) - PTR_DIFF(p, outbuf), sid);
-
-       p += sid_size;
-
-       SIVAL(p, 0, 1);
-       SSVAL(p, 4, 0xffff);
-       SSVAL(p, 6, 0xffff);
-       p+=8;
-
-       return cli_send_mailslot(winbind_messaging_context(),
-                                False, "\\MAILSLOT\\NET\\NTLOGON", 0,
-                                outbuf, PTR_DIFF(p, outbuf),
-                                global_myname(), 0, domain_name, 0x1c,
-                                dc_ss);
-}
-
-static bool receive_getdc_response(struct sockaddr_storage *dc_ss,
-                                  const char *domain_name,
-                                  fstring dc_name)
-{
-       struct packet_struct *packet;
-       fstring my_mailslot;
-       char *buf, *p;
-       fstring dcname, user, domain;
-       int len;
-       struct in_addr dc_ip;
-
-       if (dc_ss->ss_family != AF_INET) {
-               return false;
-       }
-       dc_ip = ((struct sockaddr_in *)dc_ss)->sin_addr;
-       mailslot_name(dc_ip, my_mailslot);
-
-       packet = receive_unexpected(DGRAM_PACKET, 0, my_mailslot);
-
-       if (packet == NULL) {
-               DEBUG(5, ("Did not receive packet for %s\n", my_mailslot));
-               return False;
-       }
-
-       DEBUG(5, ("Received packet for %s\n", my_mailslot));
-
-       buf = packet->packet.dgram.data;
-       len = packet->packet.dgram.datasize;
-
-       if (len < 70) {
-               /* 70 is a completely arbitrary value to make sure
-                  the SVAL below does not read uninitialized memory */
-               DEBUG(3, ("GetDC got short response\n"));
-               return False;
-       }
-
-       /* This should be (buf-4)+SVAL(buf-4, smb_vwv12)... */
-       p = buf+SVAL(buf, smb_vwv10);
-
-       if (CVAL(p,0) != SAMLOGON_R) {
-               DEBUG(8, ("GetDC got invalid response type %d\n", CVAL(p, 0)));
-               return False;
-       }
-
-       p+=2;
-       pull_ucs2(buf, dcname, p, sizeof(dcname), PTR_DIFF(buf+len, p),
-                 STR_TERMINATE|STR_NOALIGN);
-       p = skip_unibuf(p, PTR_DIFF(buf+len, p));
-       pull_ucs2(buf, user, p, sizeof(dcname), PTR_DIFF(buf+len, p),
-                 STR_TERMINATE|STR_NOALIGN);
-       p = skip_unibuf(p, PTR_DIFF(buf+len, p));
-       pull_ucs2(buf, domain, p, sizeof(dcname), PTR_DIFF(buf+len, p),
-                 STR_TERMINATE|STR_NOALIGN);
-       p = skip_unibuf(p, PTR_DIFF(buf+len, p));
-
-       if (!strequal(domain, domain_name)) {
-               DEBUG(3, ("GetDC: Expected domain %s, got %s\n",
-                         domain_name, domain));
-               return False;
-       }
-
-       p = dcname;
-       if (*p == '\\') p += 1;
-       if (*p == '\\') p += 1;
-
-       fstrcpy(dc_name, p);
-
-       DEBUG(10, ("GetDC gave name %s for domain %s\n",
-                  dc_name, domain));
-
-       return True;
-}
-
 /*******************************************************************
  convert an ip to a name
 *******************************************************************/
 
-static bool dcip_to_name(const struct winbindd_domain *domain,
+static bool dcip_to_name(TALLOC_CTX *mem_ctx,
+               const struct winbindd_domain *domain,
                struct sockaddr_storage *pss,
                fstring name )
 {
        struct ip_service ip_list;
+       uint32_t nt_version = NETLOGON_NT_VERSION_1;
 
        ip_list.ss = *pss;
        ip_list.port = 0;
@@ -1200,21 +1091,23 @@ static bool dcip_to_name(const struct winbindd_domain *domain,
 
        if (lp_security() == SEC_ADS) {
                ADS_STRUCT *ads;
+               ADS_STATUS ads_status;
                char addr[INET6_ADDRSTRLEN];
 
                print_sockaddr(addr, sizeof(addr), pss);
 
-               ads = ads_init(domain->alt_name, domain->name, NULL);
+               ads = ads_init(domain->alt_name, domain->name, addr);
                ads->auth.flags |= ADS_AUTH_NO_BIND;
 
-               if (ads_try_connect(ads, addr)) {
+               ads_status = ads_connect(ads);
+               if (ADS_ERR_OK(ads_status)) {
                        /* We got a cldap packet. */
                        fstrcpy(name, ads->config.ldap_server_name);
                        namecache_store(name, 0x20, 1, &ip_list);
 
                        DEBUG(10,("dcip_to_name: flags = 0x%x\n", (unsigned int)ads->config.flags));
 
-                       if (domain->primary && (ads->config.flags & ADS_KDC)) {
+                       if (domain->primary && (ads->config.flags & NBT_SERVER_KDC)) {
                                if (ads_closest_dc(ads)) {
                                        char *sitename = sitename_fetch(ads->config.realm);
 
@@ -1252,11 +1145,17 @@ static bool dcip_to_name(const struct winbindd_domain *domain,
 
        /* try GETDC requests next */
 
-       if (send_getdc_request(pss, domain->name, &domain->sid)) {
+       if (send_getdc_request(mem_ctx, winbind_messaging_context(),
+                              pss, domain->name, &domain->sid,
+                              nt_version)) {
+               const char *dc_name = NULL;
                int i;
                smb_msleep(100);
                for (i=0; i<5; i++) {
-                       if (receive_getdc_response(pss, domain->name, name)) {
+                       if (receive_getdc_response(mem_ctx, pss, domain->name,
+                                                  &nt_version,
+                                                  &dc_name, NULL)) {
+                               fstrcpy(name, dc_name);
                                namecache_store(name, 0x20, 1, &ip_list);
                                return True;
                        }
@@ -1274,8 +1173,15 @@ static bool dcip_to_name(const struct winbindd_domain *domain,
 }
 
 /*******************************************************************
- Retreive a list of IP address for domain controllers.  Fill in 
- the dcs[]  with results.
+ Retrieve a list of IP addresses for domain controllers.
+
+ The array is sorted in the preferred connection order.
+
+ @param[in] mem_ctx talloc memory context to allocate from
+ @param[in] domain domain to retrieve DCs for
+ @param[out] dcs array of dcs that will be returned
+ @param[out] num_dcs number of dcs returned in the dcs array
+ @return always true
 *******************************************************************/
 
 static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
@@ -1291,9 +1197,11 @@ static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
 
        is_our_domain = strequal(domain->name, lp_workgroup());
 
+       /* If not our domain, get the preferred DC, by asking our primary DC */
        if ( !is_our_domain
                && get_dc_name_via_netlogon(domain, dcname, &ss)
-               && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs, num_dcs) )
+               && add_one_dc_unique(mem_ctx, domain->name, dcname, &ss, dcs,
+                      num_dcs) )
        {
                char addr[INET6_ADDRSTRLEN];
                print_sockaddr(addr, sizeof(addr), &ss);
@@ -1320,8 +1228,13 @@ static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
                if (sitename) {
 
                        /* Do the site-specific AD dns lookup first. */
-                       get_sorted_dc_list(domain->alt_name, sitename, &ip_list, &iplist_size, True);
+                       get_sorted_dc_list(domain->alt_name, sitename, &ip_list,
+                              &iplist_size, True);
 
+                       /* Add ips to the DC array.  We don't look up the name
+                          of the DC in this function, but we fill in the char*
+                          of the ip now to make the failed connection cache
+                          work */
                        for ( i=0; i<iplist_size; i++ ) {
                                char addr[INET6_ADDRSTRLEN];
                                print_sockaddr(addr, sizeof(addr),
@@ -1339,8 +1252,9 @@ static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
                        iplist_size = 0;
                }
 
-               /* Now we add DCs from the main AD dns lookup. */
-               get_sorted_dc_list(domain->alt_name, NULL, &ip_list, &iplist_size, True);
+               /* Now we add DCs from the main AD DNS lookup. */
+               get_sorted_dc_list(domain->alt_name, NULL, &ip_list,
+                       &iplist_size, True);
 
                for ( i=0; i<iplist_size; i++ ) {
                        char addr[INET6_ADDRSTRLEN];
@@ -1353,33 +1267,46 @@ static bool get_dcs(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
                                        dcs,
                                        num_dcs);
                }
-        }
 
-       /* try standard netbios queries if no ADS */
-
-       if (iplist_size==0) {
-               get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size, False);
-       }
+               SAFE_FREE(ip_list);
+               iplist_size = 0;
+        }
 
-       /* FIXME!! this is where we should re-insert the GETDC requests --jerry */
+       /* Try standard netbios queries if no ADS */
+       if (*num_dcs == 0) {
+               get_sorted_dc_list(domain->name, NULL, &ip_list, &iplist_size,
+                      False);
 
-       /* now add to the dc array.  We'll wait until the last minute 
-          to look up the name of the DC.  But we fill in the char* for 
-          the ip now in to make the failed connection cache work */
+               for ( i=0; i<iplist_size; i++ ) {
+                       char addr[INET6_ADDRSTRLEN];
+                       print_sockaddr(addr, sizeof(addr),
+                                       &ip_list[i].ss);
+                       add_one_dc_unique(mem_ctx,
+                                       domain->name,
+                                       addr,
+                                       &ip_list[i].ss,
+                                       dcs,
+                                       num_dcs);
+               }
 
-       for ( i=0; i<iplist_size; i++ ) {
-               char addr[INET6_ADDRSTRLEN];
-               print_sockaddr(addr, sizeof(addr),
-                               &ip_list[i].ss);
-               add_one_dc_unique(mem_ctx, domain->name, addr,
-                       &ip_list[i].ss, dcs, num_dcs);
+               SAFE_FREE(ip_list);
+               iplist_size = 0;
        }
 
-       SAFE_FREE( ip_list );
-
        return True;
 }
 
+/*******************************************************************
+ Find and make a connection to a DC in the given domain.
+
+ @param[in] mem_ctx talloc memory context to allocate from
+ @param[in] domain domain to find a dc in
+ @param[out] dcname NetBIOS or FQDN of DC that's connected to
+ @param[out] pss DC Internet address and port
+ @param[out] fd fd of the open socket connected to the newly found dc
+ @return true when a DC connection is made, false otherwise
+*******************************************************************/
+
 static bool find_new_dc(TALLOC_CTX *mem_ctx,
                        struct winbindd_domain *domain,
                        fstring dcname, struct sockaddr_storage *pss, int *fd)
@@ -1395,6 +1322,8 @@ static bool find_new_dc(TALLOC_CTX *mem_ctx,
 
        int i, fd_index;
 
+       *fd = -1;
+
  again:
        if (!get_dcs(mem_ctx, domain, &dcs, &num_dcs) || (num_dcs == 0))
                return False;
@@ -1449,13 +1378,27 @@ static bool find_new_dc(TALLOC_CTX *mem_ctx,
        }
 
        /* Try to figure out the name */
-       if (dcip_to_name(domain, pss, dcname)) {
+       if (dcip_to_name(mem_ctx, domain, pss, dcname)) {
                return True;
        }
 
        /* We can not continue without the DC's name */
        winbind_add_failed_connection_entry(domain, dcs[fd_index].name,
                                    NT_STATUS_UNSUCCESSFUL);
+
+       /* Throw away all arrays as we're doing this again. */
+       TALLOC_FREE(dcs);
+       num_dcs = 0;
+
+       TALLOC_FREE(dcnames);
+       num_dcnames = 0;
+
+       TALLOC_FREE(addrs);
+       num_addrs = 0;
+
+       close(*fd);
+       *fd = -1;
+
        goto again;
 }
 
@@ -1475,7 +1418,7 @@ static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
 
        /* we have to check the server affinity cache here since 
           later we selecte a DC based on response time and not preference */
-          
+
        /* Check the negative connection cache
           before talking to it. It going down may have
           triggered the reconnection. */
@@ -1494,7 +1437,7 @@ static NTSTATUS cm_open_connection(struct winbindd_domain *domain,
                                                AI_NUMERICHOST)) {
                                return NT_STATUS_UNSUCCESSFUL;
                        }
-                       if (dcip_to_name( domain, &ss, saf_name )) {
+                       if (dcip_to_name(mem_ctx, domain, &ss, saf_name )) {
                                fstrcpy( domain->dcname, saf_name );
                        } else {
                                winbind_add_failed_connection_entry(
@@ -1592,33 +1535,27 @@ void invalidate_cm_connection(struct winbindd_cm_conn *conn)
        }
 
        if (conn->samr_pipe != NULL) {
-               if (!cli_rpc_pipe_close(conn->samr_pipe)) {
-                       /* Ok, it must be dead. Drop timeout to 0.5 sec. */
-                       if (conn->cli) {
-                               cli_set_timeout(conn->cli, 500);
-                       }
+               TALLOC_FREE(conn->samr_pipe);
+               /* Ok, it must be dead. Drop timeout to 0.5 sec. */
+               if (conn->cli) {
+                       cli_set_timeout(conn->cli, 500);
                }
-               conn->samr_pipe = NULL;
        }
 
        if (conn->lsa_pipe != NULL) {
-               if (!cli_rpc_pipe_close(conn->lsa_pipe)) {
-                       /* Ok, it must be dead. Drop timeout to 0.5 sec. */
-                       if (conn->cli) {
-                               cli_set_timeout(conn->cli, 500);
-                       }
+               TALLOC_FREE(conn->lsa_pipe);
+               /* Ok, it must be dead. Drop timeout to 0.5 sec. */
+               if (conn->cli) {
+                       cli_set_timeout(conn->cli, 500);
                }
-               conn->lsa_pipe = NULL;
        }
 
        if (conn->netlogon_pipe != NULL) {
-               if (!cli_rpc_pipe_close(conn->netlogon_pipe)) {
-                       /* Ok, it must be dead. Drop timeout to 0.5 sec. */
-                       if (conn->cli) {
-                               cli_set_timeout(conn->cli, 500);
-                       }
+               TALLOC_FREE(conn->netlogon_pipe);
+               /* Ok, it must be dead. Drop timeout to 0.5 sec. */
+               if (conn->cli) {
+                       cli_set_timeout(conn->cli, 500);
                }
-               conn->netlogon_pipe = NULL;
        }
 
        if (conn->cli) {
@@ -1731,26 +1668,26 @@ static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
        TALLOC_CTX *mem_ctx = NULL;
 
        DEBUG(5, ("set_dc_type_and_flags_trustinfo: domain %s\n", domain->name ));
-       
+
        /* Our primary domain doesn't need to worry about trust flags.
           Force it to go through the network setup */
        if ( domain->primary ) {                
                return False;           
        }
-       
+
        our_domain = find_our_domain();
-       
+
        if ( !connection_ok(our_domain) ) {
                DEBUG(3,("set_dc_type_and_flags_trustinfo: No connection to our domain!\n"));           
                return False;
        }
 
        /* This won't work unless our domain is AD */
-        
+
        if ( !our_domain->active_directory ) {
                return False;
        }
-       
+
        /* Use DsEnumerateDomainTrusts to get us the trust direction
           and type */
 
@@ -1769,7 +1706,7 @@ static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
        }       
 
        result = rpccli_netr_DsrEnumerateDomainTrusts(cli, mem_ctx,
-                                                     cli->cli->desthost,
+                                                     cli->desthost,
                                                      flags,
                                                      &trusts,
                                                      NULL);
@@ -1811,13 +1748,13 @@ static bool set_dc_type_and_flags_trustinfo( struct winbindd_domain *domain )
 
                        if ( !winbindd_can_contact_domain( domain) )
                                domain->internal = True;
-                       
+
                        break;
                }               
        }
-       
+
        talloc_destroy( mem_ctx );
-       
+
        return domain->initialized;     
 }
 
@@ -1837,13 +1774,8 @@ static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
        struct rpc_pipe_client  *cli;
        POLICY_HND pol;
        union dssetup_DsRoleInfo info;
+       union lsa_PolicyInformation *lsa_info = NULL;
 
-       const char *domain_name = NULL;
-       const char *dns_name = NULL;
-       const char *forest_name = NULL;
-       DOM_SID *dom_sid = NULL;        
-
-       
        if (!connection_ok(domain)) {
                return;
        }
@@ -1857,10 +1789,11 @@ static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
 
        DEBUG(5, ("set_dc_type_and_flags_connect: domain %s\n", domain->name ));
 
-       cli = cli_rpc_pipe_open_noauth(domain->conn.cli, PI_DSSETUP,
-                                      &result);
+       result = cli_rpc_pipe_open_noauth(domain->conn.cli,
+                                         &ndr_table_dssetup.syntax_id,
+                                         &cli);
 
-       if (cli == NULL) {
+       if (!NT_STATUS_IS_OK(result)) {
                DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
                          "PI_DSSETUP on domain %s: (%s)\n",
                          domain->name, nt_errstr(result)));
@@ -1876,7 +1809,7 @@ static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
                                                                  DS_ROLE_BASIC_INFORMATION,
                                                                  &info,
                                                                  &werr);
-       cli_rpc_pipe_close(cli);
+       TALLOC_FREE(cli);
 
        if (!NT_STATUS_IS_OK(result)) {
                DEBUG(5, ("set_dc_type_and_flags_connect: rpccli_ds_getprimarydominfo "
@@ -1904,71 +1837,83 @@ static void set_dc_type_and_flags_connect( struct winbindd_domain *domain )
        }
 
 no_dssetup:
-       cli = cli_rpc_pipe_open_noauth(domain->conn.cli, PI_LSARPC, &result);
+       result = cli_rpc_pipe_open_noauth(domain->conn.cli,
+                                         &ndr_table_lsarpc.syntax_id, &cli);
 
-       if (cli == NULL) {
+       if (!NT_STATUS_IS_OK(result)) {
                DEBUG(5, ("set_dc_type_and_flags_connect: Could not bind to "
                          "PI_LSARPC on domain %s: (%s)\n",
                          domain->name, nt_errstr(result)));
-               cli_rpc_pipe_close(cli);
+               TALLOC_FREE(cli);
                TALLOC_FREE(mem_ctx);
                return;
        }
 
        result = rpccli_lsa_open_policy2(cli, mem_ctx, True, 
                                         SEC_RIGHTS_MAXIMUM_ALLOWED, &pol);
-               
+
        if (NT_STATUS_IS_OK(result)) {
                /* This particular query is exactly what Win2k clients use 
                   to determine that the DC is active directory */
-               result = rpccli_lsa_query_info_policy2(cli, mem_ctx, &pol,
-                                                      12, &domain_name,
-                                                      &dns_name, &forest_name,
-                                                      NULL, &dom_sid);
+               result = rpccli_lsa_QueryInfoPolicy2(cli, mem_ctx,
+                                                    &pol,
+                                                    LSA_POLICY_INFO_DNS,
+                                                    &lsa_info);
        }
 
        if (NT_STATUS_IS_OK(result)) {
                domain->active_directory = True;
 
-               if (domain_name)
-                       fstrcpy(domain->name, domain_name);
+               if (lsa_info->dns.name.string) {
+                       fstrcpy(domain->name, lsa_info->dns.name.string);
+               }
 
-               if (dns_name)
-                       fstrcpy(domain->alt_name, dns_name);
+               if (lsa_info->dns.dns_domain.string) {
+                       fstrcpy(domain->alt_name,
+                               lsa_info->dns.dns_domain.string);
+               }
 
                /* See if we can set some domain trust flags about
                   ourself */
 
-               if ( forest_name ) {
-                       fstrcpy(domain->forest_name, forest_name);              
+               if (lsa_info->dns.dns_forest.string) {
+                       fstrcpy(domain->forest_name,
+                               lsa_info->dns.dns_forest.string);
 
                        if (strequal(domain->forest_name, domain->alt_name)) {
-                               domain->domain_flags = NETR_TRUST_FLAG_TREEROOT;
+                               domain->domain_flags |= NETR_TRUST_FLAG_TREEROOT;
                        }
                }
 
-               if (dom_sid) 
-                       sid_copy(&domain->sid, dom_sid);
+               if (lsa_info->dns.sid) {
+                       sid_copy(&domain->sid, lsa_info->dns.sid);
+               }
        } else {
                domain->active_directory = False;
 
                result = rpccli_lsa_open_policy(cli, mem_ctx, True, 
                                                SEC_RIGHTS_MAXIMUM_ALLOWED,
                                                &pol);
-                       
-               if (!NT_STATUS_IS_OK(result))
+
+               if (!NT_STATUS_IS_OK(result)) {
                        goto done;
-                       
-               result = rpccli_lsa_query_info_policy(cli, mem_ctx, 
-                                                     &pol, 5, &domain_name, 
-                                                     &dom_sid);
-                       
+               }
+
+               result = rpccli_lsa_QueryInfoPolicy(cli, mem_ctx,
+                                                   &pol,
+                                                   LSA_POLICY_INFO_ACCOUNT_DOMAIN,
+                                                   &lsa_info);
+
                if (NT_STATUS_IS_OK(result)) {
-                       if (domain_name)
-                               fstrcpy(domain->name, domain_name);
 
-                       if (dom_sid) 
-                               sid_copy(&domain->sid, dom_sid);
+                       if (lsa_info->account_domain.name.string) {
+                               fstrcpy(domain->name,
+                                       lsa_info->account_domain.name.string);
+                       }
+
+                       if (lsa_info->account_domain.sid) {
+                               sid_copy(&domain->sid, lsa_info->account_domain.sid);
+                       }
                }
        }
 done:
@@ -1979,7 +1924,7 @@ done:
        DEBUG(5,("set_dc_type_and_flags_connect: domain %s is %srunning active directory.\n",
                  domain->name, domain->active_directory ? "" : "NOT "));
 
-       cli_rpc_pipe_close(cli);
+       TALLOC_FREE(cli);
 
        TALLOC_FREE(mem_ctx);
 
@@ -2035,6 +1980,10 @@ static bool cm_get_schannel_dcinfo(struct winbindd_domain *domain,
        /* Return a pointer to the struct dcinfo from the
           netlogon pipe. */
 
+       if (!domain->conn.netlogon_pipe->dc) {
+               return false;
+       }
+
        *ppdc = domain->conn.netlogon_pipe->dc;
        return True;
 }
@@ -2061,6 +2010,7 @@ NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
                goto done;
        }
 
+
        /*
         * No SAMR pipe yet. Attempt to get an NTLMSSP SPNEGO authenticated
         * sign and sealed pipe using the machine account password by
@@ -2094,14 +2044,15 @@ NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
 
        /* We have an authenticated connection. Use a NTLMSSP SPNEGO
           authenticated SAMR pipe with sign & seal. */
-       conn->samr_pipe =
-               cli_rpc_pipe_open_spnego_ntlmssp(conn->cli, PI_SAMR,
-                                                PIPE_AUTH_LEVEL_PRIVACY,
-                                                domain_name,
-                                                machine_account,
-                                                machine_password, &result);
-
-       if (conn->samr_pipe == NULL) {
+       result = cli_rpc_pipe_open_spnego_ntlmssp(conn->cli,
+                                                 &ndr_table_samr.syntax_id,
+                                                 PIPE_AUTH_LEVEL_PRIVACY,
+                                                 domain_name,
+                                                 machine_account,
+                                                 machine_password,
+                                                 &conn->samr_pipe);
+
+       if (!NT_STATUS_IS_OK(result)) {
                DEBUG(10,("cm_connect_sam: failed to connect to SAMR "
                          "pipe for domain %s using NTLMSSP "
                          "authenticated pipe: user %s\\%s. Error was "
@@ -2116,7 +2067,7 @@ NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
                  domain_name, machine_account));
 
        result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
-                                     conn->samr_pipe->cli->desthost,
+                                     conn->samr_pipe->desthost,
                                      SEC_RIGHTS_MAXIMUM_ALLOWED,
                                      &conn->sam_connect_handle);
        if (NT_STATUS_IS_OK(result)) {
@@ -2125,7 +2076,7 @@ NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
        DEBUG(10,("cm_connect_sam: ntlmssp-sealed rpccli_samr_Connect2 "
                  "failed for domain %s, error was %s. Trying schannel\n",
                  domain->name, nt_errstr(result) ));
-       cli_rpc_pipe_close(conn->samr_pipe);
+       TALLOC_FREE(conn->samr_pipe);
 
  schannel:
 
@@ -2137,11 +2088,11 @@ NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
                           "for domain %s, trying anon\n", domain->name));
                goto anonymous;
        }
-       conn->samr_pipe = cli_rpc_pipe_open_schannel_with_key
-               (conn->cli, PI_SAMR, PIPE_AUTH_LEVEL_PRIVACY,
-                domain->name, p_dcinfo, &result);
+       result = cli_rpc_pipe_open_schannel_with_key
+               (conn->cli, &ndr_table_samr.syntax_id, PIPE_AUTH_LEVEL_PRIVACY,
+                domain->name, p_dcinfo, &conn->samr_pipe);
 
-       if (conn->samr_pipe == NULL) {
+       if (!NT_STATUS_IS_OK(result)) {
                DEBUG(10,("cm_connect_sam: failed to connect to SAMR pipe for "
                          "domain %s using schannel. Error was %s\n",
                          domain->name, nt_errstr(result) ));
@@ -2151,7 +2102,7 @@ NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
                  "schannel.\n", domain->name ));
 
        result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
-                                     conn->samr_pipe->cli->desthost,
+                                     conn->samr_pipe->desthost,
                                      SEC_RIGHTS_MAXIMUM_ALLOWED,
                                      &conn->sam_connect_handle);
        if (NT_STATUS_IS_OK(result)) {
@@ -2160,21 +2111,20 @@ NTSTATUS cm_connect_sam(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
        DEBUG(10,("cm_connect_sam: schannel-sealed rpccli_samr_Connect2 failed "
                  "for domain %s, error was %s. Trying anonymous\n",
                  domain->name, nt_errstr(result) ));
-       cli_rpc_pipe_close(conn->samr_pipe);
+       TALLOC_FREE(conn->samr_pipe);
 
  anonymous:
 
        /* Finally fall back to anonymous. */
-       conn->samr_pipe = cli_rpc_pipe_open_noauth(conn->cli, PI_SAMR,
-                                                  &result);
+       result = cli_rpc_pipe_open_noauth(conn->cli, &ndr_table_samr.syntax_id,
+                                         &conn->samr_pipe);
 
-       if (conn->samr_pipe == NULL) {
-               result = NT_STATUS_PIPE_NOT_AVAILABLE;
+       if (!NT_STATUS_IS_OK(result)) {
                goto done;
        }
 
        result = rpccli_samr_Connect2(conn->samr_pipe, mem_ctx,
-                                     conn->samr_pipe->cli->desthost,
+                                     conn->samr_pipe->desthost,
                                      SEC_RIGHTS_MAXIMUM_ALLOWED,
                                      &conn->sam_connect_handle);
        if (!NT_STATUS_IS_OK(result)) {
@@ -2235,11 +2185,13 @@ NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
 
        /* We have an authenticated connection. Use a NTLMSSP SPNEGO
         * authenticated LSA pipe with sign & seal. */
-       conn->lsa_pipe = cli_rpc_pipe_open_spnego_ntlmssp
-               (conn->cli, PI_LSARPC, PIPE_AUTH_LEVEL_PRIVACY,
-                conn->cli->domain, conn->cli->user_name, conn_pwd, &result);
+       result = cli_rpc_pipe_open_spnego_ntlmssp
+               (conn->cli, &ndr_table_lsarpc.syntax_id,
+                PIPE_AUTH_LEVEL_PRIVACY,
+                conn->cli->domain, conn->cli->user_name, conn_pwd,
+                &conn->lsa_pipe);
 
-       if (conn->lsa_pipe == NULL) {
+       if (!NT_STATUS_IS_OK(result)) {
                DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
                          "domain %s using NTLMSSP authenticated pipe: user "
                          "%s\\%s. Error was %s. Trying schannel.\n",
@@ -2262,7 +2214,7 @@ NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
        DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
                  "schannel\n"));
 
-       cli_rpc_pipe_close(conn->lsa_pipe);
+       TALLOC_FREE(conn->lsa_pipe);
 
  schannel:
 
@@ -2274,11 +2226,12 @@ NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
                           "for domain %s, trying anon\n", domain->name));
                goto anonymous;
        }
-       conn->lsa_pipe = cli_rpc_pipe_open_schannel_with_key
-               (conn->cli, PI_LSARPC, PIPE_AUTH_LEVEL_PRIVACY,
-                domain->name, p_dcinfo, &result);
+       result = cli_rpc_pipe_open_schannel_with_key
+               (conn->cli, &ndr_table_lsarpc.syntax_id,
+                PIPE_AUTH_LEVEL_PRIVACY,
+                domain->name, p_dcinfo, &conn->lsa_pipe);
 
-       if (conn->lsa_pipe == NULL) {
+       if (!NT_STATUS_IS_OK(result)) {
                DEBUG(10,("cm_connect_lsa: failed to connect to LSA pipe for "
                          "domain %s using schannel. Error was %s\n",
                          domain->name, nt_errstr(result) ));
@@ -2297,13 +2250,14 @@ NTSTATUS cm_connect_lsa(struct winbindd_domain *domain, TALLOC_CTX *mem_ctx,
        DEBUG(10,("cm_connect_lsa: rpccli_lsa_open_policy failed, trying "
                  "anonymous\n"));
 
-       cli_rpc_pipe_close(conn->lsa_pipe);
+       TALLOC_FREE(conn->lsa_pipe);
 
  anonymous:
 
-       conn->lsa_pipe = cli_rpc_pipe_open_noauth(conn->cli, PI_LSARPC,
-                                                 &result);
-       if (conn->lsa_pipe == NULL) {
+       result = cli_rpc_pipe_open_noauth(conn->cli,
+                                         &ndr_table_lsarpc.syntax_id,
+                                         &conn->lsa_pipe);
+       if (!NT_STATUS_IS_OK(result)) {
                result = NT_STATUS_PIPE_NOT_AVAILABLE;
                goto done;
        }
@@ -2333,7 +2287,7 @@ NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
        struct winbindd_cm_conn *conn;
        NTSTATUS result;
 
-       uint32 neg_flags = NETLOGON_NEG_SELECT_AUTH2_FLAGS;
+       uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
        uint8  mach_pwd[16];
        uint32  sec_chan_type;
        const char *account_name;
@@ -2353,9 +2307,10 @@ NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
                return NT_STATUS_OK;
        }
 
-       netlogon_pipe = cli_rpc_pipe_open_noauth(conn->cli, PI_NETLOGON,
-                                                &result);
-       if (netlogon_pipe == NULL) {
+       result = cli_rpc_pipe_open_noauth(conn->cli,
+                                         &ndr_table_netlogon.syntax_id,
+                                         &netlogon_pipe);
+       if (!NT_STATUS_IS_OK(result)) {
                return result;
        }
 
@@ -2372,7 +2327,7 @@ NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
        if (!get_trust_pw_hash(domain->name, mach_pwd, &account_name,
                               &sec_chan_type))
        {
-               cli_rpc_pipe_close(netlogon_pipe);
+               TALLOC_FREE(netlogon_pipe);
                return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
        }
 
@@ -2387,20 +2342,25 @@ NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
                 &neg_flags);
 
        if (!NT_STATUS_IS_OK(result)) {
-               cli_rpc_pipe_close(netlogon_pipe);
+               TALLOC_FREE(netlogon_pipe);
                return result;
        }
 
        if ((lp_client_schannel() == True) &&
                        ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
                DEBUG(3, ("Server did not offer schannel\n"));
-               cli_rpc_pipe_close(netlogon_pipe);
+               TALLOC_FREE(netlogon_pipe);
                return NT_STATUS_ACCESS_DENIED;
        }
 
  no_schannel:
        if ((lp_client_schannel() == False) ||
                        ((neg_flags & NETLOGON_NEG_SCHANNEL) == 0)) {
+               /*
+                * NetSamLogonEx only works for schannel
+                */
+               domain->can_do_samlogon_ex = False;
+
                /* We're done - just keep the existing connection to NETLOGON
                 * open */
                conn->netlogon_pipe = netlogon_pipe;
@@ -2413,25 +2373,27 @@ NTSTATUS cm_connect_netlogon(struct winbindd_domain *domain,
           part of the new pipe auth struct.
        */
 
-       conn->netlogon_pipe =
-               cli_rpc_pipe_open_schannel_with_key(conn->cli,
-                                                   PI_NETLOGON,
-                                                   PIPE_AUTH_LEVEL_PRIVACY,
-                                                   domain->name,
-                                                   netlogon_pipe->dc,
-                                                   &result);
+       result = cli_rpc_pipe_open_schannel_with_key(
+               conn->cli, &ndr_table_netlogon.syntax_id,
+               PIPE_AUTH_LEVEL_PRIVACY, domain->name, netlogon_pipe->dc,
+               &conn->netlogon_pipe);
 
        /* We can now close the initial netlogon pipe. */
-       cli_rpc_pipe_close(netlogon_pipe);
+       TALLOC_FREE(netlogon_pipe);
 
-       if (conn->netlogon_pipe == NULL) {
+       if (!NT_STATUS_IS_OK(result)) {
                DEBUG(3, ("Could not open schannel'ed NETLOGON pipe. Error "
                          "was %s\n", nt_errstr(result)));
-                         
+
                /* make sure we return something besides OK */
                return !NT_STATUS_IS_OK(result) ? result : NT_STATUS_PIPE_NOT_AVAILABLE;
        }
 
+       /*
+        * Try NetSamLogonEx for AD domains
+        */
+       domain->can_do_samlogon_ex = domain->active_directory;
+
        *cli = conn->netlogon_pipe;
        return NT_STATUS_OK;
 }