s3:libads: Improve logging for failover scenarios
[samba.git] / source3 / libads / ldap.c
index e0f35609294279b65d3406f37d9d459315f74287..acf558a7ab338e7f7fce6d5c80f8197cb4fe1f91 100644 (file)
@@ -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
@@ -92,7 +94,25 @@ static void gotalarm_sig(int signum)
                return NULL;
        }
 
-#ifdef HAVE_LDAP_INITIALIZE
+#ifdef HAVE_LDAP_INIT_FD
+       {
+               int fd = -1;
+               NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
+               unsigned timeout_ms = 1000 * to;
+
+               status = open_socket_out(ss, port, timeout_ms, &fd);
+               if (!NT_STATUS_IS_OK(status)) {
+                       DEBUG(3, ("open_socket_out: failed to open socket\n"));
+                       return NULL;
+               }
+
+/* define LDAP_PROTO_TCP from openldap.h if required */
+#ifndef LDAP_PROTO_TCP
+#define LDAP_PROTO_TCP 1
+#endif
+               ldap_err = ldap_init_fd(fd, LDAP_PROTO_TCP, uri, &ldp);
+       }
+#elif defined(HAVE_LDAP_INITIALIZE)
        ldap_err = ldap_initialize(&ldp, uri);
 #else
        ldp = ldap_open(server, port);
@@ -145,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);
@@ -225,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;
 
@@ -322,39 +359,229 @@ 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.
  Take note of and update negative connection cache.
 **********************************************************************/
 
-static NTSTATUS cldap_ping_list(ADS_STRUCT *ads,const char *domain,
-                               struct ip_service *ip_list, int count)
+static NTSTATUS cldap_ping_list(ADS_STRUCT *ads,
+                       const char *domain,
+                       struct samba_sockaddr *sa_list,
+                       size_t count)
 {
-       int i;
-       bool ok;
+       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 = 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), &ip_list[i].ss);
+               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;
+               }
 
-               /* Returns ok only if it matches the correct server type */
-               ok = ads_try_connect(ads, false, &ip_list[i].ss);
+               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;
+               }
+
+               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;
 }
 
