s3:libads: Improve logging for failover scenarios
[samba.git] / source3 / libads / ldap.c
old mode 100755 (executable)
new mode 100644 (file)
index 28f396f..acf558a
@@ -1,4 +1,4 @@
-/* 
+/*
    Unix SMB/CIFS implementation.
    ads (active directory) utility library
    Copyright (C) Andrew Tridgell 2001
@@ -25,6 +25,7 @@
 #include "ads.h"
 #include "libads/sitename_cache.h"
 #include "libads/cldap.h"
+#include "../lib/tsocket/tsocket.h"
 #include "../lib/addns/dnsquery.h"
 #include "../libds/common/flags.h"
 #include "smbldap.h"
@@ -32,6 +33,7 @@
 #include "../librpc/gen_ndr/netlogon.h"
 #include "lib/param/loadparm.h"
 #include "libsmb/namequery.h"
+#include "../librpc/gen_ndr/ndr_ads.h"
 
 #ifdef HAVE_LDAP
 
@@ -41,7 +43,7 @@
  *
  * The routines contained here should do the necessary ldap calls for
  * ads setups.
- * 
+ *
  * Important note: attribute names passed into ads_ routines must
  * already be in UTF-8 format.  We do not convert them because in almost
  * all cases, they are just ascii (which is represented with the same
@@ -163,7 +165,7 @@ static int ldap_search_with_timeout(LDAP *ld,
                /* Setup alarm timeout. */
                CatchSignal(SIGALRM, gotalarm_sig);
                /* Make the alarm time one second beyond
-                  the timout we're setting for the
+                  the timeout we're setting for the
                   remote search timeout, to allow that
                   to fire in preference. */
                alarm(to+1);
@@ -243,94 +245,111 @@ bool ads_closest_dc(ADS_STRUCT *ads)
                return True;
        }
 
