lib: Make sid_parse return the parsed length
[samba.git] / source3 / libads / ldap.c
index df45be5f8a51093873d60bbd5f44c58c3432a54a..8e0ecb87569ef6780ca8ea0a6f2d26a3472a4b19 100644 (file)
 */
 
 #include "includes.h"
-#include "lib/ldb/include/ldb.h"
+#include "ads.h"
 #include "libads/sitename_cache.h"
+#include "libads/cldap.h"
+#include "../lib/addns/dnsquery.h"
+#include "../libds/common/flags.h"
+#include "smbldap.h"
+#include "../libcli/security/security.h"
+#include "../librpc/gen_ndr/netlogon.h"
+#include "lib/param/loadparm.h"
+#include "libsmb/namequery.h"
 
 #ifdef HAVE_LDAP
 
@@ -54,32 +62,58 @@ static void gotalarm_sig(int signum)
        gotalarm = 1;
 }
 
- LDAP *ldap_open_with_timeout(const char *server, int port, unsigned int to)
+ LDAP *ldap_open_with_timeout(const char *server,
+                             struct sockaddr_storage *ss,
+                             int port, unsigned int to)
 {
        LDAP *ldp = NULL;
-
+       int ldap_err;
+       char *uri;
 
        DEBUG(10, ("Opening connection to LDAP server '%s:%d', timeout "
                   "%u seconds\n", server, port, to));
 
-       /* Setup timeout */
-       gotalarm = 0;
-       CatchSignal(SIGALRM, gotalarm_sig);
-       alarm(to);
-       /* End setup timeout. */
+       if (to) {
+               /* Setup timeout */
+               gotalarm = 0;
+               CatchSignal(SIGALRM, gotalarm_sig);
+               alarm(to);
+               /* End setup timeout. */
+       }
 
-       ldp = ldap_open(server, port);
+       if ( strchr_m(server, ':') ) {
+               /* IPv6 URI */
+               uri = talloc_asprintf(talloc_tos(), "ldap://[%s]:%u", server, port);
+       } else {
+               /* IPv4 URI */
+               uri = talloc_asprintf(talloc_tos(), "ldap://%s:%u", server, port);
+       }
+       if (uri == NULL) {
+               return NULL;
+       }
 
-       if (ldp == NULL) {
-               DEBUG(2,("Could not open connection to LDAP server %s:%d: %s\n",
-                        server, port, strerror(errno)));
+#ifdef HAVE_LDAP_INITIALIZE
+       ldap_err = ldap_initialize(&ldp, uri);
+#else
+       ldp = ldap_open(server, port);
+       if (ldp != NULL) {
+               ldap_err = LDAP_SUCCESS;
        } else {
-               DEBUG(10, ("Connected to LDAP server '%s:%d'\n", server, port));
+               ldap_err = LDAP_OTHER;
+       }
+#endif
+       if (ldap_err != LDAP_SUCCESS) {
+               DEBUG(2,("Could not initialize connection for LDAP server '%s': %s\n",
+                        uri, ldap_err2string(ldap_err)));
+       } else {
+               DEBUG(10, ("Initialized connection for LDAP server '%s'\n", uri));
        }
 
-       /* Teardown timeout. */
-       CatchSignal(SIGALRM, SIG_IGN);
-       alarm(0);
+       if (to) {
+               /* Teardown timeout. */
+               alarm(0);
+               CatchSignal(SIGALRM, SIG_IGN);
+       }
 
        return ldp;
 }
@@ -95,26 +129,39 @@ static int ldap_search_with_timeout(LDAP *ld,
                                    int sizelimit,
                                    LDAPMessage **res )
 {
+       int to = lp_ldap_timeout();
        struct timeval timeout;
+       struct timeval *timeout_ptr = NULL;
        int result;
 
        /* Setup timeout for the ldap_search_ext_s call - local and remote. */
-       timeout.tv_sec = lp_ldap_timeout();
-       timeout.tv_usec = 0;
-
-       /* Setup alarm timeout.... Do we need both of these ? JRA. */
        gotalarm = 0;
-       CatchSignal(SIGALRM, gotalarm_sig);
-       alarm(lp_ldap_timeout());
-       /* End setup timeout. */
+
+       if (to) {
+               timeout.tv_sec = to;
+               timeout.tv_usec = 0;
+               timeout_ptr = &timeout;
+
+               /* Setup alarm timeout. */
+               CatchSignal(SIGALRM, gotalarm_sig);
+               /* Make the alarm time one second beyond
+                  the timout we're setting for the
+                  remote search timeout, to allow that
+                  to fire in preference. */
+               alarm(to+1);
+               /* End setup timeout. */
+       }
+
 
        result = ldap_search_ext_s(ld, base, scope, filter, attrs,
-                                  attrsonly, sctrls, cctrls, &timeout,
+                                  attrsonly, sctrls, cctrls, timeout_ptr,
                                   sizelimit, res);
 
-       /* Teardown timeout. */
-       CatchSignal(SIGALRM, SIG_IGN);
-       alarm(0);
+       if (to) {
+               /* Teardown alarm timeout. */
+               CatchSignal(SIGALRM, SIG_IGN);
+               alarm(0);
+       }
 
        if (gotalarm != 0)
                return LDAP_TIMELIMIT_EXCEEDED;
@@ -189,47 +236,28 @@ bool ads_closest_dc(ADS_STRUCT *ads)
   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, const char *server, bool gc)
+static bool ads_try_connect(ADS_STRUCT *ads, bool gc,
+                           struct sockaddr_storage *ss)
 {
-       char *srv;
        struct NETLOGON_SAM_LOGON_RESPONSE_EX cldap_reply;
        TALLOC_CTX *frame = talloc_stackframe();
        bool ret = false;
+       char addr[INET6_ADDRSTRLEN];
 
-       if (!server || !*server) {
+       if (ss == NULL) {
                TALLOC_FREE(frame);
                return False;
        }
 
-       if (!is_ipaddress(server)) {
-               struct sockaddr_storage ss;
-               char addr[INET6_ADDRSTRLEN];
-
-               if (!resolve_name(server, &ss, 0x20, true)) {
-                       DEBUG(5,("ads_try_connect: unable to resolve name %s\n",
-                               server ));
-                       TALLOC_FREE(frame);
-                       return false;
-               }
-               print_sockaddr(addr, sizeof(addr), &ss);
-               srv = talloc_strdup(frame, addr);
-       } else {
-               /* this copes with inet_ntoa brokenness */
-               srv = talloc_strdup(frame, server);
-       }
-
-       if (!srv) {
-               TALLOC_FREE(frame);
-               return false;
-       }
+       print_sockaddr(addr, sizeof(addr), ss);
 
        DEBUG(5,("ads_try_connect: sending CLDAP request to %s (realm: %s)\n", 
-               srv, ads->server.realm));
+               addr, ads->server.realm));
 
        ZERO_STRUCT( cldap_reply );
 
-       if ( !ads_cldap_netlogon_5(frame, srv, ads->server.realm, &cldap_reply ) ) {
-               DEBUG(3,("ads_try_connect: CLDAP request %s failed.\n", srv));
+       if ( !ads_cldap_netlogon_5(frame, ss, ads->server.realm, &cldap_reply ) ) {
+               DEBUG(3,("ads_try_connect: CLDAP request %s failed.\n", addr));
                ret = false;
                goto out;
        }
@@ -238,7 +266,7 @@ static bool ads_try_connect(ADS_STRUCT *ads, const char *server, bool gc)
 
        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",
-                       srv));
+                       addr));
                ret = false;
                goto out;
        }
@@ -252,10 +280,19 @@ static bool ads_try_connect(ADS_STRUCT *ads, const char *server, bool gc)
        SAFE_FREE(ads->config.client_site_name);
        SAFE_FREE(ads->server.workgroup);
 
-       ads->config.flags              = cldap_reply.server_type;
+       if (!check_cldap_reply_required_flags(cldap_reply.server_type,
+                                             ads->config.flags)) {
+               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);
-       strupper_m(ads->config.realm);
+       if (!strupper_m(ads->config.realm)) {
+               ret = false;
+               goto out;
+       }
+
        ads->config.bind_path          = ads_build_dn(ads->config.realm);
        if (*cldap_reply.server_site) {
                ads->config.server_site_name =
@@ -265,21 +302,18 @@ static bool ads_try_connect(ADS_STRUCT *ads, const char *server, bool gc)
                ads->config.client_site_name =
                        SMB_STRDUP(cldap_reply.client_site);
        }
-       ads->server.workgroup          = SMB_STRDUP(cldap_reply.domain);
+       ads->server.workgroup          = SMB_STRDUP(cldap_reply.domain_name);
 
        ads->ldap.port = gc ? LDAP_GC_PORT : LDAP_PORT;
-       if (!interpret_string_addr(&ads->ldap.ss, srv, 0)) {
-               DEBUG(1,("ads_try_connect: unable to convert %s "
-                       "to an address\n",
-                       srv));
-               ret = false;
-               goto out;
-       }
+       ads->ldap.ss = *ss;
 
        /* Store our site name. */
-       sitename_store( cldap_reply.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;
+
        ret = true;
 
  out:
@@ -289,297 +323,248 @@ static bool ads_try_connect(ADS_STRUCT *ads, const char *server, bool gc)
 }
 
 /**********************************************************************
- 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 
- disabled
+ 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 ads_find_dc(ADS_STRUCT *ads)
+static NTSTATUS cldap_ping_list(ADS_STRUCT *ads,const char *domain,
+                               struct ip_service *ip_list, int count)
 {
-       const char *c_domain;
-       const char *c_realm;
-       int count, i=0;
-       struct ip_service *ip_list;
-       const char *realm;
-       const char *domain;
-       bool got_realm = False;
-       bool use_own_domain = False;
-       char *sitename;
-       NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
-
-       /* if the realm and workgroup are both empty, assume they are ours */
+       int i;
+       bool ok;
 