@@ -365,15 +592,20 @@ static NTSTATUS cldap_ping_list(ADS_STRUCT *ads,const char *domain,
 static NTSTATUS resolve_and_ping_netbios(ADS_STRUCT *ads,
                                         const char *domain, const char *realm)
 {
-       int count, i;
-       struct ip_service *ip_list;
-       NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
+       size_t i;
+       size_t count = 0;
+       struct samba_sockaddr *sa_list = NULL;
+       NTSTATUS status;
 
        DEBUG(6, ("resolve_and_ping_netbios: (cldap) looking for domain '%s'\n",
                  domain));
 
-       status = get_sorted_dc_list(domain, NULL, &ip_list, &count,
-                                   false);
+       status = get_sorted_dc_list(talloc_tos(),
+                               domain,
+                               NULL,
+                               &sa_list,
+                               &count,
+                               false);
        if (!NT_STATUS_IS_OK(status)) {
                return status;
        }
@@ -384,7 +616,7 @@ static NTSTATUS resolve_and_ping_netbios(ADS_STRUCT *ads,
                for (i = 0; i < count; ++i) {
                        char server[INET6_ADDRSTRLEN];
 
-                       print_sockaddr(server, sizeof(server), &ip_list[i].ss);
+                       print_sockaddr(server, sizeof(server), &sa_list[i].u.ss);
 
                        if(!NT_STATUS_IS_OK(
                                check_negative_conn_cache(realm, server))) {
@@ -397,9 +629,9 @@ static NTSTATUS resolve_and_ping_netbios(ADS_STRUCT *ads,
                }
        }
 
-       status = cldap_ping_list(ads, domain, ip_list, count);
+       status = cldap_ping_list(ads, domain, sa_list, count);
 
-       SAFE_FREE(ip_list);
+       TALLOC_FREE(sa_list);
 
        return status;
 }
@@ -412,30 +644,34 @@ static NTSTATUS resolve_and_ping_netbios(ADS_STRUCT *ads,
 static NTSTATUS resolve_and_ping_dns(ADS_STRUCT *ads, const char *sitename,
                                     const char *realm)
 {
-       int count;
-       struct ip_service *ip_list = NULL;
-       NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
+       size_t count = 0;
+       struct samba_sockaddr *sa_list = NULL;
+       NTSTATUS status;
 
        DEBUG(6, ("resolve_and_ping_dns: (cldap) looking for realm '%s'\n",
                  realm));
 
-       status = get_sorted_dc_list(realm, sitename, &ip_list, &count,
-                                   true);
+       status = get_sorted_dc_list(talloc_tos(),
+                               realm,
+                               sitename,
+                               &sa_list,
+                               &count,
+                               true);
        if (!NT_STATUS_IS_OK(status)) {
-               SAFE_FREE(ip_list);
+               TALLOC_FREE(sa_list);
                return status;
        }
 
-       status = cldap_ping_list(ads, realm, ip_list, count);
+       status = cldap_ping_list(ads, realm, sa_list, count);
 
-       SAFE_FREE(ip_list);
+       TALLOC_FREE(sa_list);
 
        return status;
 }
 
 /**********************************************************************
  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
 **********************************************************************/
 
@@ -499,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
@@ -576,8 +816,34 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
        ADS_STATUS status;
        NTSTATUS ntstatus;
        char addr[INET6_ADDRSTRLEN];
+       struct sockaddr_storage existing_ss;
 
-       ZERO_STRUCT(ads->ldap);
+       zero_sockaddr(&existing_ss);
+
+       /*
+        * ads_connect can be passed in a reused ADS_STRUCT
+        * with an existing non-zero ads->ldap.ss IP address
+        * that was stored by going through ads_find_dc()
+        * if ads->server.ldap_server was NULL.
+        *
+        * If ads->server.ldap_server is still NULL but
+        * the target address isn't the zero address, then
+        * store that address off off before zeroing out
+        * ads->ldap so we don't keep doing multiple calls
+        * to ads_find_dc() in the reuse case.
+        *
+        * If a caller wants a clean ADS_STRUCT they
+        * 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.
+        */
+       if (ads->server.ldap_server == NULL && !is_zero_addr(&ads->ldap.ss)) {
+               /* Save off the address we previously found by ads_find_dc(). */
+               existing_ss = ads->ldap.ss;
+       }
+
+       ads_zero_ldap(ads);
        ZERO_STRUCT(ads->ldap_wrap_data);
        ads->ldap.last_attempt  = time_mono(NULL);
        ads->ldap_wrap_data.wrap_type   = ADS_SASLWRAP_TYPE_PLAIN;
@@ -595,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",
@@ -602,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;
@@ -622,6 +896,22 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                }
        }
 
+       if (!is_zero_addr(&existing_ss)) {
+               /* We saved off who we should talk to. */
+               bool ok = ads_try_connect(ads,
+                                         ads->server.gc,
+                                         &existing_ss);
+               if (ok) {
+                       goto got_connection;
+               }
+               /*
+                * 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);
        if (NT_STATUS_IS_OK(ntstatus)) {
                goto got_connection;
@@ -638,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 */
@@ -669,7 +970,7 @@ got_connection:
 
        /* Otherwise setup the TCP LDAP session */
 
-       ads->ldap.ld = ldap_open_with_timeout(addr,
+       ads->ldap.ld = ldap_open_with_timeout(ads->config.ldap_server_name,
                                              &ads->ldap.ss,
                                              ads->ldap.port, lp_ldap_timeout());
        if (ads->ldap.ld == NULL) {
@@ -686,13 +987,6 @@ got_connection:
 
        ldap_set_option(ads->ldap.ld, LDAP_OPT_PROTOCOL_VERSION, &version);
 
-       if ( lp_ldap_ssl_ads() ) {
-               status = ADS_ERROR(smbldap_start_tls(ads->ldap.ld, version));
-               if (!ADS_ERR_OK(status)) {
-                       goto out;
-               }
-       }
-
        /* fill in the current time and offsets */
 
        status = ads_current_time( ads );
@@ -738,6 +1032,25 @@ ADS_STATUS ads_connect_user_creds(ADS_STRUCT *ads)
        return ads_connect(ads);
 }
 
+/**
+ * Zero out the internal ads->ldap struct and initialize the address to zero IP.
+ * @param ads Pointer to an existing ADS_STRUCT
+ *
+ * Sets the ads->ldap.ss to a valid
+ * zero ip address that can be detected by
+ * our is_zero_addr() function. Otherwise
+ * it is left as AF_UNSPEC (0).
+ **/
+void ads_zero_ldap(ADS_STRUCT *ads)
+{
+       ZERO_STRUCT(ads->ldap);
+       /*
+        * Initialize the sockaddr_storage so we can use
+        * sockaddr test functions against it.
+        */
+       zero_sockaddr(&ads->ldap.ss);
+}
+
 /**
  * Disconnect the LDAP server
  * @param ads Pointer to an existing ADS_STRUCT
@@ -755,7 +1068,7 @@ void ads_disconnect(ADS_STRUCT *ads)
        if (ads->ldap_wrap_data.mem_ctx) {
                talloc_free(ads->ldap_wrap_data.mem_ctx);
        }
-       ZERO_STRUCT(ads->ldap);
+       ads_zero_ldap(ads);
        ZERO_STRUCT(ads->ldap_wrap_data);
 }
 
@@ -782,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;
@@ -843,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;
@@ -852,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
@@ -867,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;
@@ -887,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))
@@ -934,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) {
 
@@ -980,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);
@@ -1069,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);
@@ -1077,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
@@ -1100,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
@@ -1140,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;
@@ -1167,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;
@@ -1206,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)
 {
@@ -1217,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;
        }
@@ -1239,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;
                }
@@ -1249,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);
 
@@ -1272,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);
 }
 
@@ -1283,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=*)",
@@ -1366,19 +1679,45 @@ char *ads_parent_dn(const char *dn)
 {
        ADS_STATUS status;
        char *expr;
-       const char *attrs[] = {"*", "msDS-SupportedEncryptionTypes", "nTSecurityDescriptor", NULL};
+       const char *attrs[] = {
+               /* This is how Windows checks for machine accounts */
+               "objectClass",
+               "SamAccountName",
+               "userAccountControl",
+               "DnsHostName",
+               "ServicePrincipalName",
+               "userPrincipalName",
+               "unicodePwd",
+
+               /* Additional attributes Samba checks */
+               "msDS-AdditionalDnsHostName",
+               "msDS-SupportedEncryptionTypes",
+               "nTSecurityDescriptor",
+               "objectSid",
+
+               NULL
+       };
+       TALLOC_CTX *frame = talloc_stackframe();
 
        *res = NULL;
 
        /* the easiest way to find a machine account anywhere in the tree
           is to look for hostname$ */
-       if (asprintf(&expr, "(samAccountName=%s$)", machine) == -1) {
-               DEBUG(1, ("asprintf failed!\n"));
-               return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
+       expr = talloc_asprintf(frame, "(samAccountName=%s$)", machine);
+       if (expr == NULL) {
+               status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
+               goto done;
        }
 
        status = ads_search(ads, res, expr, attrs);
-       SAFE_FREE(expr);
+       if (ADS_ERR_OK(status)) {
+               if (ads_count_replies(ads, *res) != 1) {
+                       status = ADS_ERROR_LDAP(LDAP_NO_SUCH_OBJECT);
+               }
+       }
+
+done:
+       TALLOC_FREE(frame);
        return status;
 }
 
@@ -1404,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;
@@ -1434,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;
@@ -1463,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];
@@ -1489,11 +1828,10 @@ 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);
 }
 