-       DEBUG(10,("ads_closest_dc: %s is not the closest DC\n", 
+       DEBUG(10,("ads_closest_dc: %s is not the closest DC\n",
                ads->config.ldap_server_name));
 
        return False;
 }
 
-
-/*
-  try a connection to a given ldap server, returning True and setting the servers IP
-  in the ads struct if successful
- */
-static bool ads_try_connect(ADS_STRUCT *ads, bool gc,
-                           struct sockaddr_storage *ss)
+static bool ads_fill_cldap_reply(ADS_STRUCT *ads,
+                                bool gc,
+                                const struct sockaddr_storage *ss,
+                                const struct NETLOGON_SAM_LOGON_RESPONSE_EX *cldap_reply)
 {
-       struct NETLOGON_SAM_LOGON_RESPONSE_EX cldap_reply;
        TALLOC_CTX *frame = talloc_stackframe();
        bool ret = false;
        char addr[INET6_ADDRSTRLEN];
-
-       if (ss == NULL) {
-               TALLOC_FREE(frame);
-               return False;
-       }
+       ADS_STATUS status;
+       char *dn;
 
        print_sockaddr(addr, sizeof(addr), ss);
 
-       DEBUG(5,("ads_try_connect: sending CLDAP request to %s (realm: %s)\n", 
-               addr, ads->server.realm));
-
-       ZERO_STRUCT( cldap_reply );
+       /* Check the CLDAP reply flags */
 
-       if ( !ads_cldap_netlogon_5(frame, ss, ads->server.realm, &cldap_reply ) ) {
-               DEBUG(3,("ads_try_connect: CLDAP request %s failed.\n", addr));
+       if (!(cldap_reply->server_type & NBT_SERVER_LDAP)) {
+               DBG_WARNING("%s's CLDAP reply says it is not an LDAP server!\n",
+                           addr);
                ret = false;
                goto out;
        }
 
-       /* Check the CLDAP reply flags */
+       /* Fill in the ads->config values */
+
+       ADS_TALLOC_CONST_FREE(ads->config.realm);
+       ADS_TALLOC_CONST_FREE(ads->config.bind_path);
+       ADS_TALLOC_CONST_FREE(ads->config.ldap_server_name);
+       ADS_TALLOC_CONST_FREE(ads->config.server_site_name);
+       ADS_TALLOC_CONST_FREE(ads->config.client_site_name);
+       ADS_TALLOC_CONST_FREE(ads->server.workgroup);
 
-       if ( !(cldap_reply.server_type & NBT_SERVER_LDAP) ) {
-               DEBUG(1,("ads_try_connect: %s's CLDAP reply says it is not an LDAP server!\n",
-                       addr));
+       if (!check_cldap_reply_required_flags(cldap_reply->server_type,
+                                             ads->config.flags)) {
                ret = false;
                goto out;
        }
 
-       /* Fill in the ads->config values */
-
-       SAFE_FREE(ads->config.realm);
-       SAFE_FREE(ads->config.bind_path);
-       SAFE_FREE(ads->config.ldap_server_name);
-       SAFE_FREE(ads->config.server_site_name);
-       SAFE_FREE(ads->config.client_site_name);
-       SAFE_FREE(ads->server.workgroup);
+       ads->config.ldap_server_name = talloc_strdup(ads,
+                                                    cldap_reply->pdc_dns_name);
+       if (ads->config.ldap_server_name == NULL) {
+               DBG_WARNING("Out of memory\n");
+               ret = false;
+               goto out;
+       }
 
-       if (!check_cldap_reply_required_flags(cldap_reply.server_type,
-                                             ads->config.flags)) {
+       ads->config.realm = talloc_asprintf_strupper_m(ads,
+                                                      "%s",
+                                                      cldap_reply->dns_domain);
+       if (ads->config.realm == NULL) {
+               DBG_WARNING("Out of memory\n");
                ret = false;
                goto out;
        }
 
-       ads->config.ldap_server_name   = SMB_STRDUP(cldap_reply.pdc_dns_name);
-       ads->config.realm              = SMB_STRDUP(cldap_reply.dns_domain);
-       if (!strupper_m(ads->config.realm)) {
+       status = ads_build_dn(ads->config.realm, ads, &dn);
+       if (!ADS_ERR_OK(status)) {
+               DBG_DEBUG("Failed to build bind path: %s\n",
+                         ads_errstr(status));
                ret = false;
                goto out;
        }
+       ads->config.bind_path = dn;
 
-       ads->config.bind_path          = ads_build_dn(ads->config.realm);
-       if (*cldap_reply.server_site) {
+       if (*cldap_reply->server_site) {
                ads->config.server_site_name =
-                       SMB_STRDUP(cldap_reply.server_site);
+                       talloc_strdup(ads, cldap_reply->server_site);
+               if (ads->config.server_site_name == NULL) {
+                       DBG_WARNING("Out of memory\n");
+                       ret = false;
+                       goto out;
+               }
        }
-       if (*cldap_reply.client_site) {
+
+       if (*cldap_reply->client_site) {
                ads->config.client_site_name =
-                       SMB_STRDUP(cldap_reply.client_site);
+                       talloc_strdup(ads, cldap_reply->client_site);
+               if (ads->config.client_site_name == NULL) {
+                       DBG_WARNING("Out of memory\n");
+                       ret = false;
+                       goto out;
+               }
+       }
+
+       ads->server.workgroup = talloc_strdup(ads, cldap_reply->domain_name);
+       if (ads->server.workgroup == NULL) {
+               DBG_WARNING("Out of memory\n");
+               ret = false;
+               goto out;
        }
-       ads->server.workgroup          = SMB_STRDUP(cldap_reply.domain_name);
 
        ads->ldap.port = gc ? LDAP_GC_PORT : LDAP_PORT;
        ads->ldap.ss = *ss;
 
        /* Store our site name. */
-       sitename_store( cldap_reply.domain_name, cldap_reply.client_site);
-       sitename_store( cldap_reply.dns_domain, cldap_reply.client_site);
+       sitename_store(cldap_reply->domain_name, cldap_reply->client_site);
+       sitename_store(cldap_reply->dns_domain, cldap_reply->client_site);
 
        /* Leave this until last so that the flags are not clobbered */
-       ads->config.flags              = cldap_reply.server_type;
+       ads->config.flags = cldap_reply->server_type;
 
        ret = true;
 
@@ -340,6 +359,48 @@ static bool ads_try_connect(ADS_STRUCT *ads, bool gc,
        return ret;
 }
 
+/*
+  try a connection to a given ldap server, returning True and setting the servers IP
+  in the ads struct if successful
+ */
+static bool ads_try_connect(ADS_STRUCT *ads, bool gc,
+                           struct sockaddr_storage *ss)
+{
+       struct NETLOGON_SAM_LOGON_RESPONSE_EX cldap_reply = {};
+       TALLOC_CTX *frame = talloc_stackframe();
+       bool ok;
+       char addr[INET6_ADDRSTRLEN] = { 0, };
+
+       if (ss == NULL) {
+               TALLOC_FREE(frame);
+               return false;
+       }
+
+       print_sockaddr(addr, sizeof(addr), ss);
+
+       DBG_INFO("ads_try_connect: sending CLDAP request to %s (realm: %s)\n",
+                addr, ads->server.realm);
+
+       ok = ads_cldap_netlogon_5(frame, ss, ads->server.realm, &cldap_reply);
+       if (!ok) {
+               DBG_NOTICE("ads_cldap_netlogon_5(%s, %s) failed.\n",
+                          addr, ads->server.realm);
+               TALLOC_FREE(frame);
+               return false;
+       }
+
+       ok = ads_fill_cldap_reply(ads, gc, ss, &cldap_reply);
+       if (!ok) {
+               DBG_NOTICE("ads_fill_cldap_reply(%s, %s) failed.\n",
+                          addr, ads->server.realm);
+               TALLOC_FREE(frame);
+               return false;
+       }
+
+       TALLOC_FREE(frame);
+       return true;
+}
+
 /**********************************************************************
  send a cldap ping to list of servers, one at a time, until one of
  them answers it's an ldap server. Record success in the ADS_STRUCT.
@@ -351,30 +412,176 @@ static NTSTATUS cldap_ping_list(ADS_STRUCT *ads,
                        struct samba_sockaddr *sa_list,
                        size_t count)
 {
+       TALLOC_CTX *frame = talloc_stackframe();
+       struct timeval endtime = timeval_current_ofs(MAX(3,lp_ldap_timeout()/2), 0);
+       uint32_t nt_version = NETLOGON_NT_VERSION_5 | NETLOGON_NT_VERSION_5EX;
+       struct tsocket_address **ts_list = NULL;
+       const struct tsocket_address * const *ts_list_const = NULL;
+       struct samba_sockaddr **req_sa_list = NULL;
+       struct netlogon_samlogon_response **responses = NULL;
+       size_t num_requests = 0;
+       NTSTATUS status;
        size_t i;
-       bool ok;
+       bool ok = false;
+       bool retry;
+
+       ts_list = talloc_zero_array(frame,
+                                   struct tsocket_address *,
+                                   count);
+       if (ts_list == NULL) {
+               TALLOC_FREE(frame);
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       req_sa_list = talloc_zero_array(frame,
+                                       struct samba_sockaddr *,
+                                       count);
+       if (req_sa_list == NULL) {
+               TALLOC_FREE(frame);
+               return NT_STATUS_NO_MEMORY;
+       }
+
+again:
+       /*
+        * The retry loop is bound by the timeout
+        */
+       retry = false;
+       num_requests = 0;
 
        for (i = 0; i < count; i++) {
                char server[INET6_ADDRSTRLEN];
+               int ret;
+
+               if (is_zero_addr(&sa_list[i].u.ss)) {
+                       continue;
+               }
 
                print_sockaddr(server, sizeof(server), &sa_list[i].u.ss);
 
-               if (!NT_STATUS_IS_OK(
-                       check_negative_conn_cache(domain, server)))
+               status = check_negative_conn_cache(domain, server);
+               if (!NT_STATUS_IS_OK(status)) {
+                       continue;
+               }
+
+               ret = tsocket_address_inet_from_strings(ts_list, "ip",
+                                                       server, LDAP_PORT,
+                                                       &ts_list[num_requests]);
+               if (ret != 0) {
+                       status = map_nt_error_from_unix(errno);
+                       DBG_WARNING("Failed to create tsocket_address for %s - %s\n",
+                                   server, nt_errstr(status));
+                       TALLOC_FREE(frame);
+                       return status;
+               }
+
+               req_sa_list[num_requests] = &sa_list[i];
+               num_requests += 1;
+       }
+
+       DBG_DEBUG("Try to create %zu netlogon connections for domain '%s' "
+                 "(provided count of addresses was %zu).\n",
+                 num_requests,
+                 domain,
+                 count);
+
+       if (num_requests == 0) {
+               status = NT_STATUS_NO_LOGON_SERVERS;
+               DBG_WARNING("domain[%s] num_requests[%zu] for count[%zu] - %s\n",
+                           domain, num_requests, count, nt_errstr(status));
+               TALLOC_FREE(frame);
+               return status;
+       }
+
+       ts_list_const = (const struct tsocket_address * const *)ts_list;
+
+       status = cldap_multi_netlogon(frame,
+                                     ts_list_const, num_requests,
+                                     ads->server.realm, NULL,
+                                     nt_version,
+                                     1, endtime, &responses);
+       if (!NT_STATUS_IS_OK(status)) {
+               DBG_WARNING("cldap_multi_netlogon(realm=%s, num_requests=%zu) "
+                           "for count[%zu] - %s\n",
+                           ads->server.realm,
+                           num_requests, count,
+                           nt_errstr(status));
+               TALLOC_FREE(frame);
+               return NT_STATUS_NO_LOGON_SERVERS;
+       }
+
+       for (i = 0; i < num_requests; i++) {
+               struct NETLOGON_SAM_LOGON_RESPONSE_EX *cldap_reply = NULL;
+               char server[INET6_ADDRSTRLEN];
+
+               if (responses[i] == NULL) {
                        continue;
+               }
 
-               /* Returns ok only if it matches the correct server type */
-               ok = ads_try_connect(ads, false, &sa_list[i].u.ss);
+               print_sockaddr(server, sizeof(server), &req_sa_list[i]->u.ss);
 
+               if (responses[i]->ntver != NETLOGON_NT_VERSION_5EX) {
+                       DBG_NOTICE("realm=[%s] nt_version mismatch: 0x%08x for %s\n",
+                                  ads->server.realm,
+                                  responses[i]->ntver, server);
+                       continue;
+               }
+
+               cldap_reply = &responses[i]->data.nt5_ex;
+
+               /* Returns ok only if it matches the correct server type */
+               ok = ads_fill_cldap_reply(ads,
+                                         false,
+                                         &req_sa_list[i]->u.ss,
+                                         cldap_reply);
                if (ok) {
+                       DBG_DEBUG("realm[%s]: selected %s => %s\n",
+                                 ads->server.realm,
+                                 server, cldap_reply->pdc_dns_name);
+                       if (CHECK_DEBUGLVL(DBGLVL_DEBUG)) {
+                               NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_EX,
+                                               cldap_reply);
+                       }
+                       TALLOC_FREE(frame);
                        return NT_STATUS_OK;
                }
 
-               /* keep track of failures */
+               DBG_NOTICE("realm[%s] server %s %s - not usable\n",
+                          ads->server.realm,
+                          server, cldap_reply->pdc_dns_name);
+               if (CHECK_DEBUGLVL(DBGLVL_NOTICE)) {
+                       NDR_PRINT_DEBUG(NETLOGON_SAM_LOGON_RESPONSE_EX,
+                                       cldap_reply);
+               }
+               add_failed_connection_entry(domain, server,
+                               NT_STATUS_CLIENT_SERVER_PARAMETERS_INVALID);
+               retry = true;
+       }
+
+       if (retry) {
+               bool expired;
+
+               expired = timeval_expired(&endtime);
+               if (!expired) {
+                       goto again;
+               }
+       }
+
+       /* keep track of failures as all were not suitable */
+       for (i = 0; i < num_requests; i++) {
+               char server[INET6_ADDRSTRLEN];
+
+               print_sockaddr(server, sizeof(server), &req_sa_list[i]->u.ss);
+
                add_failed_connection_entry(domain, server,
                                            NT_STATUS_UNSUCCESSFUL);
        }
 
+       status = NT_STATUS_NO_LOGON_SERVERS;
+       DBG_WARNING("realm[%s] no valid response "
+                   "num_requests[%zu] for count[%zu] - %s\n",
+                   ads->server.realm,
+                   num_requests, count, nt_errstr(status));
+       TALLOC_FREE(frame);
        return NT_STATUS_NO_LOGON_SERVERS;
 }
 
@@ -464,7 +671,7 @@ static NTSTATUS resolve_and_ping_dns(ADS_STRUCT *ads, const char *sitename,
 
 /**********************************************************************
  Try to find an AD dc using our internal name resolution routines
- Try the realm first and then then workgroup name if netbios is not
+ Try the realm first and then the workgroup name if netbios is not
  disabled
 **********************************************************************/
 
@@ -528,6 +735,10 @@ static NTSTATUS ads_find_dc(ADS_STRUCT *ads)
 
                ok = get_dc_name(c_domain, c_realm, srv_name, &ip_out);
                if (ok) {
+                       if (is_zero_addr(&ip_out)) {
+                               return NT_STATUS_NO_LOGON_SERVERS;
+                       }
+
                        /*
                         * we call ads_try_connect() to fill in the
                         * ads->config details
@@ -605,7 +816,9 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
        ADS_STATUS status;
        NTSTATUS ntstatus;
        char addr[INET6_ADDRSTRLEN];
-       struct sockaddr_storage existing_ss = {0};
+       struct sockaddr_storage existing_ss;
+
+       zero_sockaddr(&existing_ss);
 
        /*
         * ads_connect can be passed in a reused ADS_STRUCT
@@ -620,8 +833,8 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
         * to ads_find_dc() in the reuse case.
         *
         * If a caller wants a clean ADS_STRUCT they
-        * will re-initialize by calling ads_init(), or
-        * call ads_destroy() both of which ensures
+        * will TALLOC_FREE it and allocate a new one
+        * by calling ads_init(), which ensures
         * ads->ldap.ss is a properly zero'ed out valid IP
         * address.
         */
@@ -648,6 +861,8 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                bool ok = false;
                struct sockaddr_storage ss;
 
+               DBG_DEBUG("Resolving name of LDAP server '%s'.\n",
+                         ads->server.ldap_server);
                ok = resolve_name(ads->server.ldap_server, &ss, 0x20, true);
                if (!ok) {
                        DEBUG(5,("ads_connect: unable to resolve name %s\n",
@@ -655,6 +870,12 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                        status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
                        goto out;
                }
+
+               if (is_zero_addr(&ss)) {
+                       status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
+                       goto out;
+               }
+
                ok = ads_try_connect(ads, ads->server.gc, &ss);
                if (ok) {
                        goto got_connection;
@@ -687,6 +908,8 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                 * Keep trying to find a server and fall through
                 * into ads_find_dc() again.
                 */
+               DBG_DEBUG("Failed to connect to DC via LDAP server IP address, "
+                         "trying to find another DC.\n");
        }
 
        ntstatus = ads_find_dc(ads);
@@ -705,20 +928,31 @@ got_connection:
        if (!ads->auth.user_name) {
                /* Must use the userPrincipalName value here or sAMAccountName
                   and not servicePrincipalName; found by Guenther Deschner */
-
-               if (asprintf(&ads->auth.user_name, "%s$", lp_netbios_name() ) == -1) {
-                       DEBUG(0,("ads_connect: asprintf fail.\n"));
-                       ads->auth.user_name = NULL;
+               ads->auth.user_name = talloc_asprintf(ads,
+                                                     "%s$",
+                                                     lp_netbios_name());
+               if (ads->auth.user_name == NULL) {
+                       DBG_ERR("talloc_asprintf failed\n");
+                       status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
+                       goto out;
                }
        }
 
-       if (!ads->auth.realm) {
-               ads->auth.realm = SMB_STRDUP(ads->config.realm);
+       if (ads->auth.realm == NULL) {
+               ads->auth.realm = talloc_strdup(ads, ads->config.realm);
+               if (ads->auth.realm == NULL) {
+                       status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
+                       goto out;
+               }
        }
 
        if (!ads->auth.kdc_server) {
                print_sockaddr(addr, sizeof(addr), &ads->ldap.ss);
-               ads->auth.kdc_server = SMB_STRDUP(addr);
+               ads->auth.kdc_server = talloc_strdup(ads, addr);
+               if (ads->auth.kdc_server == NULL) {
+                       status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
+                       goto out;
+               }
        }
 
        /* If the caller() requested no LDAP bind, then we are done */
@@ -861,7 +1095,7 @@ static struct berval *dup_berval(TALLOC_CTX *ctx, const struct berval *in_val)
 /*
   Make a values list out of an array of (struct berval *)
  */
-static struct berval **ads_dup_values(TALLOC_CTX *ctx, 
+static struct berval **ads_dup_values(TALLOC_CTX *ctx,
                                      const struct berval **in_vals)
 {
        struct berval **values;
@@ -922,7 +1156,7 @@ static char **ads_pull_strvals(TALLOC_CTX *ctx, const char **in_vals)
                if (!pull_utf8_talloc(ctx, &values[i], in_vals[i],
                                      &converted_size)) {
                        DEBUG(0,("ads_pull_strvals: pull_utf8_talloc failed: "
-                                "%s", strerror(errno)));
+                                "%s\n", strerror(errno)));
                }
        }
        return values;
@@ -931,8 +1165,8 @@ static char **ads_pull_strvals(TALLOC_CTX *ctx, const char **in_vals)
 /**
  * Do a search with paged results.  cookie must be null on the first
  *  call, and then returned on each subsequent call.  It will be null
- *  again when the entire search is complete 
- * @param ads connection to ads server 
+ *  again when the entire search is complete
+ * @param ads connection to ads server
  * @param bind_path Base dn for the search
  * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
  * @param expr Search expression - specified in local charset
@@ -946,7 +1180,7 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
                                           const char *bind_path,
                                           int scope, const char *expr,
                                           const char **attrs, void *args,
-                                          LDAPMessage **res, 
+                                          LDAPMessage **res,
                                           int *count, struct berval **cookie)
 {
        int rc, i, version;
@@ -966,8 +1200,8 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
        if (!(ctx = talloc_init("ads_do_paged_search_args")))
                return ADS_ERROR(LDAP_NO_MEMORY);
 
-       /* 0 means the conversion worked but the result was empty 
-          so we only fail if it's -1.  In any case, it always 
+       /* 0 means the conversion worked but the result was empty
+          so we only fail if it's -1.  In any case, it always
           at least nulls out the dest */
        if (!push_utf8_talloc(ctx, &utf8_expr, expr, &converted_size) ||
            !push_utf8_talloc(ctx, &utf8_path, bind_path, &converted_size))
@@ -1013,14 +1247,14 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
        NoReferrals.ldctl_value.bv_len = 0;
        NoReferrals.ldctl_value.bv_val = discard_const_p(char, "");
 
-       if (external_control && 
-           (strequal(external_control->control, ADS_EXTENDED_DN_OID) || 
+       if (external_control &&
+           (strequal(external_control->control, ADS_EXTENDED_DN_OID) ||
             strequal(external_control->control, ADS_SD_FLAGS_OID))) {
 
                ExternalCtrl.ldctl_oid = discard_const_p(char, external_control->control);
                ExternalCtrl.ldctl_iscritical = (char) external_control->critical;
 
-               /* win2k does not accept a ldctl_value beeing passed in */
+               /* win2k does not accept a ldctl_value being passed in */
 
                if (external_control->val != 0) {
 
@@ -1059,15 +1293,15 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
 
        /* we need to disable referrals as the openldap libs don't
           handle them and paged results at the same time.  Using them
-          together results in the result record containing the server 
-          page control being removed from the result list (tridge/jmcd) 
+          together results in the result record containing the server
+          page control being removed from the result list (tridge/jmcd)
 
           leaving this in despite the control that says don't generate
           referrals, in case the server doesn't support it (jmcd)
        */
        ldap_set_option(ads->ldap.ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
 
-       rc = ldap_search_with_timeout(ads->ldap.ld, utf8_path, scope, utf8_expr, 
+       rc = ldap_search_with_timeout(ads->ldap.ld, utf8_path, scope, utf8_expr,
                                      search_attrs, 0, controls,
                                      NULL, LDAP_NO_LIMIT,
                                      (LDAPMessage **)res);
@@ -1148,7 +1382,7 @@ done:
 
 static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
                                      int scope, const char *expr,
-                                     const char **attrs, LDAPMessage **res, 
+                                     const char **attrs, LDAPMessage **res,
                                      int *count, struct berval **cookie)
 {
        return ads_do_paged_search_args(ads, bind_path, scope, expr, attrs, NULL, res, count, cookie);
@@ -1156,9 +1390,9 @@ static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
 
 
 /**
- * Get all results for a search.  This uses ads_do_paged_search() to return 
+ * Get all results for a search.  This uses ads_do_paged_search() to return
  * all entries in a large search.
- * @param ads connection to ads server 
+ * @param ads connection to ads server
  * @param bind_path Base dn for the search
  * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
  * @param expr Search expression
@@ -1179,7 +1413,7 @@ static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
        status = ads_do_paged_search_args(ads, bind_path, scope, expr, attrs, args, res,
                                     &count, &cookie);
 
-       if (!ADS_ERR_OK(status)) 
+       if (!ADS_ERR_OK(status))
                return status;
 
 #ifdef HAVE_LDAP_ADD_RESULT_ENTRY
@@ -1219,7 +1453,7 @@ static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
 
  ADS_STATUS ads_do_search_all_sd_flags(ADS_STRUCT *ads, const char *bind_path,
                                       int scope, const char *expr,
-                                      const char **attrs, uint32_t sd_flags, 
+                                      const char **attrs, uint32_t sd_flags,
                                       LDAPMessage **res)
 {
        ads_control args;
@@ -1246,7 +1480,7 @@ static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
  **/
 ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
                                int scope, const char *expr, const char **attrs,
-                               bool (*fn)(ADS_STRUCT *, char *, void **, void *), 
+                               bool (*fn)(ADS_STRUCT *, char *, void **, void *),
                                void *data_area)
 {
        struct berval *cookie = NULL;
@@ -1285,7 +1519,7 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
  * @param res ** which will contain results - free res* with ads_msgfree()
  * @return status of search
  **/
- ADS_STATUS ads_do_search(ADS_STRUCT *ads, const char *bind_path, int scope, 
+ ADS_STATUS ads_do_search(ADS_STRUCT *ads, const char *bind_path, int scope,
                          const char *expr,
                          const char **attrs, LDAPMessage **res)
 {
@@ -1296,17 +1530,17 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
 
        *res = NULL;
        if (!(ctx = talloc_init("ads_do_search"))) {
-               DEBUG(1,("ads_do_search: talloc_init() failed!"));
+               DEBUG(1,("ads_do_search: talloc_init() failed!\n"));
                return ADS_ERROR(LDAP_NO_MEMORY);
        }
 
-       /* 0 means the conversion worked but the result was empty 
-          so we only fail if it's negative.  In any case, it always 
+       /* 0 means the conversion worked but the result was empty
+          so we only fail if it's negative.  In any case, it always
           at least nulls out the dest */
        if (!push_utf8_talloc(ctx, &utf8_expr, expr, &converted_size) ||
            !push_utf8_talloc(ctx, &utf8_path, bind_path, &converted_size))
        {
-               DEBUG(1,("ads_do_search: push_utf8_talloc() failed!"));
+               DEBUG(1,("ads_do_search: push_utf8_talloc() failed!\n"));
                rc = LDAP_NO_MEMORY;
                goto done;
        }
@@ -1318,7 +1552,7 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
                /* if (!(search_attrs = ads_push_strvals(ctx, attrs)))  */
                if (!(search_attrs = str_list_copy(talloc_tos(), attrs)))
                {
-                       DEBUG(1,("ads_do_search: str_list_copy() failed!"));
+                       DEBUG(1,("ads_do_search: str_list_copy() failed!\n"));
                        rc = LDAP_NO_MEMORY;
                        goto done;
                }
@@ -1328,7 +1562,7 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
        ldap_set_option(ads->ldap.ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
 
        rc = ldap_search_with_timeout(ads->ldap.ld, utf8_path, scope, utf8_expr,
-                                     search_attrs, 0, NULL, NULL, 
+                                     search_attrs, 0, NULL, NULL,
                                      LDAP_NO_LIMIT,
                                      (LDAPMessage **)res);
 
@@ -1351,10 +1585,10 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
  * @param attrs Attributes to retrieve
  * @return status of search
  **/
- ADS_STATUS ads_search(ADS_STRUCT *ads, LDAPMessage **res, 
+ ADS_STATUS ads_search(ADS_STRUCT *ads, LDAPMessage **res,
                       const char *expr, const char **attrs)
 {
-       return ads_do_search(ads, ads->config.bind_path, LDAP_SCOPE_SUBTREE, 
+       return ads_do_search(ads, ads->config.bind_path, LDAP_SCOPE_SUBTREE,
                             expr, attrs, res);
 }
 
@@ -1362,11 +1596,11 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
  * Do a search on a specific DistinguishedName
  * @param ads connection to ads server
  * @param res ** which will contain results - free res* with ads_msgfree()
- * @param dn DistinguishName to search
+ * @param dn DistinguishedName to search
  * @param attrs Attributes to retrieve
  * @return status of search
  **/
- ADS_STATUS ads_search_dn(ADS_STRUCT *ads, LDAPMessage **res, 
+ ADS_STATUS ads_search_dn(ADS_STRUCT *ads, LDAPMessage **res,
                          const char *dn, const char **attrs)
 {
        return ads_do_search(ads, dn, LDAP_SCOPE_BASE, "(objectclass=*)",
@@ -1509,8 +1743,8 @@ ADS_MODLIST ads_init_mods(TALLOC_CTX *ctx)
 /*
   add an attribute to the list, with values list already constructed
 */
-static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods, 
-                                 int mod_op, const char *name, 
+static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
+                                 int mod_op, const char *name,
                                  const void *_invals)
 {
        int curmod;
@@ -1539,7 +1773,7 @@ static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
                if (!(modlist = talloc_realloc(ctx, modlist, LDAPMod *,
                                curmod+ADS_MODLIST_ALLOC_SIZE+1)))
                        return ADS_ERROR(LDAP_NO_MEMORY);
-               memset(&modlist[curmod], 0, 
+               memset(&modlist[curmod], 0,
                       ADS_MODLIST_ALLOC_SIZE*sizeof(LDAPMod *));
                modlist[curmod+ADS_MODLIST_ALLOC_SIZE] = (LDAPMod *) -1;
                *mods = (ADS_MODLIST)modlist;
@@ -1568,7 +1802,7 @@ static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
  * @param val The value to add - NULL means DELETE
  * @return ADS STATUS indicating success of add
  **/
-ADS_STATUS ads_mod_str(TALLOC_CTX *ctx, ADS_MODLIST *mods, 
+ADS_STATUS ads_mod_str(TALLOC_CTX *ctx, ADS_MODLIST *mods,
                       const char *name, const char *val)
 {
        const char *values[2];
@@ -1594,7 +1828,7 @@ ADS_STATUS ads_mod_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
 {
        if (!vals)
                return ads_modlist_add(ctx, mods, LDAP_MOD_DELETE, name, NULL);
-       return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE, 
+       return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE,
                               name, (const void **) vals);
 }
 
@@ -1606,7 +1840,7 @@ ADS_STATUS ads_mod_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
  * @param val The value to add - NULL means DELETE
  * @return ADS STATUS indicating success of add
  **/
-static ADS_STATUS ads_mod_ber(TALLOC_CTX *ctx, ADS_MODLIST *mods, 
+static ADS_STATUS ads_mod_ber(TALLOC_CTX *ctx, ADS_MODLIST *mods,
                              const char *name, const struct berval *val)
 {
        const struct berval *values[2];
@@ -1644,8 +1878,8 @@ ADS_STATUS ads_gen_mod(ADS_STRUCT *ads, const char *mod_dn, ADS_MODLIST mods)
        int ret,i;
        char *utf8_dn = NULL;
        size_t converted_size;
-       /* 
-          this control is needed to modify that contains a currently 
+       /*
+          this control is needed to modify that contains a currently
           non-existent attribute (but allowable for the object) to run
        */
        LDAPControl PermitModify = {
@@ -1690,7 +1924,7 @@ ADS_STATUS ads_gen_add(ADS_STRUCT *ads, const char *new_dn, ADS_MODLIST mods)
        DBG_INFO("AD LDAP: Adding %s\n", new_dn);
 
        if (!push_utf8_talloc(talloc_tos(), &utf8_dn, new_dn, &converted_size)) {
-               DEBUG(1, ("ads_gen_add: push_utf8_talloc failed!"));
+               DEBUG(1, ("ads_gen_add: push_utf8_talloc failed!\n"));
                return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
        }
 
@@ -1717,7 +1951,7 @@ ADS_STATUS ads_del_dn(ADS_STRUCT *ads, char *del_dn)
        char *utf8_dn = NULL;
        size_t converted_size;
        if (!push_utf8_talloc(talloc_tos(), &utf8_dn, del_dn, &converted_size)) {
-               DEBUG(1, ("ads_del_dn: push_utf8_talloc failed!"));
+               DEBUG(1, ("ads_del_dn: push_utf8_talloc failed!\n"));
                return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
        }
 
@@ -1740,7 +1974,9 @@ ADS_STATUS ads_del_dn(ADS_STRUCT *ads, char *del_dn)
  **/
 char *ads_ou_string(ADS_STRUCT *ads, const char *org_unit)
 {
+       ADS_STATUS status;
        char *ret = NULL;
+       char *dn = NULL;
 
        if (!org_unit || !*org_unit) {
 
@@ -1757,7 +1993,12 @@ char *ads_ou_string(ADS_STRUCT *ads, const char *org_unit)
        /* jmcd: removed "\\" from the separation chars, because it is
           needed as an escape for chars like '#' which are valid in an
           OU name */
-       return ads_build_path(org_unit, "/", "ou=", 1);
+       status = ads_build_path(org_unit, "/", "ou=", 1, &dn);
+       if (!ADS_ERR_OK(status)) {
+               return NULL;
+       }
+
+       return dn;
 }
 
 /**
@@ -1951,7 +2192,7 @@ uint32_t ads_get_machine_kvno(ADS_STRUCT *ads, const char *machine_name)
 
 /**
  * This clears out all registered spn's for a given hostname
- * @param ads An initilaized ADS_STRUCT
+ * @param ads An initialized ADS_STRUCT
  * @param machine_name the NetBIOS name of the computer.
  * @return 0 upon success, non-zero otherwise.
  **/
@@ -2111,7 +2352,7 @@ done:
  * @param machine_name the NetBIOS name of the computer, which is used to identify the computer account.
  * @param spns An array or strings for the service principals to add,
  *        i.e. 'cifs/machine_name', 'http/machine.full.domain.com' etc.
- * @return 0 upon sucess, or non-zero if a failure occurs
+ * @return 0 upon success, or non-zero if a failure occurs
  **/
 
 ADS_STATUS ads_add_service_principal_names(ADS_STRUCT *ads,
@@ -2303,7 +2544,7 @@ done:
 
 /**
  * adds a machine account to the ADS server
- * @param ads An intialized ADS_STRUCT
+ * @param ads An initialized ADS_STRUCT
  * @param machine_name - the NetBIOS machine name of this account.
  * @param account_type A number indicating the type of account to create
  * @param org_unit The LDAP path in which to place this account
@@ -2487,14 +2728,14 @@ done:
 
 /**
  * move a machine account to another OU on the ADS server
- * @param ads - An intialized ADS_STRUCT
+ * @param ads - An initialized ADS_STRUCT
  * @param machine_name - the NetBIOS machine name of this account.
  * @param org_unit - The LDAP path in which to place this account
  * @param moved - whether we moved the machine account (optional)
  * @return 0 upon success, or non-zero otherwise
 **/
 
-ADS_STATUS ads_move_machine_acct(ADS_STRUCT *ads, const char *machine_name, 
+ADS_STATUS ads_move_machine_acct(ADS_STRUCT *ads, const char *machine_name,
                                  const char *org_unit, bool *moved)
 {
        ADS_STATUS rc;
@@ -2535,7 +2776,7 @@ ADS_STATUS ads_move_machine_acct(ADS_STRUCT *ads, const char *machine_name,
                goto done;
        }
 
-       ldap_status = ldap_rename_s(ads->ldap.ld, computer_dn, computer_rdn, 
+       ldap_status = ldap_rename_s(ads->ldap.ld, computer_dn, computer_rdn,
                                    org_unit, 1, NULL, NULL);
        rc = ADS_ERROR(ldap_status);
 
@@ -2725,13 +2966,13 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
        if (!(ctx = talloc_init("ads_process_results")))
                return;
 
-       for (msg = ads_first_entry(ads, res); msg; 
+       for (msg = ads_first_entry(ads, res); msg;
             msg = ads_next_entry(ads, msg)) {
                char *utf8_field;
                BerElement *b;
 
                for (utf8_field=ldap_first_attribute(ads->ldap.ld,
-                                                    (LDAPMessage *)msg,&b); 
+                                                    (LDAPMessage *)msg,&b);
                     utf8_field;
                     utf8_field=ldap_next_attribute(ads->ldap.ld,
                                                    (LDAPMessage *)msg,b)) {
@@ -2739,13 +2980,13 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
                        char **str_vals;
                        char **utf8_vals;
                        char *field;
-                       bool string; 
+                       bool string;
 
                        if (!pull_utf8_talloc(ctx, &field, utf8_field,
                                              &converted_size))
                        {
                                DEBUG(0,("ads_process_results: "
-                                        "pull_utf8_talloc failed: %s",
+                                        "pull_utf8_talloc failed: %s\n",
                                         strerror(errno)));
                        }
 
@@ -2761,7 +3002,7 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
                                fn(ads, field, (void **) str_vals, data_area);
                                ldap_value_free(utf8_vals);
                        } else {
-                               ber_vals = ldap_get_values_len(ads->ldap.ld, 
+                               ber_vals = ldap_get_values_len(ads->ldap.ld,
                                                 (LDAPMessage *)msg, field);
                                fn(ads, field, (void **) ber_vals, data_area);
 
@@ -2904,7 +3145,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 }
 
 /**
- * pull an array of strings from a ADS result 
+ * pull an array of strings from a ADS result
  *  (handle large multivalue attributes with range retrieval)
  * @param ads connection to ads server
  * @param mem_ctx TALLOC_CTX to use for allocating result string
@@ -2916,7 +3157,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @param more_values Are there more values to get?
  * @return Result strings in talloc context
  **/
- char **ads_pull_strings_range(ADS_STRUCT *ads, 
+ char **ads_pull_strings_range(ADS_STRUCT *ads,
                               TALLOC_CTX *mem_ctx,
                               LDAPMessage *msg, const char *field,
                               char **current_strings,
@@ -2925,7 +3166,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
                               bool *more_strings)
 {
        char *attr;
-       char *expected_range_attrib, *range_attr;
+       char *expected_range_attrib, *range_attr = NULL;
        BerElement *ptr = NULL;
        char **strings;
        char **new_strings;
@@ -2942,8 +3183,8 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
        expected_range_attrib = talloc_asprintf(mem_ctx, "%s;Range=", field);
 
        /* look for Range result */
-       for (attr = ldap_first_attribute(ads->ldap.ld, (LDAPMessage *)msg, &ptr); 
-            attr; 
+       for (attr = ldap_first_attribute(ads->ldap.ld, (LDAPMessage *)msg, &ptr);
+            attr;
             attr = ldap_next_attribute(ads->ldap.ld, (LDAPMessage *)msg, ptr)) {
                /* we ignore the fact that this is utf8, as all attributes are ascii... */
                if (strnequal(attr, expected_range_attrib, strlen(expected_range_attrib))) {
@@ -2952,22 +3193,22 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
                }
                ldap_memfree(attr);
        }
-       if (!attr) {
+       if (!range_attr) {
                ber_free(ptr, 0);
                /* nothing here - this field is just empty */
                *more_strings = False;
                return NULL;
        }
 
-       if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-%lu", 
+       if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-%lu",
                   &range_start, &range_end) == 2) {
                *more_strings = True;
        } else {
-               if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-*", 
+               if (sscanf(&range_attr[strlen(expected_range_attrib)], "%lu-*",
                           &range_start) == 1) {
                        *more_strings = False;
                } else {
-                       DEBUG(1, ("ads_pull_strings_range:  Cannot parse Range attriubte (%s)\n", 
+                       DEBUG(1, ("ads_pull_strings_range:  Cannot parse Range attribute (%s)\n",
                                  range_attr));
                        ldap_memfree(range_attr);
                        *more_strings = False;
@@ -2977,7 +3218,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 
        if ((*num_strings) != range_start) {
                DEBUG(1, ("ads_pull_strings_range: Range attribute (%s) doesn't start at %u, but at %lu"
-                         " - aborting range retreival\n",
+                         " - aborting range retrieval\n",
                          range_attr, (unsigned int)(*num_strings) + 1, range_start));
                ldap_memfree(range_attr);
                *more_strings = False;
@@ -2988,8 +3229,8 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 
        if (*more_strings && ((*num_strings + num_new_strings) != (range_end + 1))) {
                DEBUG(1, ("ads_pull_strings_range: Range attribute (%s) tells us we have %lu "
-                         "strings in this bunch, but we only got %lu - aborting range retreival\n",
-                         range_attr, (unsigned long int)range_end - range_start + 1, 
+                         "strings in this bunch, but we only got %lu - aborting range retrieval\n",
+                         range_attr, (unsigned long int)range_end - range_start + 1,
                          (unsigned long int)num_new_strings));
                ldap_memfree(range_attr);
                *more_strings = False;
@@ -3014,7 +3255,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 
        if (*more_strings) {
                *next_attribute = talloc_asprintf(mem_ctx,
-                                                 "%s;range=%d-*", 
+                                                 "%s;range=%d-*",
                                                  field,
                                                  (int)*num_strings);
 
@@ -3037,7 +3278,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @param msg Results of search
  * @param field Attribute to retrieve
  * @param v Pointer to int to store result
- * @return boolean inidicating success
+ * @return boolean indicating success
 */
  bool ads_pull_uint32(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
                      uint32_t *v)
@@ -3086,7 +3327,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @param msg Results of search
  * @param field Attribute to retrieve
  * @param sid Pointer to sid to store result
- * @return boolean inidicating success
+ * @return boolean indicating success
 */
  bool ads_pull_sid(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
                   struct dom_sid *sid)
@@ -3151,7 +3392,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @param msg Results of search
  * @param field Attribute to retrieve
  * @param sd Pointer to *struct security_descriptor to store result (talloc()ed)
- * @return boolean inidicating success
+ * @return boolean indicating success
 */
  bool ads_pull_sd(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
                  LDAPMessage *msg, const char *field,
@@ -3180,9 +3421,9 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
        return ret;
 }
 
-/* 
- * in order to support usernames longer than 21 characters we need to 
- * use both the sAMAccountName and the userPrincipalName attributes 
+/*
+ * in order to support usernames longer than 21 characters we need to
+ * use both the sAMAccountName and the userPrincipalName attributes
  * It seems that not all users have the userPrincipalName attribute set
  *
  * @param ads connection to ads server
@@ -3196,7 +3437,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 #if 0  /* JERRY */
        char *ret, *p;
 
-       /* lookup_name() only works on the sAMAccountName to 
+       /* lookup_name() only works on the sAMAccountName to
           returning the username portion of userPrincipalName
           breaks winbindd_getpwnam() */
 
@@ -3224,7 +3465,7 @@ ADS_STATUS ads_USN(ADS_STRUCT *ads, uint32_t *usn)
        LDAPMessage *res;
 
        status = ads_do_search_retry(ads, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
-       if (!ADS_ERR_OK(status)) 
+       if (!ADS_ERR_OK(status))
                return status;
 
        if (ads_count_replies(ads, res) != 1) {
@@ -3250,8 +3491,8 @@ static time_t ads_parse_time(const char *str)
 
        ZERO_STRUCT(tm);
 
-       if (sscanf(str, "%4d%2d%2d%2d%2d%2d", 
-                  &tm.tm_year, &tm.tm_mon, &tm.tm_mday, 
+       if (sscanf(str, "%4d%2d%2d%2d%2d%2d",
+                  &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
                   &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
                return 0;
        }
@@ -3270,13 +3511,9 @@ ADS_STATUS ads_current_time(ADS_STRUCT *ads)
        ADS_STATUS status;
        LDAPMessage *res;
        char *timestr;
-       TALLOC_CTX *ctx;
+       TALLOC_CTX *tmp_ctx = talloc_stackframe();
        ADS_STRUCT *ads_s = ads;
 
-       if (!(ctx = talloc_init("ads_current_time"))) {
-               return ADS_ERROR(LDAP_NO_MEMORY);
-       }
-
         /* establish a new ldap tcp session if necessary */
 
        if ( !ads->ldap.ld ) {
@@ -3294,7 +3531,8 @@ ADS_STATUS ads_current_time(ADS_STRUCT *ads)
                 * through ads_find_dc() again we want to avoid repeating.
                 */
                if (is_zero_addr(&ads->ldap.ss)) {
-                       ads_s = ads_init(ads->server.realm,
+                       ads_s = ads_init(tmp_ctx,
+                                        ads->server.realm,
                                         ads->server.workgroup,
                                         ads->server.ldap_server,
                                         ADS_SASL_PLAIN );
@@ -3303,6 +3541,13 @@ ADS_STATUS ads_current_time(ADS_STRUCT *ads)
                                goto done;
                        }
                }
+
+               /*
+                * Reset ads->config.flags as it can contain the flags
+                * returned by the previous CLDAP ping when reusing the struct.
+                */
+               ads_s->config.flags = 0;
+
                ads_s->auth.flags = ADS_AUTH_ANON_BIND;
                status = ads_connect( ads_s );
                if ( !ADS_ERR_OK(status))
@@ -3314,14 +3559,14 @@ ADS_STATUS ads_current_time(ADS_STRUCT *ads)
                goto done;
        }
 
-       timestr = ads_pull_string(ads_s, ctx, res, "currentTime");
+       timestr = ads_pull_string(ads_s, tmp_ctx, res, "currentTime");
        if (!timestr) {
                ads_msgfree(ads_s, res);
                status = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
                goto done;
        }
 
-       /* but save the time and offset in the original ADS_STRUCT */   
+       /* but save the time and offset in the original ADS_STRUCT */
 
        ads->config.current_time = ads_parse_time(timestr);
 
@@ -3335,11 +3580,7 @@ ADS_STATUS ads_current_time(ADS_STRUCT *ads)
        status = ADS_SUCCESS;
 
 done:
-       /* free any temporary ads connections */
-       if ( ads_s != ads ) {
-               ads_destroy( &ads_s );
-       }
-       talloc_destroy(ctx);
+       TALLOC_FREE(tmp_ctx);
 
        return status;
 }
@@ -3349,6 +3590,7 @@ done:
 
 ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32_t *val)
 {
+       TALLOC_CTX *tmp_ctx = talloc_stackframe();
        const char *attrs[] = {"domainFunctionality", NULL};
        ADS_STATUS status;
        LDAPMessage *res;
@@ -3373,7 +3615,8 @@ ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32_t *val)
                 * through ads_find_dc() again we want to avoid repeating.
                 */
                if (is_zero_addr(&ads->ldap.ss)) {
-                       ads_s = ads_init(ads->server.realm,
+                       ads_s = ads_init(tmp_ctx,
+                                        ads->server.realm,
                                         ads->server.workgroup,
                                         ads->server.ldap_server,
                                         ADS_SASL_PLAIN );
@@ -3382,13 +3625,20 @@ ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32_t *val)
                                goto done;
                        }
                }
+
+               /*
+                * Reset ads->config.flags as it can contain the flags
+                * returned by the previous CLDAP ping when reusing the struct.
+                */
+               ads_s->config.flags = 0;
+
                ads_s->auth.flags = ADS_AUTH_ANON_BIND;
                status = ads_connect( ads_s );
                if ( !ADS_ERR_OK(status))
                        goto done;
        }
 
-       /* If the attribute does not exist assume it is a Windows 2000 
+       /* If the attribute does not exist assume it is a Windows 2000
           functional domain */
 
        status = ads_do_search(ads_s, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
@@ -3405,13 +3655,10 @@ ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32_t *val)
        DEBUG(3,("ads_domain_func_level: %d\n", *val));
 
 
-       ads_msgfree(ads, res);
+       ads_msgfree(ads_s, res);
 
 done:
-       /* free any temporary ads connections */
-       if ( ads_s != ads ) {
-               ads_destroy( &ads_s );
-       }
+       TALLOC_FREE(tmp_ctx);
 
        return status;
 }
@@ -3428,7 +3675,7 @@ ADS_STATUS ads_domain_sid(ADS_STRUCT *ads, struct dom_sid *sid)
        LDAPMessage *res;
        ADS_STATUS rc;
 
-       rc = ads_do_search_retry(ads, ads->config.bind_path, LDAP_SCOPE_BASE, "(objectclass=*)", 
+       rc = ads_do_search_retry(ads, ads->config.bind_path, LDAP_SCOPE_BASE, "(objectclass=*)",
                           attrs, &res);
        if (!ADS_ERR_OK(rc)) return rc;
        if (!ads_pull_sid(ads, res, "objectSid", sid)) {
@@ -3441,7 +3688,7 @@ ADS_STATUS ads_domain_sid(ADS_STRUCT *ads, struct dom_sid *sid)
 }
 
 /**
- * find our site name 
+ * find our site name
  * @param ads connection to ads server
  * @param mem_ctx Pointer to talloc context
  * @param site_name Pointer to the sitename
@@ -3481,7 +3728,7 @@ ADS_STATUS ads_site_dn(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const char **site_n
        return status;
        /*
        dsServiceName: CN=NTDS Settings,CN=W2K3DC,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=ber,DC=suse,DC=de
-       */                                               
+       */
 }
 
 /**
@@ -3515,7 +3762,7 @@ ADS_STATUS ads_site_dn_for_machine(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const c
                return ADS_ERROR(LDAP_NO_MEMORY);
        }
 
-       status = ads_do_search(ads, config_context, LDAP_SCOPE_SUBTREE, 
+       status = ads_do_search(ads, config_context, LDAP_SCOPE_SUBTREE,
                               filter, NULL, &res);
        if (!ADS_ERR_OK(status)) {
                return status;
@@ -3793,7 +4040,7 @@ static char **get_addl_hosts(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
 
        /*
         * Windows DC implicitly adds a short name for each FQDN added to
-        * msDS-AdditionalDnsHostName, but it comes with a strage binary
+        * msDS-AdditionalDnsHostName, but it comes with a strange binary
         * suffix "\0$" which we should ignore (see bug #14406).
         */
 
@@ -4222,7 +4469,7 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
 }
 
 /**
- * Find a sAMAccoutName in LDAP
+ * Find a sAMAccountName in LDAP
  * @param ads connection to ads server
  * @param mem_ctx TALLOC_CTX for allocating sid array
  * @param samaccountname to search
@@ -4293,14 +4540,14 @@ ADS_STATUS ads_find_samaccount(ADS_STRUCT *ads,
 }
 
 /**
- * find our configuration path 
+ * find our configuration path
  * @param ads connection to ads server
  * @param mem_ctx Pointer to talloc context
  * @param config_path Pointer to the config path
  * @return status of search
  **/
-ADS_STATUS ads_config_path(ADS_STRUCT *ads, 
-                          TALLOC_CTX *mem_ctx, 
+ADS_STATUS ads_config_path(ADS_STRUCT *ads,
+                          TALLOC_CTX *mem_ctx,
                           char **config_path)
 {
        ADS_STATUS status;
@@ -4308,13 +4555,13 @@ ADS_STATUS ads_config_path(ADS_STRUCT *ads,
        const char *config_context = NULL;
        const char *attrs[] = { "configurationNamingContext", NULL };
 
-       status = ads_do_search(ads, "", LDAP_SCOPE_BASE, 
+       status = ads_do_search(ads, "", LDAP_SCOPE_BASE,
                               "(objectclass=*)", attrs, &res);
        if (!ADS_ERR_OK(status)) {
                return status;
        }
 
-       config_context = ads_pull_string(ads, mem_ctx, res, 
+       config_context = ads_pull_string(ads, mem_ctx, res,
                                         "configurationNamingContext");
        ads_msgfree(ads, res);
        if (!config_context) {
@@ -4332,16 +4579,16 @@ ADS_STATUS ads_config_path(ADS_STRUCT *ads,
 }
 
 /**
- * find the displayName of an extended right 
+ * find the displayName of an extended right
  * @param ads connection to ads server
  * @param config_path The config path
  * @param mem_ctx Pointer to talloc context
  * @param GUID struct of the rightsGUID
  * @return status of search
  **/
-const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads, 
-                                               const char *config_path, 
-                                               TALLOC_CTX *mem_ctx, 
+const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads,
+                                               const char *config_path,
+                                               TALLOC_CTX *mem_ctx,
                                                const struct GUID *rights_guid)
 {
        ADS_STATUS rc;
@@ -4355,7 +4602,7 @@ const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads,
                goto done;
        }
 
-       expr = talloc_asprintf(mem_ctx, "(rightsGuid=%s)", 
+       expr = talloc_asprintf(mem_ctx, "(rightsGuid=%s)",
                               GUID_string(mem_ctx, rights_guid));
        if (!expr) {
                goto done;
@@ -4366,7 +4613,7 @@ const char *ads_get_extended_right_name_by_guid(ADS_STRUCT *ads,
                goto done;
        }
 
-       rc = ads_do_search_retry(ads, path, LDAP_SCOPE_SUBTREE, 
+       rc = ads_do_search_retry(ads, path, LDAP_SCOPE_SUBTREE,
                                 expr, attrs, &res);
        if (!ADS_ERR_OK(rc)) {
                goto done;