-       /* realm */
-       c_realm = ads->server.realm;
+       for (i = 0; i < count; i++) {
+               char server[INET6_ADDRSTRLEN];
 
-       if ( !c_realm || !*c_realm ) {
-               /* special case where no realm and no workgroup means our own */
-               if ( !ads->server.workgroup || !*ads->server.workgroup ) {
-                       use_own_domain = True;
-                       c_realm = lp_realm();
-               }
-       }
+               print_sockaddr(server, sizeof(server), &ip_list[i].ss);
 
-       if (c_realm && *c_realm)
-               got_realm = True;
+               if (!NT_STATUS_IS_OK(
+                       check_negative_conn_cache(domain, server)))
+                       continue;
 
-       /* we need to try once with the realm name and fallback to the
-          netbios domain name if we fail (if netbios has not been disabled */
+               /* Returns ok only if it matches the correct server type */
+               ok = ads_try_connect(ads, false, &ip_list[i].ss);
 
-       if ( !got_realm && !lp_disable_netbios() ) {
-               c_realm = ads->server.workgroup;
-               if (!c_realm || !*c_realm) {
-                       if ( use_own_domain )
-                               c_realm = lp_workgroup();
+               if (ok) {
+                       return NT_STATUS_OK;
                }
-       }
 
-       if ( !c_realm || !*c_realm ) {
-               DEBUG(0,("ads_find_dc: no realm or workgroup!  Don't know what to do\n"));
-               return NT_STATUS_INVALID_PARAMETER; /* rather need MISSING_PARAMETER ... */
-       }
-
-       if ( use_own_domain ) {
-               c_domain = lp_workgroup();
-       } else {
-               c_domain = ads->server.workgroup;
+               /* keep track of failures */
+               add_failed_connection_entry(domain, server,
+                                           NT_STATUS_UNSUCCESSFUL);
        }
 
-       realm = c_realm;
-       domain = c_domain;
-
-       /*
-        * In case of LDAP we use get_dc_name() as that
-        * creates the custom krb5.conf file
-        */
-       if (!(ads->auth.flags & ADS_AUTH_NO_BIND)) {
-               fstring srv_name;
-               struct sockaddr_storage ip_out;
-
-               DEBUG(6,("ads_find_dc: (ldap) looking for %s '%s'\n",
-                       (got_realm ? "realm" : "domain"), realm));
-
-               if (get_dc_name(domain, realm, srv_name, &ip_out)) {
-                       /*
-                        * we call ads_try_connect() to fill in the
-                        * ads->config details
-                        */
-                       if (ads_try_connect(ads, srv_name, false)) {
-                               return NT_STATUS_OK;
-                       }
-               }
-
-               return NT_STATUS_NO_LOGON_SERVERS;
-       }
+       return NT_STATUS_NO_LOGON_SERVERS;
+}
 
-       sitename = sitename_fetch(realm);
+/***************************************************************************
+ resolve a name and perform an "ldap ping" using NetBIOS and related methods
+****************************************************************************/
 
- again:
+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;
 
-       DEBUG(6,("ads_find_dc: (cldap) looking for %s '%s'\n",
-               (got_realm ? "realm" : "domain"), realm));
+       DEBUG(6, ("resolve_and_ping_netbios: (cldap) looking for domain '%s'\n",
+                 domain));
 
-       status = get_sorted_dc_list(realm, sitename, &ip_list, &count, got_realm);
+       status = get_sorted_dc_list(domain, NULL, &ip_list, &count,
+                                   false);
        if (!NT_STATUS_IS_OK(status)) {
-               /* fall back to netbios if we can */
-               if ( got_realm && !lp_disable_netbios() ) {
-                       got_realm = False;
-                       goto again;
-               }
-
-               SAFE_FREE(sitename);
                return status;
        }
 
-       /* if we fail this loop, then giveup since all the IP addresses returned were dead */
-       for ( i=0; i<count; i++ ) {
-               char server[INET6_ADDRSTRLEN];
+       /* remove servers which are known to be dead based on
+          the corresponding DNS method */
+       if (*realm) {
+               for (i = 0; i < count; ++i) {
+                       char server[INET6_ADDRSTRLEN];
 
-               print_sockaddr(server, sizeof(server), &ip_list[i].ss);
+                       print_sockaddr(server, sizeof(server), &ip_list[i].ss);
 
-               if ( !NT_STATUS_IS_OK(check_negative_conn_cache(realm, server)) )
-                       continue;
-
-               if (!got_realm) {
-                       /* realm in this case is a workgroup name. We need
-                          to ignore any IP addresses in the negative connection
-                          cache that match ip addresses returned in the ad realm
-                          case. It sucks that I have to reproduce the logic above... */
-                       c_realm = ads->server.realm;
-                       if ( !c_realm || !*c_realm ) {
-                               if ( !ads->server.workgroup || !*ads->server.workgroup ) {
-                                       c_realm = lp_realm();
-                               }
-                       }
-                       if (c_realm && *c_realm &&
-                                       !NT_STATUS_IS_OK(check_negative_conn_cache(c_realm, server))) {
+                       if(!NT_STATUS_IS_OK(
+                               check_negative_conn_cache(realm, server))) {
                                /* Ensure we add the workgroup name for this
                                   IP address as negative too. */
-                               add_failed_connection_entry( realm, server, NT_STATUS_UNSUCCESSFUL );
-                               continue;
+                               add_failed_connection_entry(
+                                   domain, server,
+                                   NT_STATUS_UNSUCCESSFUL);
                        }
                }
-
-               if ( ads_try_connect(ads, server, false) ) {
-                       SAFE_FREE(ip_list);
-                       SAFE_FREE(sitename);
-                       return NT_STATUS_OK;
-               }
-
-               /* keep track of failures */
-               add_failed_connection_entry( realm, server, NT_STATUS_UNSUCCESSFUL );
        }
 
-       SAFE_FREE(ip_list);
-
-       /* In case we failed to contact one of our closest DC on our site we
-        * need to try to find another DC, retry with a site-less SRV DNS query
-        * - Guenther */
+       status = cldap_ping_list(ads, domain, ip_list, count);
 
-       if (sitename) {
-               DEBUG(1,("ads_find_dc: failed to find a valid DC on our site (%s), "
-                               "trying to find another DC\n", sitename));
-               SAFE_FREE(sitename);
-               namecache_delete(realm, 0x1C);
-               goto again;
-       }
+       SAFE_FREE(ip_list);
 
-       return NT_STATUS_NO_LOGON_SERVERS;
+       return status;
 }
 
-/*********************************************************************
- *********************************************************************/
 
-static NTSTATUS ads_lookup_site(void)
-{
-       ADS_STRUCT *ads = NULL;
-       ADS_STATUS ads_status;
-       NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
+/**********************************************************************
+ resolve a name and perform an "ldap ping" using DNS
+**********************************************************************/
 
-       ads = ads_init(lp_realm(), NULL, NULL);
-       if (!ads) {
-               return NT_STATUS_NO_MEMORY;
-       }
+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;
 
-       /* The NO_BIND here will find a DC and set the client site
-          but not establish the TCP connection */
+       DEBUG(6, ("resolve_and_ping_dns: (cldap) looking for realm '%s'\n",
+                 realm));
 
-       ads->auth.flags = ADS_AUTH_NO_BIND;
-       ads_status = ads_connect(ads);
-       if (!ADS_ERR_OK(ads_status)) {
-               DEBUG(4, ("ads_lookup_site: ads_connect to our realm failed! (%s)\n",
-                         ads_errstr(ads_status)));
+       status = get_sorted_dc_list(realm, sitename, &ip_list, &count,
+                                   true);
+       if (!NT_STATUS_IS_OK(status)) {
+               SAFE_FREE(ip_list);
+               return status;
        }
-       nt_status = ads_ntstatus(ads_status);
 
-       if (ads) {
-               ads_destroy(&ads);
-       }
+       status = cldap_ping_list(ads, realm, ip_list, count);
 
-       return nt_status;
+       SAFE_FREE(ip_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
+ disabled
+**********************************************************************/
 
-static const char* host_dns_domain(const char *fqdn)
+static NTSTATUS ads_find_dc(ADS_STRUCT *ads)
 {
-       const char *p = fqdn;
-
-       /* go to next char following '.' */
-
-       if ((p = strchr_m(fqdn, '.')) != NULL) {
-               p++;
-       }
+       const char *c_domain = "";
+       const char *c_realm;
+       bool use_own_domain = False;
+       char *sitename = NULL;
+       NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
+       bool ok = false;
 
-       return p;
-}
+       /* if the realm and workgroup are both empty, assume they are ours */
 
+       /* realm */
+       c_realm = ads->server.realm;
 
-/**
- * Connect to the Global Catalog server
- * @param ads Pointer to an existing ADS_STRUCT
- * @return status of connection
- *
- * Simple wrapper around ads_connect() that fills in the
- * GC ldap server information
- **/
+       if (c_realm == NULL)
+               c_realm = "";
 
-ADS_STATUS ads_connect_gc(ADS_STRUCT *ads)
-{
-       TALLOC_CTX *frame = talloc_stackframe();
-       struct dns_rr_srv *gcs_list;
-       int num_gcs;
-       char *realm = ads->server.realm;
-       NTSTATUS nt_status = NT_STATUS_UNSUCCESSFUL;
-       ADS_STATUS ads_status = ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
-       int i;
-       bool done = false;
-       char *sitename = NULL;
+       if (!*c_realm) {
+               /* special case where no realm and no workgroup means our own */
+               if ( !ads->server.workgroup || !*ads->server.workgroup ) {
+                       use_own_domain = True;
+                       c_realm = lp_realm();
+               }
+       }
 
-       if (!realm)
-               realm = lp_realm();
+       if (!lp_disable_netbios()) {
+               if (use_own_domain) {
+                       c_domain = lp_workgroup();
+               } else {
+                       c_domain = ads->server.workgroup;
+                       if (!*c_realm && (!c_domain || !*c_domain)) {
+                               c_domain = lp_workgroup();
+                       }
+               }
 
-       if ((sitename = sitename_fetch(realm)) == NULL) {
-               ads_lookup_site();
-               sitename = sitename_fetch(realm);
+               if (!c_domain) {
+                       c_domain = "";
+               }
        }
 
-       do {
-               /* We try once with a sitename and once without
-                  (unless we don't have a sitename and then we're
-                  done */
-
-               if (sitename == NULL)
-                       done = true;
+       if (!*c_realm && !*c_domain) {
+               DEBUG(0, ("ads_find_dc: no realm or workgroup!  Don't know "
+                         "what to do\n"));
+               return NT_STATUS_INVALID_PARAMETER; /* rather need MISSING_PARAMETER ... */
+       }
 
-               nt_status = ads_dns_query_gcs(frame, realm, sitename,
-                                             &gcs_list, &num_gcs);
+       /*
+        * In case of LDAP we use get_dc_name() as that
+        * creates the custom krb5.conf file
+        */
+       if (!(ads->auth.flags & ADS_AUTH_NO_BIND)) {
+               fstring srv_name;
+               struct sockaddr_storage ip_out;
 
-               SAFE_FREE(sitename);
+               DEBUG(6, ("ads_find_dc: (ldap) looking for realm '%s'"
+                         " and falling back to domain '%s'\n",
+                         c_realm, c_domain));
 
-               if (!NT_STATUS_IS_OK(nt_status)) {
-                       ads_status = ADS_ERROR_NT(nt_status);
-                       goto done;
+               ok = get_dc_name(c_domain, c_realm, srv_name, &ip_out);
+               if (ok) {
+                       /*
+                        * we call ads_try_connect() to fill in the
+                        * ads->config details
+                        */
+                       ok = ads_try_connect(ads, false, &ip_out);
+                       if (ok) {
+                               return NT_STATUS_OK;
+                       }
                }
 
-               /* Loop until we get a successful connection or have gone
-                  through them all.  When connecting a GC server, make sure that
-                  the realm is the server's DNS name and not the forest root */
-
-               for (i=0; i<num_gcs; i++) {
-                       ads->server.gc = true;
-                       ads->server.ldap_server = SMB_STRDUP(gcs_list[i].hostname);
-                       ads->server.realm = SMB_STRDUP(host_dns_domain(ads->server.ldap_server));
-                       ads_status = ads_connect(ads);
-                       if (ADS_ERR_OK(ads_status)) {
-                               /* Reset the bind_dn to "".  A Global Catalog server
-                                  may host  multiple domain trees in a forest.
-                                  Windows 2003 GC server will accept "" as the search
-                                  path to imply search all domain trees in the forest */
+               return NT_STATUS_NO_LOGON_SERVERS;
+       }
 
-                               SAFE_FREE(ads->config.bind_path);
-                               ads->config.bind_path = SMB_STRDUP("");
+       if (*c_realm) {
+               sitename = sitename_fetch(talloc_tos(), c_realm);
+               status = resolve_and_ping_dns(ads, sitename, c_realm);
 
+               if (NT_STATUS_IS_OK(status)) {
+                       TALLOC_FREE(sitename);
+                       return status;
+               }
 
-                               goto done;
+               /* In case we failed to contact one of our closest DC on our
+                * site we
+                * need to try to find another DC, retry with a site-less SRV
+                * DNS query
+                * - Guenther */
+
+               if (sitename) {
+                       DEBUG(3, ("ads_find_dc: failed to find a valid DC on "
+                                 "our site (%s), Trying to find another DC "
+                                 "for realm '%s' (domain '%s')\n",
+                                 sitename, c_realm, c_domain));
+                       namecache_delete(c_realm, 0x1C);
+                       status =
+                           resolve_and_ping_dns(ads, NULL, c_realm);
+
+                       if (NT_STATUS_IS_OK(status)) {
+                               TALLOC_FREE(sitename);
+                               return status;
                        }
-                       SAFE_FREE(ads->server.ldap_server);
-                       SAFE_FREE(ads->server.realm);
                }
 
-               TALLOC_FREE(gcs_list);
-               num_gcs = 0;
-       } while (!done);
-
-done:
-       SAFE_FREE(sitename);
-       talloc_destroy(frame);
+               TALLOC_FREE(sitename);
+       }
 
-       return ads_status;
-}
+       /* try netbios as fallback - if permitted,
+          or if configuration specifically requests it */
+       if (*c_domain) {
+               if (*c_realm) {
+                       DEBUG(3, ("ads_find_dc: falling back to netbios "
+                                 "name resolution for domain '%s' (realm '%s')\n",
+                                 c_domain, c_realm));
+               }
 
+               status = resolve_and_ping_netbios(ads, c_domain, c_realm);
+               if (NT_STATUS_IS_OK(status)) {
+                       return status;
+               }
+       }
 
+       DEBUG(1, ("ads_find_dc: "
+                 "name resolution for realm '%s' (domain '%s') failed: %s\n",
+                 c_realm, c_domain, nt_errstr(status)));
+       return status;
+}
 /**
  * Connect to the LDAP server
  * @param ads Pointer to an existing ADS_STRUCT
@@ -593,8 +578,9 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
        char addr[INET6_ADDRSTRLEN];
 
        ZERO_STRUCT(ads->ldap);
-       ads->ldap.last_attempt  = time(NULL);
-       ads->ldap.wrap_type     = ADS_SASLWRAP_TYPE_PLAIN;
+       ZERO_STRUCT(ads->ldap_wrap_data);
+       ads->ldap.last_attempt  = time_mono(NULL);
+       ads->ldap_wrap_data.wrap_type   = ADS_SASLWRAP_TYPE_PLAIN;
 
        /* try with a user specified server */
 
@@ -605,9 +591,19 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                TALLOC_FREE(s);
        }
 
-       if (ads->server.ldap_server)
-       {
-               if (ads_try_connect(ads, ads->server.ldap_server, ads->server.gc)) {
+       if (ads->server.ldap_server) {
+               bool ok = false;
+               struct sockaddr_storage ss;
+
+               ok = resolve_name(ads->server.ldap_server, &ss, 0x20, true);
+               if (!ok) {
+                       DEBUG(5,("ads_connect: unable to resolve name %s\n",
+                                ads->server.ldap_server));
+                       status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
+                       goto out;
+               }
+               ok = ads_try_connect(ads, ads->server.gc, &ss);
+               if (ok) {
                        goto got_connection;
                }
 
@@ -619,6 +615,11 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                if (ads->server.gc == true) {
                        return ADS_ERROR(LDAP_OPERATIONS_ERROR);
                }
+
+               if (ads->server.no_fallback) {
+                       status = ADS_ERROR_NT(NT_STATUS_NOT_FOUND);
+                       goto out;
+               }
        }
 
        ntstatus = ads_find_dc(ads);
@@ -638,7 +639,7 @@ got_connection:
                /* Must use the userPrincipalName value here or sAMAccountName
                   and not servicePrincipalName; found by Guenther Deschner */
 
-               if (asprintf(&ads->auth.user_name, "%s$", global_myname() ) == -1) {
+               if (asprintf(&ads->auth.user_name, "%s$", lp_netbios_name() ) == -1) {
                        DEBUG(0,("ads_connect: asprintf fail.\n"));
                        ads->auth.user_name = NULL;
                }
@@ -653,18 +654,6 @@ got_connection:
                ads->auth.kdc_server = SMB_STRDUP(addr);
        }
 
-#if KRB5_DNS_HACK
-       /* this is a really nasty hack to avoid ADS DNS problems. It needs a patch
-          to MIT kerberos to work (tridge) */
-       {
-               char *env = NULL;
-               if (asprintf(&env, "KRB5_KDC_ADDRESS_%s", ads->config.realm) > 0) {
-                       setenv(env, ads->auth.kdc_server, 1);
-                       free(env);
-               }
-       }
-#endif
-
        /* If the caller() requested no LDAP bind, then we are done */
 
        if (ads->auth.flags & ADS_AUTH_NO_BIND) {
@@ -672,15 +661,16 @@ got_connection:
                goto out;
        }
 
-       ads->ldap.mem_ctx = talloc_init("ads LDAP connection memory");
-       if (!ads->ldap.mem_ctx) {
+       ads->ldap_wrap_data.mem_ctx = talloc_init("ads LDAP connection memory");
+       if (!ads->ldap_wrap_data.mem_ctx) {
                status = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
                goto out;
        }
 
        /* Otherwise setup the TCP LDAP session */
 
-       ads->ldap.ld = ldap_open_with_timeout(ads->config.ldap_server_name,
+       ads->ldap.ld = ldap_open_with_timeout(addr,
+                                             &ads->ldap.ss,
                                              ads->ldap.port, lp_ldap_timeout());
        if (ads->ldap.ld == NULL) {
                status = ADS_ERROR(LDAP_OPERATIONS_ERROR);
@@ -697,7 +687,7 @@ got_connection:
        ldap_set_option(ads->ldap.ld, LDAP_OPT_PROTOCOL_VERSION, &version);
 
        if ( lp_ldap_ssl_ads() ) {
-               status = ADS_ERROR(smb_ldap_start_tls(ads->ldap.ld, version));
+               status = ADS_ERROR(smbldap_start_tls(ads->ldap.ld, version));
                if (!ADS_ERR_OK(status)) {
                        goto out;
                }
@@ -758,13 +748,15 @@ void ads_disconnect(ADS_STRUCT *ads)
                ldap_unbind(ads->ldap.ld);
                ads->ldap.ld = NULL;
        }
-       if (ads->ldap.wrap_ops && ads->ldap.wrap_ops->disconnect) {
-               ads->ldap.wrap_ops->disconnect(ads);
+       if (ads->ldap_wrap_data.wrap_ops &&
+               ads->ldap_wrap_data.wrap_ops->disconnect) {
+               ads->ldap_wrap_data.wrap_ops->disconnect(&ads->ldap_wrap_data);
        }
-       if (ads->ldap.mem_ctx) {
-               talloc_free(ads->ldap.mem_ctx);
+       if (ads->ldap_wrap_data.mem_ctx) {
+               talloc_free(ads->ldap_wrap_data.mem_ctx);
        }
        ZERO_STRUCT(ads->ldap);
+       ZERO_STRUCT(ads->ldap_wrap_data);
 }
 
 /*
@@ -776,13 +768,13 @@ static struct berval *dup_berval(TALLOC_CTX *ctx, const struct berval *in_val)
 
        if (!in_val) return NULL;
 
-       value = TALLOC_ZERO_P(ctx, struct berval);
+       value = talloc_zero(ctx, struct berval);
        if (value == NULL)
                return NULL;
        if (in_val->bv_len == 0) return value;
 
        value->bv_len = in_val->bv_len;
-       value->bv_val = (char *)TALLOC_MEMDUP(ctx, in_val->bv_val,
+       value->bv_val = (char *)talloc_memdup(ctx, in_val->bv_val,
                                              in_val->bv_len);
        return value;
 }
@@ -799,7 +791,7 @@ static struct berval **ads_dup_values(TALLOC_CTX *ctx,
        if (!in_vals) return NULL;
        for (i=0; in_vals[i]; i++)
                ; /* count values */
-       values = TALLOC_ZERO_ARRAY(ctx, struct berval *, i+1);
+       values = talloc_zero_array(ctx, struct berval *, i+1);
        if (!values) return NULL;
 
        for (i=0; in_vals[i]; i++) {
@@ -820,7 +812,7 @@ static char **ads_push_strvals(TALLOC_CTX *ctx, const char **in_vals)
        if (!in_vals) return NULL;
        for (i=0; in_vals[i]; i++)
                ; /* count values */
-       values = TALLOC_ZERO_ARRAY(ctx, char *, i+1);
+       values = talloc_zero_array(ctx, char *, i+1);
        if (!values) return NULL;
 
        for (i=0; in_vals[i]; i++) {
@@ -844,7 +836,7 @@ static char **ads_pull_strvals(TALLOC_CTX *ctx, const char **in_vals)
        if (!in_vals) return NULL;
        for (i=0; in_vals[i]; i++)
                ; /* count values */
-       values = TALLOC_ZERO_ARRAY(ctx, char *, i+1);
+       values = talloc_zero_array(ctx, char *, i+1);
        if (!values) return NULL;
 
        for (i=0; in_vals[i]; i++) {
@@ -925,28 +917,28 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
 
        cookie_be = ber_alloc_t(LBER_USE_DER);
        if (*cookie) {
-               ber_printf(cookie_be, "{iO}", (ber_int_t) 1000, *cookie);
+               ber_printf(cookie_be, "{iO}", (ber_int_t) ads->config.ldap_page_size, *cookie);
                ber_bvfree(*cookie); /* don't need it from last time */
                *cookie = NULL;
        } else {
-               ber_printf(cookie_be, "{io}", (ber_int_t) 1000, "", 0);
+               ber_printf(cookie_be, "{io}", (ber_int_t) ads->config.ldap_page_size, "", 0);
        }
        ber_flatten(cookie_be, &cookie_bv);
-       PagedResults.ldctl_oid = CONST_DISCARD(char *, ADS_PAGE_CTL_OID);
+       PagedResults.ldctl_oid = discard_const_p(char, ADS_PAGE_CTL_OID);
        PagedResults.ldctl_iscritical = (char) 1;
        PagedResults.ldctl_value.bv_len = cookie_bv->bv_len;
        PagedResults.ldctl_value.bv_val = cookie_bv->bv_val;
 
-       NoReferrals.ldctl_oid = CONST_DISCARD(char *, ADS_NO_REFERRALS_OID);
+       NoReferrals.ldctl_oid = discard_const_p(char, ADS_NO_REFERRALS_OID);
        NoReferrals.ldctl_iscritical = (char) 0;
        NoReferrals.ldctl_value.bv_len = 0;
-       NoReferrals.ldctl_value.bv_val = CONST_DISCARD(char *, "");
+       NoReferrals.ldctl_value.bv_val = discard_const_p(char, "");
 
        if (external_control && 
            (strequal(external_control->control, ADS_EXTENDED_DN_OID) || 
             strequal(external_control->control, ADS_SD_FLAGS_OID))) {
 
-               ExternalCtrl.ldctl_oid = CONST_DISCARD(char *, external_control->control);
+               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 */
@@ -1007,6 +999,24 @@ static ADS_STATUS ads_do_paged_search_args(ADS_STRUCT *ads,
        if (rc) {
                DEBUG(3,("ads_do_paged_search_args: ldap_search_with_timeout(%s) -> %s\n", expr,
                         ldap_err2string(rc)));
+               if (rc == LDAP_OTHER) {
+                       char *ldap_errmsg;
+                       int ret;
+
+                       ret = ldap_parse_result(ads->ldap.ld,
+                                               *res,
+                                               NULL,
+                                               NULL,
+                                               &ldap_errmsg,
+                                               NULL,
+                                               NULL,
+                                               0);
+                       if (ret == LDAP_SUCCESS) {
+                               DEBUG(3, ("ldap_search_with_timeout(%s) "
+                                         "error: %s\n", expr, ldap_errmsg));
+                               ldap_memfree(ldap_errmsg);
+                       }
+               }
                goto done;
        }
 
@@ -1046,6 +1056,11 @@ done:
                ber_bvfree(ext_bv);
        }
 
+       if (rc != LDAP_SUCCESS && *res != NULL) {
+               ads_msgfree(ads, *res);
+               *res = NULL;
+       }
+
        /* if/when we decide to utf8-encode attrs, take out this next line */
        TALLOC_FREE(search_attrs);
 
@@ -1091,13 +1106,13 @@ static ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
 #ifdef HAVE_LDAP_ADD_RESULT_ENTRY
        while (cookie) {
                LDAPMessage *res2 = NULL;
-               ADS_STATUS status2;
                LDAPMessage *msg, *next;
 
-               status2 = ads_do_paged_search_args(ads, bind_path, scope, expr, 
+               status = ads_do_paged_search_args(ads, bind_path, scope, expr,
                                              attrs, args, &res2, &count, &cookie);
-
-               if (!ADS_ERR_OK(status2)) break;
+               if (!ADS_ERR_OK(status)) {
+                       break;
+               }
 
                /* this relies on the way that ldap_add_result_entry() works internally. I hope
                   that this works on all ldap libs, but I have only tested with openldap */
@@ -1125,7 +1140,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 sd_flags, 
+                                      const char **attrs, uint32_t sd_flags, 
                                       LDAPMessage **res)
 {
        ads_control args;
@@ -1351,7 +1366,7 @@ char *ads_parent_dn(const char *dn)
 {
        ADS_STATUS status;
        char *expr;
-       const char *attrs[] = {"*", "nTSecurityDescriptor", NULL};
+       const char *attrs[] = {"*", "msDS-SupportedEncryptionTypes", "nTSecurityDescriptor", NULL};
 
        *res = NULL;
 
@@ -1377,7 +1392,7 @@ ADS_MODLIST ads_init_mods(TALLOC_CTX *ctx)
 #define ADS_MODLIST_ALLOC_SIZE 10
        LDAPMod **mods;
 
-       if ((mods = TALLOC_ZERO_ARRAY(ctx, LDAPMod *, ADS_MODLIST_ALLOC_SIZE + 1)))
+       if ((mods = talloc_zero_array(ctx, LDAPMod *, ADS_MODLIST_ALLOC_SIZE + 1)))
                /* -1 is safety to make sure we don't go over the end.
                   need to reset it to NULL before doing ldap modify */
                mods[ADS_MODLIST_ALLOC_SIZE] = (LDAPMod *) -1;
@@ -1393,28 +1408,30 @@ static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
                                  int mod_op, const char *name, 
                                  const void *_invals)
 {
-       const void **invals = (const void **)_invals;
        int curmod;
        LDAPMod **modlist = (LDAPMod **) *mods;
        struct berval **ber_values = NULL;
        char **char_values = NULL;
 
-       if (!invals) {
+       if (!_invals) {
                mod_op = LDAP_MOD_DELETE;
        } else {
-               if (mod_op & LDAP_MOD_BVALUES)
-                       ber_values = ads_dup_values(ctx, 
-                                               (const struct berval **)invals);
-               else
-                       char_values = ads_push_strvals(ctx, 
-                                                 (const char **) invals);
+               if (mod_op & LDAP_MOD_BVALUES) {
+                       const struct berval **b;
+                       b = discard_const_p(const struct berval *, _invals);
+                       ber_values = ads_dup_values(ctx, b);
+               } else {
+                       const char **c;
+                       c = discard_const_p(const char *, _invals);
+                       char_values = ads_push_strvals(ctx, c);
+               }
        }
 
        /* find the first empty slot */
        for (curmod=0; modlist[curmod] && modlist[curmod] != (LDAPMod *) -1;
             curmod++);
        if (modlist[curmod] == (LDAPMod *) -1) {
-               if (!(modlist = TALLOC_REALLOC_ARRAY(ctx, modlist, LDAPMod *,
+               if (!(modlist = talloc_realloc(ctx, modlist, LDAPMod *,
                                curmod+ADS_MODLIST_ALLOC_SIZE+1)))
                        return ADS_ERROR(LDAP_NO_MEMORY);
                memset(&modlist[curmod], 0, 
@@ -1423,7 +1440,7 @@ static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
                *mods = (ADS_MODLIST)modlist;
        }
 
-       if (!(modlist[curmod] = TALLOC_ZERO_P(ctx, LDAPMod)))
+       if (!(modlist[curmod] = talloc_zero(ctx, LDAPMod)))
                return ADS_ERROR(LDAP_NO_MEMORY);
        modlist[curmod]->mod_type = talloc_strdup(ctx, name);
        if (mod_op & LDAP_MOD_BVALUES) {
@@ -1499,6 +1516,17 @@ static ADS_STATUS ads_mod_ber(TALLOC_CTX *ctx, ADS_MODLIST *mods,
 }
 #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));
+               SAFE_FREE(ld_error);
+       }
+}
+
 /**
  * Perform an ldap modify
  * @param ads connection to ads server
@@ -1516,7 +1544,7 @@ ADS_STATUS ads_gen_mod(ADS_STRUCT *ads, const char *mod_dn, ADS_MODLIST mods)
           non-existent attribute (but allowable for the object) to run
        */
        LDAPControl PermitModify = {
-                CONST_DISCARD(char *, ADS_PERMIT_MODIFY_OID),
+                discard_const_p(char, ADS_PERMIT_MODIFY_OID),
                {0, NULL},
                (char) 1};
        LDAPControl *controls[2];
@@ -1534,6 +1562,7 @@ ADS_STATUS ads_gen_mod(ADS_STRUCT *ads, const char *mod_dn, ADS_MODLIST mods)
        mods[i] = NULL;
        ret = ldap_modify_ext_s(ads->ldap.ld, utf8_dn,
                                (LDAPMod **) mods, controls, NULL);
+       ads_print_error(ret, ads->ldap.ld);
        TALLOC_FREE(utf8_dn);
        return ADS_ERROR(ret);
 }
@@ -1562,6 +1591,7 @@ ADS_STATUS ads_gen_add(ADS_STRUCT *ads, const char *new_dn, ADS_MODLIST mods)
        mods[i] = NULL;
 
        ret = ldap_add_s(ads->ldap.ld, utf8_dn, (LDAPMod**)mods);
+       ads_print_error(ret, ads->ldap.ld);
        TALLOC_FREE(utf8_dn);
        return ADS_ERROR(ret);
 }
@@ -1583,6 +1613,7 @@ ADS_STATUS ads_del_dn(ADS_STRUCT *ads, char *del_dn)
        }
 
        ret = ldap_delete_s(ads->ldap.ld, utf8_dn);
+       ads_print_error(ret, ads->ldap.ld);
        TALLOC_FREE(utf8_dn);
        return ADS_ERROR(ret);
 }
@@ -1602,7 +1633,7 @@ char *ads_ou_string(ADS_STRUCT *ads, const char *org_unit)
 
        if (!org_unit || !*org_unit) {
 
-               ret = ads_default_ou_string(ads, WELL_KNOWN_GUID_COMPUTERS);
+               ret = ads_default_ou_string(ads, DS_GUID_COMPUTERS_CONTAINER);
 
                /* samba4 might not yet respond to a wellknownobject-query */
                return ret ? ret : SMB_STRDUP("cn=Computers");
@@ -1734,10 +1765,10 @@ ADS_STATUS ads_add_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
  * @return the kvno for the account, or -1 in case of a failure.
  **/
 
-uint32 ads_get_kvno(ADS_STRUCT *ads, const char *account_name)
+uint32_t ads_get_kvno(ADS_STRUCT *ads, const char *account_name)
 {
        LDAPMessage *res = NULL;
-       uint32 kvno = (uint32)-1;      /* -1 indicates a failure */
+       uint32_t kvno = (uint32_t)-1;      /* -1 indicates a failure */
        char *filter;
        const char *attrs[] = {"msDS-KeyVersionNumber", NULL};
        char *dn_string = NULL;
@@ -1871,33 +1902,123 @@ ADS_STATUS ads_clear_service_principal_names(ADS_STRUCT *ads, const char *machin
        return ret;
 }
 
+/**
+ * @brief Search for an element in a string array.
+ *
+ * @param[in]  el_array  The string array to search.
+ *
+ * @param[in]  num_el    The number of elements in the string array.
+ *
+ * @param[in]  el        The string to search.
+ *
+ * @return               True if found, false if not.
+ */
+bool ads_element_in_array(const char **el_array, size_t num_el, const char *el)
+{
+       size_t i;
+
+       if (el_array == NULL || num_el == 0 || el == NULL) {
+               return false;
+       }
+
+       for (i = 0; i < num_el && el_array[i] != NULL; i++) {
+               int cmp;
+
+               cmp = strcasecmp_m(el_array[i], el);
+               if (cmp == 0) {
+                       return true;
+               }
+       }
+
+       return false;
+}
+
+/**
+ * @brief This gets the service principal names of an existing computer account.
+ *
+ * @param[in]  mem_ctx      The memory context to use to allocate the spn array.
+ *
+ * @param[in]  ads          The ADS context to use.
+ *
+ * @param[in]  machine_name The NetBIOS name of the computer, which is used to
+ *                          identify the computer account.
+ *
+ * @param[in]  spn_array    A pointer to store the array for SPNs.
+ *
+ * @param[in]  num_spns     The number of principals stored in the array.
+ *
+ * @return                  0 on success, or a ADS error if a failure occurred.
+ */
+ADS_STATUS ads_get_service_principal_names(TALLOC_CTX *mem_ctx,
+                                          ADS_STRUCT *ads,
+                                          const char *machine_name,
+                                          char ***spn_array,
+                                          size_t *num_spns)
+{
+       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;
+       }
+
+       *spn_array = ads_pull_strings(ads,
+                                     mem_ctx,
+                                     res,
+                                     "servicePrincipalName",
+                                     num_spns);
+       if (*spn_array == NULL) {
+               DEBUG(1, ("Host account for %s does not have service principal "
+                         "names.\n",
+                         machine_name));
+               status = ADS_ERROR(LDAP_NO_SUCH_OBJECT);
+               goto done;
+       }
+
+done:
+       ads_msgfree(ads, res);
+
+       return status;
+}
+
 /**
  * This adds a service principal name to an existing computer account
  * (found by hostname) in AD.
  * @param ads An initialized ADS_STRUCT
  * @param machine_name the NetBIOS name of the computer, which is used to identify the computer account.
- * @param my_fqdn The fully qualified DNS name of the machine
- * @param spn A string of the service principal to add, i.e. 'host'
+ * @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
  **/
 
-ADS_STATUS ads_add_service_principal_name(ADS_STRUCT *ads, const char *machine_name, 
-                                          const char *my_fqdn, const char *spn)
+ADS_STATUS ads_add_service_principal_names(ADS_STRUCT *ads,
+                                          const char *machine_name,
+                                           const char **spns)
 {
        ADS_STATUS ret;
        TALLOC_CTX *ctx;
        LDAPMessage *res = NULL;
-       char *psp1, *psp2;
        ADS_MODLIST mods;
        char *dn_string = NULL;
-       const char *servicePrincipalName[3] = {NULL, NULL, NULL};
+       const char **servicePrincipalName = spns;
 
        ret = ads_find_machine_acct(ads, &res, machine_name);
        if (!ADS_ERR_OK(ret) || ads_count_replies(ads, res) != 1) {
                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 Principal '%s/%s@%s' has NOT been added.\n",
-                       spn, machine_name, ads->config.realm));
+               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);
        }
@@ -1908,40 +2029,24 @@ ADS_STATUS ads_add_service_principal_name(ADS_STRUCT *ads, const char *machine_n
                return ADS_ERROR(LDAP_NO_MEMORY);
        }
 
-       /* add short name spn */
-
-       if ( (psp1 = talloc_asprintf(ctx, "%s/%s", spn, machine_name)) == NULL ) {
-               talloc_destroy(ctx);
-               ads_msgfree(ads, res);
-               return ADS_ERROR(LDAP_NO_MEMORY);
-       }
-       strupper_m(psp1);
-       strlower_m(&psp1[strlen(spn)]);
-       servicePrincipalName[0] = psp1;
-
-       DEBUG(5,("ads_add_service_principal_name: INFO: Adding %s to host %s\n", 
-               psp1, machine_name));
+       DEBUG(5,("ads_add_service_principal_name: INFO: "
+               "Adding %s to host %s\n",
+               spns[0] ? "N/A" : spns[0], machine_name));
 
 
-       /* add fully qualified spn */
-
-       if ( (psp2 = talloc_asprintf(ctx, "%s/%s", spn, my_fqdn)) == NULL ) {
-               ret = ADS_ERROR(LDAP_NO_MEMORY);
-               goto out;
-       }
-       strupper_m(psp2);
-       strlower_m(&psp2[strlen(spn)]);
-       servicePrincipalName[1] = psp2;
-
-       DEBUG(5,("ads_add_service_principal_name: INFO: Adding %s to host %s\n", 
-               psp2, machine_name));
+       DEBUG(5,("ads_add_service_principal_name: INFO: "
+               "Adding %s to host %s\n",
+               spns[1] ? "N/A" : spns[1], machine_name));
 
        if ( (mods = ads_init_mods(ctx)) == NULL ) {
                ret = ADS_ERROR(LDAP_NO_MEMORY);
                goto out;
        }
 
-       ret = ads_add_strlist(ctx, &mods, "servicePrincipalName", servicePrincipalName);
+       ret = ads_add_strlist(ctx,
+                             &mods,
+                             "servicePrincipalName",
+                             servicePrincipalName);
        if (!ADS_ERR_OK(ret)) {
                DEBUG(1,("ads_add_service_principal_name: Error: Updating Service Principals in LDAP\n"));
                goto out;
@@ -1973,8 +2078,10 @@ ADS_STATUS ads_add_service_principal_name(ADS_STRUCT *ads, const char *machine_n
  * @return 0 upon success, or non-zero otherwise
 **/
 
-ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads, const char *machine_name, 
-                                   const char *org_unit)
+ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads,
+                                  const char *machine_name,
+                                  const char *org_unit,
+                                  uint32_t etype_list)
 {
        ADS_STATUS ret;
        char *samAccountName, *controlstr;
@@ -1985,9 +2092,15 @@ ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads, const char *machine_name,
        const char *objectClass[] = {"top", "person", "organizationalPerson",
                                     "user", "computer", NULL};
        LDAPMessage *res = NULL;
-       uint32 acct_control = ( UF_WORKSTATION_TRUST_ACCOUNT |\
+       uint32_t acct_control = ( UF_WORKSTATION_TRUST_ACCOUNT |\
                                UF_DONT_EXPIRE_PASSWD |\
                                UF_ACCOUNTDISABLE );
+       uint32_t func_level = 0;
+
+       ret = ads_domain_func_level(ads, &func_level);
+       if (!ADS_ERR_OK(ret)) {
+               return ret;
+       }
 
        if (!(ctx = talloc_init("ads_add_machine_acct")))
                return ADS_ERROR(LDAP_NO_MEMORY);
@@ -2006,10 +2119,6 @@ ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads, const char *machine_name,
                goto done;
        }
 
-#ifndef ENCTYPE_ARCFOUR_HMAC
-       acct_control |= UF_USE_DES_KEY_ONLY;
-#endif
-
        if (!(controlstr = talloc_asprintf(ctx, "%u", acct_control))) {
                goto done;
        }
@@ -2023,6 +2132,17 @@ ADS_STATUS ads_create_machine_acct(ADS_STRUCT *ads, const char *machine_name,
        ads_mod_strlist(ctx, &mods, "objectClass", objectClass);
        ads_mod_str(ctx, &mods, "userAccountControl", controlstr);
 
+       if (func_level >= DS_DOMAIN_FUNCTION_2008) {
+               const char *etype_list_str;
+
+               etype_list_str = talloc_asprintf(ctx, "%d", (int)etype_list);
+               if (etype_list_str == NULL) {
+                       goto done;
+               }
+               ads_mod_str(ctx, &mods, "msDS-SupportedEncryptionTypes",
+                           etype_list_str);
+       }
+
        ret = ads_gen_add(ads, new_dn, mods);
 
 done:
@@ -2109,8 +2229,9 @@ done:
 */
 static void dump_binary(ADS_STRUCT *ads, const char *field, struct berval **values)
 {
-       int i, j;
+       size_t i;
        for (i=0; values[i]; i++) {
+               ber_len_t j;
                printf("%s: ", field);
                for (j=0; j<values[i]->bv_len; j++) {
                        printf("%02X", (unsigned char)values[i]->bv_val[j]);
@@ -2123,13 +2244,16 @@ static void dump_guid(ADS_STRUCT *ads, const char *field, struct berval **values
 {
        int i;
        for (i=0; values[i]; i++) {
+               NTSTATUS status;
+               DATA_BLOB in = data_blob_const(values[i]->bv_val, values[i]->bv_len);
+               struct GUID guid;
 
-               UUID_FLAT guid;
-               struct GUID tmp;
-
-               memcpy(guid.info, values[i]->bv_val, sizeof(guid.info));
-               smb_uuid_unpack(guid, &tmp);
-               printf("%s: %s\n", field, GUID_string(talloc_tos(), &tmp));
+               status = GUID_from_ndr_blob(&in, &guid);
+               if (NT_STATUS_IS_OK(status)) {
+                       printf("%s: %s\n", field, GUID_string(talloc_tos(), &guid));
+               } else {
+                       printf("%s: INVALID GUID\n", field);
+               }
        }
 }
 
@@ -2140,10 +2264,15 @@ static void dump_sid(ADS_STRUCT *ads, const char *field, struct berval **values)
 {
        int i;
        for (i=0; values[i]; i++) {
-               DOM_SID sid;
-               fstring tmp;
-               sid_parse(values[i]->bv_val, values[i]->bv_len, &sid);
-               printf("%s: %s\n", field, sid_to_fstring(tmp, &sid));
+               struct sid_parse_ret ret;
+               struct dom_sid sid;
+               struct dom_sid_buf tmp;
+               ret = sid_parse((const uint8_t *)values[i]->bv_val,
+                               values[i]->bv_len, &sid);
+               if (ret.len == -1) {
+                       return;
+               }
+               printf("%s: %s\n", field, dom_sid_str_buf(&sid, &tmp));
        }
 }
 
@@ -2156,7 +2285,7 @@ static void dump_sd(ADS_STRUCT *ads, const char *filed, struct berval **values)
        struct security_descriptor *psd;
        NTSTATUS status;
 
-       status = unmarshall_sec_desc(talloc_tos(), (uint8 *)values[0]->bv_val,
+       status = unmarshall_sec_desc(talloc_tos(), (uint8_t *)values[0]->bv_val,
                                     values[0]->bv_len, &psd);
        if (!NT_STATUS_IS_OK(status)) {
                DEBUG(0, ("unmarshall_sec_desc failed: %s\n",
@@ -2215,7 +2344,7 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
        }
 
        for (i=0; handlers[i].name; i++) {
-               if (StrCaseCmp(handlers[i].name, field) == 0) {
+               if (strcasecmp_m(handlers[i].name, field) == 0) {
                        if (!values) /* first time, indicate string or not */
                                return handlers[i].string;
                        handlers[i].handler(ads, field, (struct berval **) values);
@@ -2275,7 +2404,8 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
                     utf8_field=ldap_next_attribute(ads->ldap.ld,
                                                    (LDAPMessage *)msg,b)) {
                        struct berval **ber_vals;
-                       char **str_vals, **utf8_vals;
+                       char **str_vals;
+                       char **utf8_vals;
                        char *field;
                        bool string; 
 
@@ -2290,10 +2420,12 @@ static bool ads_dump_field(ADS_STRUCT *ads, char *field, void **values, void *da
                        string = fn(ads, field, NULL, data_area);
 
                        if (string) {
+                               const char **p;
+
                                utf8_vals = ldap_get_values(ads->ldap.ld,
                                                 (LDAPMessage *)msg, field);
-                               str_vals = ads_pull_strvals(ctx, 
-                                                 (const char **) utf8_vals);
+                               p = discard_const_p(const char *, utf8_vals);
+                               str_vals = ads_pull_strvals(ctx, p);
                                fn(ads, field, (void **) str_vals, data_area);
                                ldap_value_free(utf8_vals);
                        } else {
@@ -2411,8 +2543,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 {
        char **values;
        char **ret = NULL;
-       int i;
-       size_t converted_size;
+       size_t i, converted_size;
 
        values = ldap_get_values(ads->ldap.ld, msg, field);
        if (!values)
@@ -2420,7 +2551,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 
        *num_values = ldap_count_values(values);
 
-       ret = TALLOC_ARRAY(mem_ctx, char *, *num_values + 1);
+       ret = talloc_array(mem_ctx, char *, *num_values + 1);
        if (!ret) {
                ldap_value_free(values);
                return NULL;
@@ -2533,7 +2664,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
                return NULL;
        }
 
-       strings = TALLOC_REALLOC_ARRAY(mem_ctx, current_strings, char *,
+       strings = talloc_realloc(mem_ctx, current_strings, char *,
                                 *num_strings + num_new_strings);
 
        if (strings == NULL) {
@@ -2569,7 +2700,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 }
 
 /**
- * pull a single uint32 from a ADS result
+ * pull a single uint32_t from a ADS result
  * @param ads connection to ads server
  * @param msg Results of search
  * @param field Attribute to retrieve
@@ -2577,7 +2708,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @return boolean inidicating success
 */
  bool ads_pull_uint32(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
-                     uint32 *v)
+                     uint32_t *v)
 {
        char **values;
 
@@ -2603,27 +2734,22 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  **/
  bool ads_pull_guid(ADS_STRUCT *ads, LDAPMessage *msg, struct GUID *guid)
 {
-       char **values;
-       UUID_FLAT flat_guid;
-
-       values = ldap_get_values(ads->ldap.ld, msg, "objectGUID");
-       if (!values)
-               return False;
+       DATA_BLOB blob;
+       NTSTATUS status;
 
-       if (values[0]) {
-               memcpy(&flat_guid.info, values[0], sizeof(UUID_FLAT));
-               smb_uuid_unpack(flat_guid, guid);
-               ldap_value_free(values);
-               return True;
+       if (!smbldap_talloc_single_blob(talloc_tos(), ads->ldap.ld, msg, "objectGUID",
+                                       &blob)) {
+               return false;
        }
-       ldap_value_free(values);
-       return False;
 
+       status = GUID_from_ndr_blob(&blob, guid);
+       talloc_free(blob.data);
+       return NT_STATUS_IS_OK(status);
 }
 
 
 /**
- * pull a single DOM_SID from a ADS result
+ * pull a single struct dom_sid from a ADS result
  * @param ads connection to ads server
  * @param msg Results of search
  * @param field Attribute to retrieve
@@ -2631,13 +2757,13 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @return boolean inidicating success
 */
  bool ads_pull_sid(ADS_STRUCT *ads, LDAPMessage *msg, const char *field,
-                  DOM_SID *sid)
+                  struct dom_sid *sid)
 {
        return smbldap_pull_sid(ads->ldap.ld, msg, field, sid);
 }
 
 /**
- * pull an array of DOM_SIDs from a ADS result
+ * pull an array of struct dom_sids from a ADS result
  * @param ads connection to ads server
  * @param mem_ctx TALLOC_CTX for allocating sid array
  * @param msg Results of search
@@ -2646,10 +2772,9 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @return the count of SIDs pulled
  **/
  int ads_pull_sids(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
-                  LDAPMessage *msg, const char *field, DOM_SID **sids)
+                  LDAPMessage *msg, const char *field, struct dom_sid **sids)
 {
        struct berval **values;
-       bool ret;
        int count, i;
 
        values = ldap_get_values_len(ads->ldap.ld, msg, field);
@@ -2661,7 +2786,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
                /* nop */ ;
 
        if (i) {
-               (*sids) = TALLOC_ARRAY(mem_ctx, DOM_SID, i);
+               (*sids) = talloc_array(mem_ctx, struct dom_sid, i);
                if (!(*sids)) {
                        ldap_value_free_len(values);
                        return 0;
@@ -2672,10 +2797,13 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 
        count = 0;
        for (i=0; values[i]; i++) {
-               ret = sid_parse(values[i]->bv_val, values[i]->bv_len, &(*sids)[count]);
-               if (ret) {
-                       DEBUG(10, ("pulling SID: %s\n",
-                                  sid_string_dbg(&(*sids)[count])));
+               struct sid_parse_ret ret;
+               ret = sid_parse((const uint8_t *)values[i]->bv_val,
+                               values[i]->bv_len, &(*sids)[count]);
+               if (ret.len != -1) {
+                       struct dom_sid_buf buf;
+                       DBG_DEBUG("pulling SID: %s\n",
+                                 dom_sid_str_buf(&(*sids)[count], &buf));
                        count++;
                }
        }
@@ -2685,16 +2813,17 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
 }
 
 /**
- * pull a SEC_DESC from a ADS result
+ * pull a struct security_descriptor from a ADS result
  * @param ads connection to ads server
  * @param mem_ctx TALLOC_CTX for allocating sid array
  * @param msg Results of search
  * @param field Attribute to retrieve
- * @param sd Pointer to *SEC_DESC to store result (talloc()ed)
+ * @param sd Pointer to *struct security_descriptor to store result (talloc()ed)
  * @return boolean inidicating success
 */
  bool ads_pull_sd(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
-                 LDAPMessage *msg, const char *field, SEC_DESC **sd)
+                 LDAPMessage *msg, const char *field,
+                 struct security_descriptor **sd)
 {
        struct berval **values;
        bool ret = true;
@@ -2706,7 +2835,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
        if (values[0]) {
                NTSTATUS status;
                status = unmarshall_sec_desc(mem_ctx,
-                                            (uint8 *)values[0]->bv_val,
+                                            (uint8_t *)values[0]->bv_val,
                                             values[0]->bv_len, sd);
                if (!NT_STATUS_IS_OK(status)) {
                        DEBUG(0, ("unmarshall_sec_desc failed: %s\n",
@@ -2756,7 +2885,7 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * @param usn Pointer to retrieved update serial number
  * @return status of search
  **/
-ADS_STATUS ads_USN(ADS_STRUCT *ads, uint32 *usn)
+ADS_STATUS ads_USN(ADS_STRUCT *ads, uint32_t *usn)
 {
        const char *attrs[] = {"highestCommittedUSN", NULL};
        ADS_STATUS status;
@@ -2822,6 +2951,7 @@ ADS_STATUS ads_current_time(ADS_STRUCT *ads)
                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_s->auth.flags = ADS_AUTH_ANON_BIND;
@@ -2848,7 +2978,7 @@ ADS_STATUS ads_current_time(ADS_STRUCT *ads)
 
        if (ads->config.current_time != 0) {
                ads->auth.time_offset = ads->config.current_time - time(NULL);
-               DEBUG(4,("time offset is %d seconds\n", ads->auth.time_offset));
+               DEBUG(4,("KDC time offset is %d seconds\n", ads->auth.time_offset));
        }
 
        ads_msgfree(ads, res);
@@ -2868,7 +2998,7 @@ done:
 /********************************************************************
 ********************************************************************/
 
-ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32 *val)
+ADS_STATUS ads_domain_func_level(ADS_STRUCT *ads, uint32_t *val)
 {
        const char *attrs[] = {"domainFunctionality", NULL};
        ADS_STATUS status;
@@ -2926,7 +3056,7 @@ done:
  * @param sid Pointer to domain sid
  * @return status of search
  **/
-ADS_STATUS ads_domain_sid(ADS_STRUCT *ads, DOM_SID *sid)
+ADS_STATUS ads_domain_sid(ADS_STRUCT *ads, struct dom_sid *sid)
 {
        const char *attrs[] = {"objectSid", NULL};
        LDAPMessage *res;
@@ -3138,7 +3268,7 @@ ADS_STATUS ads_get_joinable_ous(ADS_STRUCT *ads,
 
        for (msg = ads_first_entry(ads, res); msg;
             msg = ads_next_entry(ads, msg)) {
-
+               const char **p = discard_const_p(const char *, *ous);
                char *dn = NULL;
 
                dn = ads_get_dn(ads, talloc_tos(), msg);
@@ -3147,15 +3277,14 @@ ADS_STATUS ads_get_joinable_ous(ADS_STRUCT *ads,
                        return ADS_ERROR(LDAP_NO_MEMORY);
                }
 
-               if (!add_string_to_array(mem_ctx, dn,
-                                        (const char ***)ous,
-                                        (int *)num_ous)) {
+               if (!add_string_to_array(mem_ctx, dn, &p, num_ous)) {
                        TALLOC_FREE(dn);
                        ads_msgfree(ads, res);
                        return ADS_ERROR(LDAP_NO_MEMORY);
                }
 
                TALLOC_FREE(dn);
+               *ous = discard_const_p(char *, p);
        }
 
        ads_msgfree(ads, res);
@@ -3165,11 +3294,11 @@ ADS_STATUS ads_get_joinable_ous(ADS_STRUCT *ads,
 
 
 /**
- * pull a DOM_SID from an extended dn string
+ * pull a struct dom_sid from an extended dn string
  * @param mem_ctx TALLOC_CTX
  * @param extended_dn string
  * @param flags string type of extended_dn
- * @param sid pointer to a DOM_SID
+ * @param sid pointer to a struct dom_sid
  * @return NT_STATUS_OK on success,
  *        NT_INVALID_PARAMETER on error,
  *        NT_STATUS_NOT_FOUND if no SID present
@@ -3177,7 +3306,7 @@ ADS_STATUS ads_get_joinable_ous(ADS_STRUCT *ads,
 ADS_STATUS ads_get_sid_from_extended_dn(TALLOC_CTX *mem_ctx,
                                        const char *extended_dn,
                                        enum ads_extended_dn_flags flags,
-                                       DOM_SID *sid)
+                                       struct dom_sid *sid)
 {
        char *p, *q, *dn;
 
@@ -3229,6 +3358,7 @@ ADS_STATUS ads_get_sid_from_extended_dn(TALLOC_CTX *mem_ctx,
                }
                break;
        case ADS_EXTENDED_DN_HEX_STRING: {
+               struct sid_parse_ret ret;
                fstring buf;
                size_t buf_len;
 
@@ -3237,7 +3367,8 @@ ADS_STATUS ads_get_sid_from_extended_dn(TALLOC_CTX *mem_ctx,
                        return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
                }
 
-               if (!sid_parse(buf, buf_len, sid)) {
+               ret = sid_parse((const uint8_t *)buf, buf_len, sid);
+               if (ret.len == -1) {
                        DEBUG(10,("failed to parse sid\n"));
                        return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
                }
@@ -3251,61 +3382,6 @@ ADS_STATUS ads_get_sid_from_extended_dn(TALLOC_CTX *mem_ctx,
        return ADS_ERROR_NT(NT_STATUS_OK);
 }
 
-/**
- * pull an array of DOM_SIDs from a ADS result
- * @param ads connection to ads server
- * @param mem_ctx TALLOC_CTX for allocating sid array
- * @param msg Results of search
- * @param field Attribute to retrieve
- * @param flags string type of extended_dn
- * @param sids pointer to sid array to allocate
- * @return the count of SIDs pulled
- **/
- int ads_pull_sids_from_extendeddn(ADS_STRUCT *ads,
-                                  TALLOC_CTX *mem_ctx,
-                                  LDAPMessage *msg,
-                                  const char *field,
-                                  enum ads_extended_dn_flags flags,
-                                  DOM_SID **sids)
-{
-       int i;
-       ADS_STATUS rc;
-       size_t dn_count, ret_count = 0;
-       char **dn_strings;
-
-       if ((dn_strings = ads_pull_strings(ads, mem_ctx, msg, field,
-                                          &dn_count)) == NULL) {
-               return 0;
-       }
-
-       (*sids) = TALLOC_ZERO_ARRAY(mem_ctx, DOM_SID, dn_count + 1);
-       if (!(*sids)) {
-               TALLOC_FREE(dn_strings);
-               return 0;
-       }
-
-       for (i=0; i<dn_count; i++) {
-               rc = ads_get_sid_from_extended_dn(mem_ctx, dn_strings[i],
-                                                 flags, &(*sids)[i]);
-               if (!ADS_ERR_OK(rc)) {
-                       if (NT_STATUS_EQUAL(ads_ntstatus(rc),
-                           NT_STATUS_NOT_FOUND)) {
-                               continue;
-                       }
-                       else {
-                               TALLOC_FREE(*sids);
-                               TALLOC_FREE(dn_strings);
-                               return 0;
-                       }
-               }
-               ret_count++;
-       }
-
-       TALLOC_FREE(dn_strings);
-
-       return ret_count;
-}
-
 /********************************************************************
 ********************************************************************/
 
@@ -3316,10 +3392,10 @@ char* ads_get_dnshostname( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine
        int count = 0;
        char *name = NULL;
 
-       status = ads_find_machine_acct(ads, &res, global_myname());
+       status = ads_find_machine_acct(ads, &res, machine_name);
        if (!ADS_ERR_OK(status)) {
                DEBUG(0,("ads_get_dnshostname: Failed to find account for %s\n",
-                       global_myname()));
+                       lp_netbios_name()));
                goto out;
        }
 
@@ -3351,7 +3427,7 @@ char* ads_get_upn( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
        status = ads_find_machine_acct(ads, &res, machine_name);
        if (!ADS_ERR_OK(status)) {
                DEBUG(0,("ads_get_upn: Failed to find account for %s\n",
-                       global_myname()));
+                       lp_netbios_name()));
                goto out;
        }
 
@@ -3373,33 +3449,37 @@ out:
 /********************************************************************
 ********************************************************************/
 
-char* ads_get_samaccountname( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
+bool ads_has_samaccountname( ADS_STRUCT *ads, TALLOC_CTX *ctx, const char *machine_name )
 {
        LDAPMessage *res = NULL;
        ADS_STATUS status;
        int count = 0;
        char *name = NULL;
+       bool ok = false;
 
-       status = ads_find_machine_acct(ads, &res, global_myname());
+       status = ads_find_machine_acct(ads, &res, machine_name);
        if (!ADS_ERR_OK(status)) {
-               DEBUG(0,("ads_get_dnshostname: Failed to find account for %s\n",
-                       global_myname()));
+               DEBUG(0,("ads_has_samaccountname: Failed to find account for %s\n",
+                       lp_netbios_name()));
                goto out;
        }
 
        if ( (count = ads_count_replies(ads, res)) != 1 ) {
-               DEBUG(1,("ads_get_dnshostname: %d entries returned!\n", count));
+               DEBUG(1,("ads_has_samaccountname: %d entries returned!\n", count));
                goto out;
        }
 
        if ( (name = ads_pull_string(ads, ctx, res, "sAMAccountName")) == NULL ) {
-               DEBUG(0,("ads_get_dnshostname: No sAMAccountName attribute!\n"));
+               DEBUG(0,("ads_has_samaccountname: No sAMAccountName attribute!\n"));
        }
 
 out:
        ads_msgfree(ads, res);
-
-       return name;
+       if (name != NULL) {
+               ok = (strlen(name) > 0);
+       }
+       TALLOC_FREE(name);
+       return ok;
 }
 
 #if 0
@@ -3415,7 +3495,7 @@ out:
  * @return status of join
  **/
 ADS_STATUS ads_join_realm(ADS_STRUCT *ads, const char *machine_name,
-                       uint32 account_type, const char *org_unit)
+                       uint32_t account_type, const char *org_unit)
 {
        ADS_STATUS status;
        LDAPMessage *res = NULL;
@@ -3476,11 +3556,14 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
 
        pldap_control[0] = &ldap_control;
        memset(&ldap_control, 0, sizeof(LDAPControl));
-       ldap_control.ldctl_oid = (char *)LDAP_SERVER_TREE_DELETE_OID;
+       ldap_control.ldctl_oid = discard_const_p(char, LDAP_SERVER_TREE_DELETE_OID);
 
        /* hostname must be lowercase */
        host = SMB_STRDUP(hostname);
-       strlower_m(host);
+       if (!strlower_m(host)) {
+               SAFE_FREE(host);
+               return ADS_ERROR_SYSTEM(EINVAL);
+       }
 
        status = ads_find_machine_acct(ads, &res, host);
        if (!ADS_ERR_OK(status)) {
@@ -3496,6 +3579,10 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
        }
 
        hostnameDN = ads_get_dn(ads, talloc_tos(), (LDAPMessage *)msg);
+       if (hostnameDN == NULL) {
+               SAFE_FREE(host);
+               return ADS_ERROR_SYSTEM(ENOENT);
+       }
 
        rc = ldap_delete_ext_s(ads->ldap.ld, hostnameDN, pldap_control, NULL);
        if (rc) {
@@ -3583,8 +3670,8 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
  * @param ads connection to ads server
  * @param mem_ctx TALLOC_CTX for allocating sid array
  * @param dn of LDAP object
- * @param user_sid pointer to DOM_SID (objectSid)
- * @param primary_group_sid pointer to DOM_SID (self composed)
+ * @param user_sid pointer to struct dom_sid (objectSid)
+ * @param primary_group_sid pointer to struct dom_sid (self composed)
  * @param sids pointer to sid array to allocate
  * @param num_sids counter of SIDs pulled
  * @return status of token query
@@ -3592,19 +3679,19 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
  ADS_STATUS ads_get_tokensids(ADS_STRUCT *ads,
                              TALLOC_CTX *mem_ctx,
                              const char *dn,
-                             DOM_SID *user_sid,
-                             DOM_SID *primary_group_sid,
-                             DOM_SID **sids,
+                             struct dom_sid *user_sid,
+                             struct dom_sid *primary_group_sid,
+                             struct dom_sid **sids,
                              size_t *num_sids)
 {
        ADS_STATUS status;
        LDAPMessage *res = NULL;
        int count = 0;
        size_t tmp_num_sids;
-       DOM_SID *tmp_sids;
-       DOM_SID tmp_user_sid;
-       DOM_SID tmp_primary_group_sid;
-       uint32 pgid;
+       struct dom_sid *tmp_sids;
+       struct dom_sid tmp_user_sid;
+       struct dom_sid tmp_primary_group_sid;
+       uint32_t pgid;
        const char *attrs[] = {
                "objectSid",
                "tokenGroups",
@@ -3637,12 +3724,11 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
                /* hack to compose the primary group sid without knowing the
                 * domsid */
 
-               DOM_SID domsid;
-               uint32 dummy_rid;
+               struct dom_sid domsid;
 
                sid_copy(&domsid, &tmp_user_sid);
 
-               if (!sid_split_rid(&domsid, &dummy_rid)) {
+               if (!sid_split_rid(&domsid, NULL)) {
                        ads_msgfree(ads, res);
                        return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
                }
@@ -3687,14 +3773,14 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
  * @param ads connection to ads server
  * @param mem_ctx TALLOC_CTX for allocating sid array
  * @param samaccountname to search
- * @param uac_ret uint32 pointer userAccountControl attribute value
+ * @param uac_ret uint32_t pointer userAccountControl attribute value
  * @param dn_ret pointer to dn
  * @return status of token query
  **/
 ADS_STATUS ads_find_samaccount(ADS_STRUCT *ads,
                               TALLOC_CTX *mem_ctx,
                               const char *samaccountname,
-                              uint32 *uac_ret,
+                              uint32_t *uac_ret,
                               const char **dn_ret)
 {
        ADS_STATUS status;
@@ -3702,7 +3788,7 @@ ADS_STATUS ads_find_samaccount(ADS_STRUCT *ads,
        const char *filter;
        LDAPMessage *res = NULL;
        char *dn = NULL;
-       uint32 uac = 0;
+       uint32_t uac = 0;
 
        filter = talloc_asprintf(mem_ctx, "(&(objectclass=user)(sAMAccountName=%s))",
                samaccountname);
@@ -3856,39 +3942,42 @@ ADS_STATUS ads_check_ou_dn(TALLOC_CTX *mem_ctx,
                           ADS_STRUCT *ads,
                           const char **account_ou)
 {
-       struct ldb_dn *name_dn = NULL;
-       const char *name = NULL;
-       char *ou_string = NULL;
-       struct ldb_context *ldb = ldb_init(mem_ctx, NULL);
+       char **exploded_dn;
+       const char *name;
+       char *ou_string;
 
-       name_dn = ldb_dn_new(mem_ctx, ldb, *account_ou);
-       if (name_dn && ldb_dn_validate(name_dn)) {
-               talloc_free(ldb);
-               return ADS_SUCCESS;
+       if (account_ou == NULL) {
+               return ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
+       }
+
+       if (*account_ou != NULL) {
+               exploded_dn = ldap_explode_dn(*account_ou, 0);
+               if (exploded_dn) {
+                       ldap_value_free(exploded_dn);
+                       return ADS_SUCCESS;
+               }
        }
 
        ou_string = ads_ou_string(ads, *account_ou);
        if (!ou_string) {
-               talloc_free(ldb);
                return ADS_ERROR_LDAP(LDAP_INVALID_DN_SYNTAX);
        }
 
-       name_dn = ldb_dn_new_fmt(mem_ctx, ldb, "%s,%s", ou_string,
-                                ads->config.bind_path);
+       name = talloc_asprintf(mem_ctx, "%s,%s", ou_string,
+                              ads->config.bind_path);
        SAFE_FREE(ou_string);
 
-       if (!name_dn || !ldb_dn_validate(name_dn)) {
-               talloc_free(ldb);
-               return ADS_ERROR_LDAP(LDAP_INVALID_DN_SYNTAX);
+       if (!name) {
+               return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
        }
 
-       *account_ou = talloc_strdup(mem_ctx, name);
-       if (!*account_ou) {
-               talloc_free(ldb);
-               return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
+       exploded_dn = ldap_explode_dn(name, 0);
+       if (!exploded_dn) {
+               return ADS_ERROR_LDAP(LDAP_INVALID_DN_SYNTAX);
        }
+       ldap_value_free(exploded_dn);
 
-       talloc_free(ldb);
+       *account_ou = name;
        return ADS_SUCCESS;
 }