-#if 0
 /**
  * Add a single ber-encoded value to a mod list
  * @param ctx An initialized TALLOC_CTX
@@ -1502,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];
@@ -1514,15 +1852,16 @@ static ADS_STATUS ads_mod_ber(TALLOC_CTX *ctx, ADS_MODLIST *mods,
        return ads_modlist_add(ctx, mods, LDAP_MOD_REPLACE|LDAP_MOD_BVALUES,
                               name, (const void **) values);
 }
-#endif
 
 static void ads_print_error(int ret, LDAP *ld)
 {
        if (ret != 0) {
                char *ld_error = NULL;
                ldap_get_option(ld, LDAP_OPT_ERROR_STRING, &ld_error);
-               DEBUG(10,("AD LDAP failure %d (%s):\n%s\n", ret,
-                       ldap_err2string(ret), ld_error));
+               DBG_ERR("AD LDAP ERROR: %d (%s): %s\n",
+                       ret,
+                       ldap_err2string(ret),
+                       ld_error);
                SAFE_FREE(ld_error);
        }
 }
@@ -1539,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 = {
@@ -1549,6 +1888,8 @@ ADS_STATUS ads_gen_mod(ADS_STRUCT *ads, const char *mod_dn, ADS_MODLIST mods)
                (char) 1};
        LDAPControl *controls[2];
 
+       DBG_INFO("AD LDAP: Modifying %s\n", mod_dn);
+
        controls[0] = &PermitModify;
        controls[1] = NULL;
 
@@ -1580,8 +1921,10 @@ ADS_STATUS ads_gen_add(ADS_STRUCT *ads, const char *new_dn, ADS_MODLIST mods)
        char *utf8_dn = NULL;
        size_t converted_size;
 
+       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);
        }
 
@@ -1590,7 +1933,7 @@ ADS_STATUS ads_gen_add(ADS_STRUCT *ads, const char *new_dn, ADS_MODLIST mods)
        /* make sure the end of the list is NULL */
        mods[i] = NULL;
 
-       ret = ldap_add_s(ads->ldap.ld, utf8_dn, (LDAPMod**)mods);
+       ret = ldap_add_ext_s(ads->ldap.ld, utf8_dn, (LDAPMod**)mods, NULL, NULL);
        ads_print_error(ret, ads->ldap.ld);
        TALLOC_FREE(utf8_dn);
        return ADS_ERROR(ret);
@@ -1608,10 +1951,12 @@ 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);
        }
 
+       DBG_INFO("AD LDAP: Deleting %s\n", del_dn);
+
        ret = ldap_delete_s(ads->ldap.ld, utf8_dn);
        ads_print_error(ret, ads->ldap.ld);
        TALLOC_FREE(utf8_dn);
@@ -1629,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) {
 
@@ -1646,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;
 }
 
 /**
@@ -1772,7 +2124,7 @@ uint32_t ads_get_kvno(ADS_STRUCT *ads, const char *account_name)
        char *filter;
        const char *attrs[] = {"msDS-KeyVersionNumber", NULL};
        char *dn_string = NULL;
-       ADS_STATUS ret = ADS_ERROR(LDAP_SUCCESS);
+       ADS_STATUS ret;
 
        DEBUG(5,("ads_get_kvno: Searching for account %s\n", account_name));
        if (asprintf(&filter, "(samAccountName=%s)", account_name) == -1) {
@@ -1840,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.
  **/
@@ -1851,15 +2203,15 @@ ADS_STATUS ads_clear_service_principal_names(ADS_STRUCT *ads, const char *machin
        LDAPMessage *res = NULL;
        ADS_MODLIST mods;
        const char *servicePrincipalName[1] = {NULL};
-       ADS_STATUS ret = ADS_ERROR(LDAP_SUCCESS);
+       ADS_STATUS ret;
        char *dn_string = NULL;
 
        ret = ads_find_machine_acct(ads, &res, machine_name);
-       if (!ADS_ERR_OK(ret) || ads_count_replies(ads, res) != 1) {
+       if (!ADS_ERR_OK(ret)) {
                DEBUG(5,("ads_clear_service_principal_names: WARNING: Host Account for %s not found... skipping operation.\n", machine_name));
                DEBUG(5,("ads_clear_service_principal_names: WARNING: Service Principals for %s have NOT been cleared.\n", machine_name));
                ads_msgfree(ads, res);
-               return ADS_ERROR(LDAP_NO_SUCH_OBJECT);
+               return ret;
        }
 
        DEBUG(5,("ads_clear_service_principal_names: Host account for %s found\n", machine_name));
@@ -2000,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,
@@ -2015,12 +2367,12 @@ ADS_STATUS ads_add_service_principal_names(ADS_STRUCT *ads,
        const char **servicePrincipalName = spns;
 
        ret = ads_find_machine_acct(ads, &res, machine_name);
-       if (!ADS_ERR_OK(ret) || ads_count_replies(ads, res) != 1) {
+       if (!ADS_ERR_OK(ret)) {
                DEBUG(1,("ads_add_service_principal_name: WARNING: Host Account for %s not found... skipping operation.\n",
                        machine_name));
                DEBUG(1,("ads_add_service_principal_name: WARNING: Service Principals have NOT been added.\n"));
                ads_msgfree(ads, res);
-               return ADS_ERROR(LDAP_NO_SUCH_OBJECT);
+               return ret;
        }
 
        DEBUG(1,("ads_add_service_principal_name: Host account for %s found\n", machine_name));
@@ -2069,9 +2421,130 @@ ADS_STATUS ads_add_service_principal_names(ADS_STRUCT *ads,
        return ret;
 }
 
+static uint32_t ads_get_acct_ctrl(ADS_STRUCT *ads,
+                                 LDAPMessage *msg)
+{
+       uint32_t acct_ctrl = 0;
+       bool ok;
+
+       ok = ads_pull_uint32(ads, msg, "userAccountControl", &acct_ctrl);
+       if (!ok) {
+               return 0;
+       }
+
+       return acct_ctrl;
+}
+
+static ADS_STATUS ads_change_machine_acct(ADS_STRUCT *ads,
+                                         LDAPMessage *msg,
+                                         const struct berval *machine_pw_val)
+{
+       ADS_MODLIST mods;
+       ADS_STATUS ret;
+       TALLOC_CTX *frame = talloc_stackframe();
+       uint32_t acct_control;
+       char *control_str = NULL;
+       const char *attrs[] = {
+               "objectSid",
+               NULL
+       };
+       LDAPMessage *res = NULL;
+       char *dn = NULL;
+
+       dn = ads_get_dn(ads, frame, msg);
+       if (dn == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto done;
+       }
+
+       acct_control = ads_get_acct_ctrl(ads, msg);
+       if (acct_control == 0) {
+               ret = ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
+               goto done;
+       }
+
+       /*
+        * Changing the password, disables the account. So we need to change the
+        * userAccountControl flags to enable it again.
+        */
+       mods = ads_init_mods(frame);
+       if (mods == NULL) {
+               ret = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
+               goto done;
+       }
+
+       ads_mod_ber(frame, &mods, "unicodePwd", machine_pw_val);
+
+       ret = ads_gen_mod(ads, dn, mods);
+       if (!ADS_ERR_OK(ret)) {
+               goto done;
+       }
+       TALLOC_FREE(mods);
+
+       /*
+        * To activate the account, we need to disable and enable it.
+        */
+       acct_control |= UF_ACCOUNTDISABLE;
+
+       control_str = talloc_asprintf(frame, "%u", acct_control);
+       if (control_str == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto done;
+       }
+
+       mods = ads_init_mods(frame);
+       if (mods == NULL) {
+               ret = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
+               goto done;
+       }
+
+       ads_mod_str(frame, &mods, "userAccountControl", control_str);
+
+       ret = ads_gen_mod(ads, dn, mods);
+       if (!ADS_ERR_OK(ret)) {
+               goto done;
+       }
+       TALLOC_FREE(mods);
+       TALLOC_FREE(control_str);
+
+       /*
+        * Enable the account again.
+        */
+       acct_control &= ~UF_ACCOUNTDISABLE;
+
+       control_str = talloc_asprintf(frame, "%u", acct_control);
+       if (control_str == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto done;
+       }
+
+       mods = ads_init_mods(frame);
+       if (mods == NULL) {
+               ret = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
+               goto done;
+       }
+
+       ads_mod_str(frame, &mods, "userAccountControl", control_str);
+
+       ret = ads_gen_mod(ads, dn, mods);
+       if (!ADS_ERR_OK(ret)) {
+               goto done;
+       }
+       TALLOC_FREE(mods);
+       TALLOC_FREE(control_str);
+
+       ret = ads_search_dn(ads, &res, dn, attrs);
+       ads_msgfree(ads, res);
+
+done:
+       talloc_free(frame);
+
+       return ret;
+}
+
 /**
  * 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
@@ -2080,74 +2553,174 @@ ADS_STATUS ads_add_service_principal_names(ADS_STRUCT *ads,
 
 ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads,
                                   const char *machine_name,
+                                  const char *machine_password,
                                   const char *org_unit,
-                                  uint32_t etype_list)
+                                  uint32_t etype_list,
+                                  const char *dns_domain_name)
 {
        ADS_STATUS ret;
-       char *samAccountName, *controlstr;
-       TALLOC_CTX *ctx;
+       char *samAccountName = NULL;
+       char *controlstr = NULL;
+       TALLOC_CTX *ctx = NULL;
        ADS_MODLIST mods;
        char *machine_escaped = NULL;
-       char *new_dn;
-       const char *objectClass[] = {"top", "person", "organizationalPerson",
-                                    "user", "computer", NULL};
+       char *dns_hostname = NULL;
+       char *new_dn = NULL;
+       char *utf8_pw = NULL;
+       size_t utf8_pw_len = 0;
+       char *utf16_pw = NULL;
+       size_t utf16_pw_len = 0;
+       struct berval machine_pw_val;
+       bool ok;
+       const char **spn_array = NULL;
+       size_t num_spns = 0;
+       const char *spn_prefix[] = {
+               "HOST",
+               "RestrictedKrbHost",
+       };
+       size_t i;
        LDAPMessage *res = NULL;
-       uint32_t acct_control = ( UF_WORKSTATION_TRUST_ACCOUNT |\
-                               UF_DONT_EXPIRE_PASSWD |\
-                               UF_ACCOUNTDISABLE );
-       uint32_t func_level = 0;
+       uint32_t acct_control = UF_WORKSTATION_TRUST_ACCOUNT;
 
-       ret = ads_domain_func_level(ads, &func_level);
-       if (!ADS_ERR_OK(ret)) {
-               return ret;
+       ctx = talloc_init("ads_add_machine_acct");
+       if (ctx == NULL) {
+               return ADS_ERROR(LDAP_NO_MEMORY);
        }
 
-       if (!(ctx = talloc_init("ads_add_machine_acct")))
-               return ADS_ERROR(LDAP_NO_MEMORY);
+       machine_escaped = escape_rdn_val_string_alloc(machine_name);
+       if (machine_escaped == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto done;
+       }
 
-       ret = ADS_ERROR(LDAP_NO_MEMORY);
+       utf8_pw = talloc_asprintf(ctx, "\"%s\"", machine_password);
+       if (utf8_pw == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto done;
+       }
+       utf8_pw_len = strlen(utf8_pw);
 
-       machine_escaped = escape_rdn_val_string_alloc(machine_name);
-       if (!machine_escaped) {
+       ok = convert_string_talloc(ctx,
+                                  CH_UTF8, CH_UTF16MUNGED,
+                                  utf8_pw, utf8_pw_len,
+                                  (void *)&utf16_pw, &utf16_pw_len);
+       if (!ok) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
                goto done;
        }
 
-       new_dn = talloc_asprintf(ctx, "cn=%s,%s", machine_escaped, org_unit);
-       samAccountName = talloc_asprintf(ctx, "%s$", machine_name);
+       machine_pw_val = (struct berval) {
+               .bv_val = utf16_pw,
+               .bv_len = utf16_pw_len,
+       };
+
+       /* Check if the machine account already exists. */
+       ret = ads_find_machine_acct(ads, &res, machine_escaped);
+       if (ADS_ERR_OK(ret)) {
+               /* Change the machine account password */
+               ret = ads_change_machine_acct(ads, res, &machine_pw_val);
+               ads_msgfree(ads, res);
 
-       if ( !new_dn || !samAccountName ) {
                goto done;
        }
+       ads_msgfree(ads, res);
 
-       if (!(controlstr = talloc_asprintf(ctx, "%u", acct_control))) {
+       new_dn = talloc_asprintf(ctx, "cn=%s,%s", machine_escaped, org_unit);
+       if (new_dn == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
                goto done;
        }
 
-       if (!(mods = ads_init_mods(ctx))) {
+       /* Create machine account */
+
+       samAccountName = talloc_asprintf(ctx, "%s$", machine_name);
+       if (samAccountName == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
                goto done;
        }
 
-       ads_mod_str(ctx, &mods, "cn", machine_name);
-       ads_mod_str(ctx, &mods, "sAMAccountName", samAccountName);
-       ads_mod_strlist(ctx, &mods, "objectClass", objectClass);
-       ads_mod_str(ctx, &mods, "userAccountControl", controlstr);
+       dns_hostname = talloc_asprintf(ctx,
+                                      "%s.%s",
+                                      machine_name,
+                                      dns_domain_name);
+       if (dns_hostname == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto done;
+       }
 
-       if (func_level >= DS_DOMAIN_FUNCTION_2008) {
-               const char *etype_list_str;
+       /* Add dns_hostname SPNs */
+       for (i = 0; i < ARRAY_SIZE(spn_prefix); i++) {
+               char *spn = talloc_asprintf(ctx,
+                                           "%s/%s",
+                                           spn_prefix[i],
+                                           dns_hostname);
+               if (spn == NULL) {
+                       ret = ADS_ERROR(LDAP_NO_MEMORY);
+                       goto done;
+               }
 
-               etype_list_str = talloc_asprintf(ctx, "%d", (int)etype_list);
-               if (etype_list_str == NULL) {
+               ok = add_string_to_array(spn_array,
+                                        spn,
+                                        &spn_array,
+                                        &num_spns);
+               if (!ok) {
+                       ret = ADS_ERROR(LDAP_NO_MEMORY);
                        goto done;
                }
-               ads_mod_str(ctx, &mods, "msDS-SupportedEncryptionTypes",
-                           etype_list_str);
        }
 
+       /* Add machine_name SPNs */
+       for (i = 0; i < ARRAY_SIZE(spn_prefix); i++) {
+               char *spn = talloc_asprintf(ctx,
+                                           "%s/%s",
+                                           spn_prefix[i],
+                                           machine_name);
+               if (spn == NULL) {
+                       ret = ADS_ERROR(LDAP_NO_MEMORY);
+                       goto done;
+               }
+
+               ok = add_string_to_array(spn_array,
+                                        spn,
+                                        &spn_array,
+                                        &num_spns);
+               if (!ok) {
+                       ret = ADS_ERROR(LDAP_NO_MEMORY);
+                       goto done;
+               }
+       }
+
+       /* Make sure to NULL terminate the array */
+       spn_array = talloc_realloc(ctx, spn_array, const char *, num_spns + 1);
+       if (spn_array == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto done;
+       }
+       spn_array[num_spns] = NULL;
+
+       controlstr = talloc_asprintf(ctx, "%u", acct_control);
+       if (controlstr == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto done;
+       }
+
+       mods = ads_init_mods(ctx);
+       if (mods == NULL) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto done;
+       }
+
+       ads_mod_str(ctx, &mods, "objectClass", "Computer");
+       ads_mod_str(ctx, &mods, "SamAccountName", samAccountName);
+       ads_mod_str(ctx, &mods, "userAccountControl", controlstr);
+       ads_mod_str(ctx, &mods, "DnsHostName", dns_hostname);
+       ads_mod_strlist(ctx, &mods, "ServicePrincipalName", spn_array);
+       ads_mod_ber(ctx, &mods, "unicodePwd", &machine_pw_val);
+
        ret = ads_gen_add(ads, new_dn, mods);
 
 done:
        SAFE_FREE(machine_escaped);
-       ads_msgfree(ads, res);
        talloc_destroy(ctx);
 
        return ret;
@@ -2155,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;
@@ -2203,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);
 
@@ -2393,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)) {
@@ -2407,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)));
                        }
 
@@ -2429,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);
 
@@ -2572,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
@@ -2584,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,
@@ -2593,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;
@@ -2610,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))) {
@@ -2620,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;
@@ -2645,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;
@@ -2656,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;
@@ -2682,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);
 
@@ -2705,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)
@@ -2754,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)
@@ -2819,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,
@@ -2848,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
@@ -2864,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() */
 
@@ -2892,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) {
@@ -2918,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;
        }
@@ -2938,22 +3511,43 @@ 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 ) {
-               if ( (ads_s = ads_init( ads->server.realm, ads->server.workgroup, 
-                       ads->server.ldap_server )) == NULL )
-               {
-                       status = ADS_ERROR(LDAP_NO_MEMORY);
-                       goto done;
+               /*
+                * ADS_STRUCT may be being reused after a
+                * DC lookup, so ads->ldap.ss may already have a
+                * good address. If not, re-initialize the passed-in
+                * ADS_STRUCT with the given server.XXXX parameters.
+                *
+                * Note that this doesn't depend on
+                * ads->server.ldap_server != NULL,
+                * as the case where ads->server.ldap_server==NULL and
+                * ads->ldap.ss != zero_address is precisely the DC
+                * lookup case where ads->ldap.ss was found by going
+                * through ads_find_dc() again we want to avoid repeating.
+                */
+               if (is_zero_addr(&ads->ldap.ss)) {
+                       ads_s = ads_init(tmp_ctx,
+                                        ads->server.realm,
+                                        ads->server.workgroup,
+                                        ads->server.ldap_server,
+                                        ADS_SASL_PLAIN );
+                       if (ads_s == NULL) {
+                               status = ADS_ERROR(LDAP_NO_MEMORY);
+                               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))
@@ -2965,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);
 
@@ -2986,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;
 }
@@ -3000,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;
@@ -3010,19 +3601,44 @@ ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32_t *val)
         /* establish a new ldap tcp session if necessary */
 
        if ( !ads->ldap.ld ) {
-               if ( (ads_s = ads_init( ads->server.realm, ads->server.workgroup, 
-                       ads->server.ldap_server )) == NULL )
-               {
-                       status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
-                       goto done;
+               /*
+                * ADS_STRUCT may be being reused after a
+                * DC lookup, so ads->ldap.ss may already have a
+                * good address. If not, re-initialize the passed-in
+                * ADS_STRUCT with the given server.XXXX parameters.
+                *
+                * Note that this doesn't depend on
+                * ads->server.ldap_server != NULL,
+                * as the case where ads->server.ldap_server==NULL and
+                * ads->ldap.ss != zero_address is precisely the DC
+                * lookup case where ads->ldap.ss was found by going
+                * through ads_find_dc() again we want to avoid repeating.
+                */
+               if (is_zero_addr(&ads->ldap.ss)) {
+                       ads_s = ads_init(tmp_ctx,
+                                        ads->server.realm,
+                                        ads->server.workgroup,
+                                        ads->server.ldap_server,
+                                        ADS_SASL_PLAIN );
+                       if (ads_s == NULL ) {
+                               status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
+                               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);
@@ -3039,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;
 }
@@ -3062,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)) {
@@ -3075,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
@@ -3115,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
-       */                                               
+       */
 }
 
 /**
@@ -3149,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;
@@ -3417,6 +4030,92 @@ out:
 /********************************************************************
 ********************************************************************/
 
+static char **get_addl_hosts(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
+                             LDAPMessage *msg, size_t *num_values)
+{
+       const char *field = "msDS-AdditionalDnsHostName";
+       struct berval **values = NULL;
+       char **ret = NULL;
+       size_t i, converted_size;
+
+       /*
+        * Windows DC implicitly adds a short name for each FQDN added to
+        * msDS-AdditionalDnsHostName, but it comes with a strange binary
+        * suffix "\0$" which we should ignore (see bug #14406).
+        */
+
+       values = ldap_get_values_len(ads->ldap.ld, msg, field);
+       if (values == NULL) {
+               return NULL;
+       }
+
+       *num_values = ldap_count_values_len(values);
+
+       ret = talloc_array(mem_ctx, char *, *num_values + 1);
+       if (ret == NULL) {
+               ldap_value_free_len(values);
+               return NULL;
+       }
+
+       for (i = 0; i < *num_values; i++) {
+               ret[i] = NULL;
+               if (!convert_string_talloc(mem_ctx, CH_UTF8, CH_UNIX,
+                                          values[i]->bv_val,
+                                          strnlen(values[i]->bv_val,
+                                                  values[i]->bv_len),
+                                          &ret[i], &converted_size)) {
+                       ldap_value_free_len(values);
+                       return NULL;
+               }
+       }
+       ret[i] = NULL;
+
+       ldap_value_free_len(values);
+       return ret;
+}
+
+ADS_STATUS ads_get_additional_dns_hostnames(TALLOC_CTX *mem_ctx,
+                                           ADS_STRUCT *ads,
+                                           const char *machine_name,
+                                           char ***hostnames_array,
+                                           size_t *num_hostnames)
+{
+       ADS_STATUS status;
+       LDAPMessage *res = NULL;
+       int count;
+
+       status = ads_find_machine_acct(ads,
+                                      &res,
+                                      machine_name);
+       if (!ADS_ERR_OK(status)) {
+               DEBUG(1,("Host Account for %s not found... skipping operation.\n",
+                        machine_name));
+               return status;
+       }
+
+       count = ads_count_replies(ads, res);
+       if (count != 1) {
+               status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
+               goto done;
+       }
+
+       *hostnames_array = get_addl_hosts(ads, mem_ctx, res, num_hostnames);
+       if (*hostnames_array == NULL) {
+               DEBUG(1, ("Host account for %s does not have msDS-AdditionalDnsHostName.\n",
+                         machine_name));
+               status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
+               goto done;
+       }
+
+done:
+       ads_msgfree(ads, res);
+
+       return status;
+}
+
+/********************************************************************
+********************************************************************/
+
 char* ads_get_upn( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
 {
        LDAPMessage *res = NULL;
@@ -3655,14 +4354,15 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
        TALLOC_FREE(hostnameDN);
 
        status = ads_find_machine_acct(ads, &res, host);
-       if (ADS_ERR_OK(status) && ads_count_replies(ads, res) == 1) {
+       if ((status.error_type == ENUM_ADS_ERROR_LDAP) &&
+           (status.err.rc != LDAP_NO_SUCH_OBJECT)) {
                DEBUG(3, ("Failed to remove host account.\n"));
                SAFE_FREE(host);
                return status;
        }
 
        SAFE_FREE(host);
-       return status;
+       return ADS_SUCCESS;
 }
 
 /**
@@ -3769,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
@@ -3840,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;
@@ -3855,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) {
@@ -3879,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;
@@ -3902,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;
@@ -3913,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;