r6149: Fixes bugs #2498 and 2484.
[samba.git] / source / libads / ldap.c
index 47a94f0a08d364696ef55906d5433c487828d805..7a59da5a6d363f79971fbfdaeac470e47a0ec80b 100644 (file)
@@ -3,7 +3,7 @@
    ads (active directory) utility library
    Copyright (C) Andrew Tridgell 2001
    Copyright (C) Remus Koos 2001
-   Copyright (C) Jim McDonough 2002
+   Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2002
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
  * codepoints in UTF-8).  This may have to change at some point
  **/
 
+static SIG_ATOMIC_T gotalarm;
+                                                                                                                   
+/***************************************************************
+ Signal function to tell us we timed out.
+****************************************************************/
+                                                                                                                   
+static void gotalarm_sig(void)
+{
+       gotalarm = 1;
+}
+                                                                                                                   
+ LDAP *ldap_open_with_timeout(const char *server, int port, unsigned int to)
+{
+       LDAP *ldp = NULL;
+                                                                                                                   
+       /* Setup timeout */
+       gotalarm = 0;
+       CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
+       alarm(to);
+       /* End setup timeout. */
+                                                                                                                   
+       ldp = ldap_open(server, port);
+                                                                                                                   
+       /* Teardown timeout. */
+       CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
+       alarm(0);
+                                                                                                                   
+       return ldp;
+}
+
+static int ldap_search_with_timeout(LDAP *ld,
+                                   LDAP_CONST char *base,
+                                   int scope,
+                                   LDAP_CONST char *filter,
+                                   char **attrs,
+                                   int attrsonly,
+                                   LDAPControl **sctrls,
+                                   LDAPControl **cctrls,
+                                   int sizelimit,
+                                   LDAPMessage **res )
+{
+       struct timeval timeout;
+       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, SIGNAL_CAST gotalarm_sig);
+       alarm(lp_ldap_timeout());
+       /* End setup timeout. */
+
+       result = ldap_search_ext_s(ld, base, scope, filter, attrs,
+                                  attrsonly, sctrls, cctrls, &timeout,
+                                  sizelimit, res);
+
+       /* Teardown timeout. */
+       CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
+       alarm(0);
+
+       if (gotalarm != 0)
+               return LDAP_TIMELIMIT_EXCEEDED;
+
+       return result;
+}
 
 /*
   try a connection to a given ldap server, returning True and setting the servers IP
   in the ads struct if successful
+  
+  TODO : add a negative connection cache in here leveraged off of the one
+  found in the rpc code.  --jerry
  */
-static BOOL ads_try_connect(ADS_STRUCT *ads, const char *server, unsigned port)
+BOOL ads_try_connect(ADS_STRUCT *ads, const char *server, unsigned port)
 {
        char *srv;
 
@@ -53,9 +123,9 @@ static BOOL ads_try_connect(ADS_STRUCT *ads, const char *server, unsigned port)
        DEBUG(5,("ads_try_connect: trying ldap server '%s' port %u\n", server, port));
 
        /* this copes with inet_ntoa brokenness */
-       srv = strdup(server);
+       srv = SMB_STRDUP(server);
 
-       ads->ld = ldap_open(srv, port);
+       ads->ld = ldap_open_with_timeout(srv, port, lp_ldap_timeout());
        if (!ads->ld) {
                free(srv);
                return False;
@@ -90,133 +160,94 @@ static BOOL ads_try_connect_uri(ADS_STRUCT *ads)
        return False;
 }
 
-/* used by the IP comparison function */
-struct ldap_ip {
-       struct in_addr ip;
-       unsigned port;
-};
-
-/* compare 2 ldap IPs by nearness to our interfaces - used in qsort */
-static int ldap_ip_compare(struct ldap_ip *ip1, struct ldap_ip *ip2)
-{
-       return ip_compare(&ip1->ip, &ip2->ip);
-}
+/**********************************************************************
+ 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
+**********************************************************************/
 
-/* try connecting to a ldap server via DNS */
-static BOOL ads_try_dns(ADS_STRUCT *ads)
+static BOOL ads_find_dc(ADS_STRUCT *ads)
 {
        const char *c_realm;
-       const char *ptr;
-       char *realm;
-       char *list = NULL;
-       pstring tok;
-       struct ldap_ip *ip_list;
        int count, i=0;
+       struct ip_service *ip_list;
+       pstring realm;
+       BOOL got_realm = False;
+       BOOL use_own_domain = False;
 
+       /* if the realm and workgroup are both empty, assume they are ours */
+
+       /* realm */
        c_realm = ads->server.realm;
-       if (!c_realm || !*c_realm) {
-               c_realm = lp_realm();
+       
+       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();
+               }
        }
-       if (!c_realm || !*c_realm) {
+       
+       if (c_realm && *c_realm) 
+               got_realm = True;
+                  
+again:
+       /* 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 */
+          
+       if ( !got_realm && !lp_disable_netbios() ) {
                c_realm = ads->server.workgroup;
-       }
-       if (!c_realm || !*c_realm) {
-               c_realm = lp_workgroup();
-       }
-       if (!c_realm) {
-               return False;
-       }
-       realm = smb_xstrdup(c_realm);
-
-       DEBUG(6,("ads_try_dns: looking for realm '%s'\n", realm));
-       if (ldap_domain2hostlist(realm, &list) != LDAP_SUCCESS) {
-               SAFE_FREE(realm);
-               return False;
-       }
-
-       DEBUG(6,("ads_try_dns: ldap realm '%s' host list '%s'\n", realm, list));
-       SAFE_FREE(realm);
-
-       count = count_chars(list, ' ') + 1;
-       ip_list = malloc(count * sizeof(struct ldap_ip));
-       if (!ip_list) {
-               return False;
-       }
-
-       ptr = list;
-       while (next_token(&ptr, tok, " ", sizeof(tok))) {
-               unsigned port = LDAP_PORT;
-               char *p = strchr(tok, ':');
-               if (p) {
-                       *p = 0;
-                       port = atoi(p+1);
+               if (!c_realm || !*c_realm) {
+                       if ( use_own_domain )
+                               c_realm = lp_workgroup();
                }
-               ip_list[i].ip = *interpret_addr2(tok);
-               ip_list[i].port = port;
-               if (!is_zero_ip(ip_list[i].ip)) {
-                       i++;
+               
+               if ( !c_realm || !*c_realm ) {
+                       DEBUG(0,("ads_find_dc: no realm or workgroup!  Don't know what to do\n"));
+                       return False;
                }
        }
-       free(list);
+       
+       pstrcpy( realm, c_realm );
 
-       count = i;
+       DEBUG(6,("ads_find_dc: looking for %s '%s'\n", 
+               (got_realm ? "realm" : "domain"), realm));
 
-       /* we sort the list of addresses by closeness to our interfaces. This
-          tries to prevent us using a DC on the other side of the country */
-       if (count > 1) {
-               qsort(ip_list, count, sizeof(struct ldap_ip), 
-                     QSORT_CAST ldap_ip_compare);      
+       if ( !get_sorted_dc_list(realm, &ip_list, &count, got_realm) ) {
+               /* fall back to netbios if we can */
+               if ( got_realm && !lp_disable_netbios() ) {
+                       got_realm = False;
+                       goto again;
+               }
+               
+               return False;
        }
-
-       for (i=0;i<count;i++) {
-               if (ads_try_connect(ads, inet_ntoa(ip_list[i].ip), ip_list[i].port)) {
-                       free(ip_list);
+                       
+       /* if we fail this loop, then giveup since all the IP addresses returned were dead */
+       for ( i=0; i<count; i++ ) {
+               /* since this is an ads conection request, default to LDAP_PORT is not set */
+               int port = (ip_list[i].port!=PORT_NONE) ? ip_list[i].port : LDAP_PORT;
+               fstring server;
+               
+               fstrcpy( server, inet_ntoa(ip_list[i].ip) );
+               
+               if ( !NT_STATUS_IS_OK(check_negative_conn_cache(realm, server)) )
+                       continue;
+                       
+               if ( ads_try_connect(ads, server, port) ) {
+                       SAFE_FREE(ip_list);
                        return True;
                }
+               
+               /* keep track of failures */
+               add_failed_connection_entry( realm, server, NT_STATUS_UNSUCCESSFUL );
        }
 
        SAFE_FREE(ip_list);
+       
        return False;
 }
 
-/* try connecting to a ldap server via netbios */
-static BOOL ads_try_netbios(ADS_STRUCT *ads)
-{
-       struct in_addr *ip_list, pdc_ip;
-       int count;
-       int i;
-       const char *workgroup = ads->server.workgroup;
-       BOOL list_ordered;
-
-       if (!workgroup) {
-               workgroup = lp_workgroup();
-       }
-
-       DEBUG(6,("ads_try_netbios: looking for workgroup '%s'\n", workgroup));
-
-       /* try the PDC first */
-       if (get_pdc_ip(workgroup, &pdc_ip)) { 
-               DEBUG(6,("ads_try_netbios: trying server '%s'\n", 
-                        inet_ntoa(pdc_ip)));
-               if (ads_try_connect(ads, inet_ntoa(pdc_ip), LDAP_PORT))
-                       return True;
-       }
-
-       /* now any DC, including backups */
-       if (get_dc_list(workgroup, &ip_list, &count, &list_ordered)) { 
-               for (i=0;i<count;i++) {
-                       DEBUG(6,("ads_try_netbios: trying server '%s'\n", 
-                                inet_ntoa(ip_list[i])));
-                       if (ads_try_connect(ads, inet_ntoa(ip_list[i]), LDAP_PORT)) {
-                               free(ip_list);
-                               return True;
-                       }
-               }
-               free(ip_list);
-       }
-
-       return False;
-}
 
 /**
  * Connect to the LDAP server
@@ -244,20 +275,7 @@ ADS_STATUS ads_connect(ADS_STRUCT *ads)
                goto got_connection;
        }
 
-       /* try with a smb.conf ads server setting if we are connecting
-           to the primary workgroup or realm */
-       if (!ads->server.foreign &&
-           ads_try_connect(ads, lp_ads_server(), LDAP_PORT)) {
-               goto got_connection;
-       }
-
-       /* try via DNS */
-       if (ads_try_dns(ads)) {
-               goto got_connection;
-       }
-
-       /* try via netbios lookups */
-       if (!lp_disable_netbios() && ads_try_netbios(ads)) {
+       if (ads_find_dc(ads)) {
                goto got_connection;
        }
 
@@ -275,19 +293,18 @@ got_connection:
        ldap_set_option(ads->ld, LDAP_OPT_PROTOCOL_VERSION, &version);
 
        if (!ads->auth.user_name) {
-               /* by default use the machine account */
-               fstring myname;
-               fstrcpy(myname, global_myname());
-               strlower(myname);
-               asprintf(&ads->auth.user_name, "HOST/%s", myname);
+               /* have to use the userPrincipalName value here and 
+                  not servicePrincipalName; found by Guenther Deschner @ Sernet */
+
+               asprintf(&ads->auth.user_name, "host/%s", global_myname() );
        }
 
        if (!ads->auth.realm) {
-               ads->auth.realm = strdup(ads->config.realm);
+               ads->auth.realm = SMB_STRDUP(ads->config.realm);
        }
 
        if (!ads->auth.kdc_server) {
-               ads->auth.kdc_server = strdup(inet_ntoa(ads->ldap_ip));
+               ads->auth.kdc_server = SMB_STRDUP(inet_ntoa(ads->ldap_ip));
        }
 
 #if KRB5_DNS_HACK
@@ -325,13 +342,13 @@ static struct berval *dup_berval(TALLOC_CTX *ctx, const struct berval *in_val)
 
        if (!in_val) return NULL;
 
-       value = talloc_zero(ctx, sizeof(struct berval));
+       value = TALLOC_ZERO_P(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 = talloc_memdup(ctx, in_val->bv_val, in_val->bv_len);
+       value->bv_val = TALLOC_MEMDUP(ctx, in_val->bv_val, in_val->bv_len);
        return value;
 }
 
@@ -345,9 +362,9 @@ static struct berval **ads_dup_values(TALLOC_CTX *ctx,
        int i;
        
        if (!in_vals) return NULL;
-       for (i=0; in_vals[i]; i++); /* count values */
-       values = (struct berval **) talloc_zero(ctx, 
-                                               (i+1)*sizeof(struct berval *));
+       for (i=0; in_vals[i]; i++)
+               ; /* count values */
+       values = TALLOC_ZERO_ARRAY(ctx, struct berval *, i+1);
        if (!values) return NULL;
 
        for (i=0; in_vals[i]; i++) {
@@ -365,8 +382,9 @@ static char **ads_push_strvals(TALLOC_CTX *ctx, const char **in_vals)
        int i;
        
        if (!in_vals) return NULL;
-       for (i=0; in_vals[i]; i++); /* count values */
-       values = (char ** ) talloc_zero(ctx, (i+1)*sizeof(char *));
+       for (i=0; in_vals[i]; i++)
+               ; /* count values */
+       values = TALLOC_ZERO_ARRAY(ctx, char *, i+1);
        if (!values) return NULL;
 
        for (i=0; in_vals[i]; i++) {
@@ -384,8 +402,9 @@ static char **ads_pull_strvals(TALLOC_CTX *ctx, const char **in_vals)
        int i;
        
        if (!in_vals) return NULL;
-       for (i=0; in_vals[i]; i++); /* count values */
-       values = (char **) talloc_zero(ctx, (i+1)*sizeof(char *));
+       for (i=0; in_vals[i]; i++)
+               ; /* count values */
+       values = TALLOC_ZERO_ARRAY(ctx, char *, i+1);
        if (!values) return NULL;
 
        for (i=0; in_vals[i]; i++) {
@@ -400,8 +419,8 @@ static char **ads_pull_strvals(TALLOC_CTX *ctx, const char **in_vals)
  *  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_BASE | LDAP_ONE | LDAP_SUBTREE)
- * @param exp Search expression - specified in local charset
+ * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
+ * @param expr Search expression - specified in local charset
  * @param attrs Attributes to retrieve - specified in utf8 or ascii
  * @param res ** which will contain results - free res* with ads_msgfree()
  * @param count Number of entries retrieved on this page
@@ -409,12 +428,12 @@ static char **ads_pull_strvals(TALLOC_CTX *ctx, const char **in_vals)
  * @return status of search
  **/
 ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
-                              int scope, const char *exp,
+                              int scope, const char *expr,
                               const char **attrs, void **res, 
                               int *count, void **cookie)
 {
        int rc, i, version;
-       char *utf8_exp, *utf8_path, **search_attrs;
+       char *utf8_expr, *utf8_path, **search_attrs;
        LDAPControl PagedResults, NoReferrals, *controls[3], **rcontrols; 
        BerElement *cookie_be = NULL;
        struct berval *cookie_bv= NULL;
@@ -426,10 +445,10 @@ ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
                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 
+          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_exp, exp) < 0) ||
-           (push_utf8_talloc(ctx, &utf8_path, bind_path) < 0)) {
+       if ((push_utf8_talloc(ctx, &utf8_expr, expr) == (size_t)-1) ||
+           (push_utf8_talloc(ctx, &utf8_path, bind_path) == (size_t)-1)) {
                rc = LDAP_NO_MEMORY;
                goto done;
        }
@@ -462,23 +481,21 @@ ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
                ber_printf(cookie_be, "{io}", (ber_int_t) 1000, "", 0);
        }
        ber_flatten(cookie_be, &cookie_bv);
-       PagedResults.ldctl_oid = ADS_PAGE_CTL_OID;
+       PagedResults.ldctl_oid = CONST_DISCARD(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 = ADS_NO_REFERRALS_OID;
+       NoReferrals.ldctl_oid = CONST_DISCARD(char *, ADS_NO_REFERRALS_OID);
        NoReferrals.ldctl_iscritical = (char) 0;
        NoReferrals.ldctl_value.bv_len = 0;
-       NoReferrals.ldctl_value.bv_val = "";
+       NoReferrals.ldctl_value.bv_val = CONST_DISCARD(char *, "");
 
 
        controls[0] = &NoReferrals;
        controls[1] = &PagedResults;
        controls[2] = NULL;
 
-       *res = NULL;
-
        /* 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 
@@ -489,15 +506,17 @@ ADS_STATUS ads_do_paged_search(ADS_STRUCT *ads, const char *bind_path,
        */
        ldap_set_option(ads->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
 
-       rc = ldap_search_ext_s(ads->ld, utf8_path, scope, utf8_exp, 
-                              search_attrs, 0, controls,
-                              NULL, NULL, LDAP_NO_LIMIT, (LDAPMessage **)res);
+       rc = ldap_search_with_timeout(ads->ld, utf8_path, scope, utf8_expr, 
+                                     search_attrs, 0, controls,
+                                     NULL, LDAP_NO_LIMIT,
+                                     (LDAPMessage **)res);
 
        ber_free(cookie_be, 1);
        ber_bvfree(cookie_bv);
 
        if (rc) {
-               DEBUG(3,("ldap_search_ext_s(%s) -> %s\n", exp, ldap_err2string(rc)));
+               DEBUG(3,("ads_do_paged_search: ldap_search_with_timeout(%s) -> %s\n", expr,
+                        ldap_err2string(rc)));
                goto done;
        }
 
@@ -540,21 +559,22 @@ done:
  * all entries in a large search.
  * @param ads connection to ads server 
  * @param bind_path Base dn for the search
- * @param scope Scope of search (LDAP_BASE | LDAP_ONE | LDAP_SUBTREE)
- * @param exp Search expression
+ * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
+ * @param expr Search expression
  * @param attrs Attributes to retrieve
  * @param res ** which will contain results - free res* with ads_msgfree()
  * @return status of search
  **/
 ADS_STATUS ads_do_search_all(ADS_STRUCT *ads, const char *bind_path,
-                            int scope, const char *exp,
+                            int scope, const char *expr,
                             const char **attrs, void **res)
 {
        void *cookie = NULL;
        int count = 0;
        ADS_STATUS status;
 
-       status = ads_do_paged_search(ads, bind_path, scope, exp, attrs, res,
+       *res = NULL;
+       status = ads_do_paged_search(ads, bind_path, scope, expr, attrs, res,
                                     &count, &cookie);
 
        if (!ADS_ERR_OK(status)) return status;
@@ -564,7 +584,7 @@ ADS_STATUS ads_do_search_all(ADS_STRUCT *ads, const char *bind_path,
                ADS_STATUS status2;
                LDAPMessage *msg, *next;
 
-               status2 = ads_do_paged_search(ads, bind_path, scope, exp, 
+               status2 = ads_do_paged_search(ads, bind_path, scope, expr
                                              attrs, &res2, &count, &cookie);
 
                if (!ADS_ERR_OK(status2)) break;
@@ -587,15 +607,15 @@ ADS_STATUS ads_do_search_all(ADS_STRUCT *ads, const char *bind_path,
  *  runs the function as each page is returned, using ads_process_results()
  * @param ads connection to ads server
  * @param bind_path Base dn for the search
- * @param scope Scope of search (LDAP_BASE | LDAP_ONE | LDAP_SUBTREE)
- * @param exp Search expression - specified in local charset
+ * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
+ * @param expr Search expression - specified in local charset
  * @param attrs Attributes to retrieve - specified in UTF-8 or ascii
  * @param fn Function which takes attr name, values list, and data_area
  * @param data_area Pointer which is passed to function on each call
  * @return status of search
  **/
 ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
-                               int scope, const char *exp, const char **attrs,
+                               int scope, const char *expr, const char **attrs,
                                BOOL(*fn)(char *, void **, void *), 
                                void *data_area)
 {
@@ -604,7 +624,7 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
        ADS_STATUS status;
        void *res;
 
-       status = ads_do_paged_search(ads, bind_path, scope, exp, attrs, &res,
+       status = ads_do_paged_search(ads, bind_path, scope, expr, attrs, &res,
                                     &count, &cookie);
 
        if (!ADS_ERR_OK(status)) return status;
@@ -613,7 +633,7 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
        ads_msgfree(ads, res);
 
        while (cookie) {
-               status = ads_do_paged_search(ads, bind_path, scope, exp, attrs,
+               status = ads_do_paged_search(ads, bind_path, scope, expr, attrs,
                                             &res, &count, &cookie);
 
                if (!ADS_ERR_OK(status)) break;
@@ -629,21 +649,21 @@ ADS_STATUS ads_do_search_all_fn(ADS_STRUCT *ads, const char *bind_path,
  * Do a search with a timeout.
  * @param ads connection to ads server
  * @param bind_path Base dn for the search
- * @param scope Scope of search (LDAP_BASE | LDAP_ONE | LDAP_SUBTREE)
- * @param exp Search expression
+ * @param scope Scope of search (LDAP_SCOPE_BASE | LDAP_SCOPE_ONE | LDAP_SCOPE_SUBTREE)
+ * @param expr Search expression
  * @param attrs Attributes to retrieve
  * @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, 
-                        const char *exp,
+                        const char *expr,
                         const char **attrs, void **res)
 {
-       struct timeval timeout;
        int rc;
-       char *utf8_exp, *utf8_path, **search_attrs = NULL;
+       char *utf8_expr, *utf8_path, **search_attrs = NULL;
        TALLOC_CTX *ctx;
 
+       *res = NULL;
        if (!(ctx = talloc_init("ads_do_search"))) {
                DEBUG(1,("ads_do_search: talloc_init() failed!"));
                return ADS_ERROR(LDAP_NO_MEMORY);
@@ -652,8 +672,8 @@ ADS_STATUS ads_do_search(ADS_STRUCT *ads, const char *bind_path, int scope,
        /* 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_exp, exp) < 0) ||
-           (push_utf8_talloc(ctx, &utf8_path, bind_path) < 0)) {
+       if ((push_utf8_talloc(ctx, &utf8_expr, expr) == (size_t)-1) ||
+           (push_utf8_talloc(ctx, &utf8_path, bind_path) == (size_t)-1)) {
                DEBUG(1,("ads_do_search: push_utf8_talloc() failed!"));
                rc = LDAP_NO_MEMORY;
                goto done;
@@ -672,16 +692,13 @@ ADS_STATUS ads_do_search(ADS_STRUCT *ads, const char *bind_path, int scope,
                }
        }
 
-       timeout.tv_sec = ADS_SEARCH_TIMEOUT;
-       timeout.tv_usec = 0;
-       *res = NULL;
-
        /* see the note in ads_do_paged_search - we *must* disable referrals */
        ldap_set_option(ads->ld, LDAP_OPT_REFERRALS, LDAP_OPT_OFF);
 
-       rc = ldap_search_ext_s(ads->ld, utf8_path, scope, utf8_exp,
-                              search_attrs, 0, NULL, NULL, 
-                              &timeout, LDAP_NO_LIMIT, (LDAPMessage **)res);
+       rc = ldap_search_with_timeout(ads->ld, utf8_path, scope, utf8_expr,
+                                     search_attrs, 0, NULL, NULL, 
+                                     LDAP_NO_LIMIT,
+                                     (LDAPMessage **)res);
 
        if (rc == LDAP_SIZELIMIT_EXCEEDED) {
                DEBUG(3,("Warning! sizelimit exceeded in ldap. Truncating.\n"));
@@ -698,16 +715,16 @@ ADS_STATUS ads_do_search(ADS_STRUCT *ads, const char *bind_path, int scope,
  * Do a general ADS search
  * @param ads connection to ads server
  * @param res ** which will contain results - free res* with ads_msgfree()
- * @param exp Search expression
+ * @param expr Search expression
  * @param attrs Attributes to retrieve
  * @return status of search
  **/
 ADS_STATUS ads_search(ADS_STRUCT *ads, void **res, 
-                     const char *exp, 
+                     const char *expr
                      const char **attrs)
 {
        return ads_do_search(ads, ads->config.bind_path, LDAP_SCOPE_SUBTREE, 
-                            exp, attrs, res);
+                            expr, attrs, res);
 }
 
 /**
@@ -749,15 +766,25 @@ void ads_memfree(ADS_STRUCT *ads, void *mem)
 /**
  * Get a dn from search results
  * @param ads connection to ads server
- * @param res Search results
+ * @param msg Search result
  * @return dn string
  **/
-char *ads_get_dn(ADS_STRUCT *ads, void *res)
+char *ads_get_dn(ADS_STRUCT *ads, void *msg)
 {
        char *utf8_dn, *unix_dn;
 
-       utf8_dn = ldap_get_dn(ads->ld, res);
-       pull_utf8_allocate((void **) &unix_dn, utf8_dn);
+       utf8_dn = ldap_get_dn(ads->ld, msg);
+
+       if (!utf8_dn) {
+               DEBUG (5, ("ads_get_dn: ldap_get_dn failed\n"));
+               return NULL;
+       }
+
+       if (pull_utf8_allocate(&unix_dn, utf8_dn) == (size_t)-1) {
+               DEBUG(0,("ads_get_dn: string conversion failure utf8 [%s]\n",
+                       utf8_dn ));
+               return NULL;
+       }
        ldap_memfree(utf8_dn);
        return unix_dn;
 }
@@ -769,21 +796,23 @@ char *ads_get_dn(ADS_STRUCT *ads, void *res)
  * @param host Hostname to search for
  * @return status of search
  **/
-ADS_STATUS ads_find_machine_acct(ADS_STRUCT *ads, void **res, const char *host)
+ADS_STATUS ads_find_machine_acct(ADS_STRUCT *ads, void **res, const char *machine)
 {
        ADS_STATUS status;
-       char *exp;
+       char *expr;
        const char *attrs[] = {"*", "nTSecurityDescriptor", NULL};
 
+       *res = NULL;
+
        /* the easiest way to find a machine account anywhere in the tree
           is to look for hostname$ */
-       if (asprintf(&exp, "(samAccountName=%s$)", host) == -1) {
+       if (asprintf(&expr, "(samAccountName=%s$)", machine) == -1) {
                DEBUG(1, ("asprintf failed!\n"));
                return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
        }
        
-       status = ads_search(ads, res, exp, attrs);
-       free(exp);
+       status = ads_search(ads, res, expr, attrs);
+       SAFE_FREE(expr);
        return status;
 }
 
@@ -797,13 +826,12 @@ ADS_MODLIST ads_init_mods(TALLOC_CTX *ctx)
 #define ADS_MODLIST_ALLOC_SIZE 10
        LDAPMod **mods;
        
-       if ((mods = (LDAPMod **) talloc_zero(ctx, sizeof(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;
        
-       return mods;
+       return (ADS_MODLIST)mods;
 }
 
 
@@ -816,40 +844,44 @@ static ADS_STATUS ads_modlist_add(TALLOC_CTX *ctx, ADS_MODLIST *mods,
 {
        int curmod;
        LDAPMod **modlist = (LDAPMod **) *mods;
-       void **values;
+       struct berval **ber_values = NULL;
+       char **char_values = NULL;
 
        if (!invals) {
-               values = NULL;
                mod_op = LDAP_MOD_DELETE;
        } else {
                if (mod_op & LDAP_MOD_BVALUES)
-                       values = (void **) ads_dup_values(ctx, 
-                                          (const struct berval **)invals);
+                       ber_values = ads_dup_values(ctx, 
+                                               (const struct berval **)invals);
                else
-                       values = (void **) ads_push_strvals(ctx, 
-                                                  (const char **) invals);
+                       char_values = ads_push_strvals(ctx, 
+                                                 (const char **) invals);
        }
 
        /* find the first empty slot */
        for (curmod=0; modlist[curmod] && modlist[curmod] != (LDAPMod *) -1;
             curmod++);
        if (modlist[curmod] == (LDAPMod *) -1) {
-               if (!(modlist = talloc_realloc(ctx, modlist, 
-                       (curmod+ADS_MODLIST_ALLOC_SIZE+1)*sizeof(LDAPMod *))))
+               if (!(modlist = TALLOC_REALLOC_ARRAY(ctx, modlist, LDAPMod *,
+                               curmod+ADS_MODLIST_ALLOC_SIZE+1)))
                        return ADS_ERROR(LDAP_NO_MEMORY);
                memset(&modlist[curmod], 0, 
                       ADS_MODLIST_ALLOC_SIZE*sizeof(LDAPMod *));
                modlist[curmod+ADS_MODLIST_ALLOC_SIZE] = (LDAPMod *) -1;
-               *mods = modlist;
+               *mods = (ADS_MODLIST)modlist;
        }
                
-       if (!(modlist[curmod] = talloc_zero(ctx, sizeof(LDAPMod))))
+       if (!(modlist[curmod] = TALLOC_ZERO_P(ctx, LDAPMod)))
                return ADS_ERROR(LDAP_NO_MEMORY);
        modlist[curmod]->mod_type = talloc_strdup(ctx, name);
-       if (mod_op & LDAP_MOD_BVALUES)
-               modlist[curmod]->mod_bvalues = (struct berval **) values;
-       else
-               modlist[curmod]->mod_values = (char **) values;
+       if (mod_op & LDAP_MOD_BVALUES) {
+               modlist[curmod]->mod_bvalues = ber_values;
+       } else if (mod_op & LDAP_MOD_DELETE) {
+               modlist[curmod]->mod_values = NULL;
+       } else {
+               modlist[curmod]->mod_values = char_values;
+       }
+
        modlist[curmod]->mod_op = mod_op;
        return ADS_ERROR(LDAP_SUCCESS);
 }
@@ -930,7 +962,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 = {
-               ADS_PERMIT_MODIFY_OID,
+                CONST_DISCARD(char *, ADS_PERMIT_MODIFY_OID),
                {0, NULL},
                (char) 1};
        LDAPControl *controls[2];
@@ -974,7 +1006,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->ld, utf8_dn, mods);
+       ret = ldap_add_s(ads->ld, utf8_dn, (LDAPMod**)mods);
        SAFE_FREE(utf8_dn);
        return ADS_ERROR(ret);
 }
@@ -994,7 +1026,7 @@ ADS_STATUS ads_del_dn(ADS_STRUCT *ads, char *del_dn)
                return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
        }
        
-       ret = ldap_delete(ads->ld, utf8_dn);
+       ret = ldap_delete_s(ads->ld, utf8_dn);
        return ADS_ERROR(ret);
 }
 
@@ -1002,97 +1034,481 @@ ADS_STATUS ads_del_dn(ADS_STRUCT *ads, char *del_dn)
  * Build an org unit string
  *  if org unit is Computers or blank then assume a container, otherwise
  *  assume a \ separated list of organisational units
+ * @param ads connection to ads server
  * @param org_unit Organizational unit
  * @return org unit string - caller must free
  **/
-char *ads_ou_string(const char *org_unit)
-{      
-       if (!org_unit || !*org_unit || strcasecmp(org_unit, "Computers") == 0) {
-               return strdup("cn=Computers");
+char *ads_ou_string(ADS_STRUCT *ads, const char *org_unit)
+{
+       char *ret = NULL;
+
+       if (!org_unit || !*org_unit) {
+
+               ret = ads_default_ou_string(ads, WELL_KNOWN_GUID_COMPUTERS);
+
+               /* samba4 might not yet respond to a wellknownobject-query */
+               return ret ? ret : SMB_STRDUP("cn=Computers");
+       }
+       
+       if (strequal(org_unit, "Computers")) {
+               return SMB_STRDUP("cn=Computers");
        }
 
        return ads_build_path(org_unit, "\\/", "ou=", 1);
 }
 
+/**
+ * Get a org unit string for a well-known GUID
+ * @param ads connection to ads server
+ * @param wknguid Well known GUID
+ * @return org unit string - caller must free
+ **/
+char *ads_default_ou_string(ADS_STRUCT *ads, const char *wknguid)
+{
+       ADS_STATUS status;
+       void *res;
+       char *base, *wkn_dn, *ret, **wkn_dn_exp, **bind_dn_exp;
+       const char *attrs[] = {"distinguishedName", NULL};
+       int new_ln, wkn_ln, bind_ln, i;
+
+       if (wknguid == NULL) {
+               return NULL;
+       }
+
+       if (asprintf(&base, "<WKGUID=%s,%s>", wknguid, ads->config.bind_path ) == -1) {
+               DEBUG(1, ("asprintf failed!\n"));
+               return NULL;
+       }
+
+       status = ads_search_dn(ads, &res, base, attrs);
+       if (!ADS_ERR_OK(status)) {
+               DEBUG(1,("Failed while searching for: %s\n", base));
+               return NULL;
+       }
+       free(base);
+
+       if (ads_count_replies(ads, res) != 1) {
+               return NULL;
+       }
+
+       /* substitute the bind-path from the well-known-guid-search result */
+       wkn_dn = ads_get_dn(ads, res);
+       wkn_dn_exp = ldap_explode_dn(wkn_dn, 0);
+       bind_dn_exp = ldap_explode_dn(ads->config.bind_path, 0);
+
+       for (wkn_ln=0; wkn_dn_exp[wkn_ln]; wkn_ln++)
+               ;
+       for (bind_ln=0; bind_dn_exp[bind_ln]; bind_ln++)
+               ;
+
+       new_ln = wkn_ln - bind_ln;
+
+       ret = wkn_dn_exp[0];
+
+       for (i=1; i < new_ln; i++) {
+               char *s;
+               asprintf(&s, "%s,%s", ret, wkn_dn_exp[i]);
+               ret = SMB_STRDUP(s);
+               free(s);
+       }
+
+       return ret;
+}
+
+/**
+ * Adds (appends) an item to an attribute array, rather then
+ * replacing the whole list
+ * @param ctx An initialized TALLOC_CTX
+ * @param mods An initialized ADS_MODLIST
+ * @param name name of the ldap attribute to append to
+ * @param vals an array of values to add
+ * @return status of addition
+ **/
+
+ADS_STATUS ads_add_strlist(TALLOC_CTX *ctx, ADS_MODLIST *mods,
+                               const char *name, const char **vals)
+{
+       return ads_modlist_add(ctx, mods, LDAP_MOD_ADD, name, (const void **) vals);
+}
+
+/**
+ * Determines the computer account's current KVNO via an LDAP lookup
+ * @param ads An initialized ADS_STRUCT
+ * @param machine_name the NetBIOS name of the computer, which is used to identify the computer account.
+ * @return the kvno for the computer account, or -1 in case of a failure.
+ **/
 
+uint32 ads_get_kvno(ADS_STRUCT *ads, const char *machine_name)
+{
+       LDAPMessage *res = NULL;
+       uint32 kvno = (uint32)-1;      /* -1 indicates a failure */
+       char *filter;
+       const char *attrs[] = {"msDS-KeyVersionNumber", NULL};
+       char *dn_string = NULL;
+       ADS_STATUS ret = ADS_ERROR(LDAP_SUCCESS);
+
+       DEBUG(5,("ads_get_kvno: Searching for host %s\n", machine_name));
+       if (asprintf(&filter, "(samAccountName=%s$)", machine_name) == -1) {
+               return kvno;
+       }
+       ret = ads_search(ads, (void**) &res, filter, attrs);
+       SAFE_FREE(filter);
+       if (!ADS_ERR_OK(ret) && ads_count_replies(ads, res)) {
+               DEBUG(1,("ads_get_kvno: Computer Account For %s not found.\n", machine_name));
+               ads_msgfree(ads, res);
+               return kvno;
+       }
 
-/*
-  add a machine account to the ADS server
-*/
-static ADS_STATUS ads_add_machine_acct(ADS_STRUCT *ads, const char *hostname, 
-                                      const char *org_unit)
+       dn_string = ads_get_dn(ads, res);
+       if (!dn_string) {
+               DEBUG(0,("ads_get_kvno: out of memory.\n"));
+               ads_msgfree(ads, res);
+               return kvno;
+       }
+       DEBUG(5,("ads_get_kvno: Using: %s\n", dn_string));
+       ads_memfree(ads, dn_string);
+
+       /* ---------------------------------------------------------
+        * 0 is returned as a default KVNO from this point on...
+        * This is done because Windows 2000 does not support key
+        * version numbers.  Chances are that a failure in the next
+        * step is simply due to Windows 2000 being used for a
+        * domain controller. */
+       kvno = 0;
+
+       if (!ads_pull_uint32(ads, res, "msDS-KeyVersionNumber", &kvno)) {
+               DEBUG(3,("ads_get_kvno: Error Determining KVNO!\n"));
+               DEBUG(3,("ads_get_kvno: Windows 2000 does not support KVNO's, so this may be normal.\n"));
+               ads_msgfree(ads, res);
+               return kvno;
+       }
+
+       /* Success */
+       DEBUG(5,("ads_get_kvno: Looked Up KVNO of: %d\n", kvno));
+       ads_msgfree(ads, res);
+       return kvno;
+}
+
+/**
+ * This clears out all registered spn's for a given hostname
+ * @param ads An initilaized ADS_STRUCT
+ * @param machine_name the NetBIOS name of the computer.
+ * @return 0 upon success, non-zero otherwise.
+ **/
+
+ADS_STATUS ads_clear_service_principal_names(ADS_STRUCT *ads, const char *machine_name)
+{
+       TALLOC_CTX *ctx;
+       LDAPMessage *res = NULL;
+       ADS_MODLIST mods;
+       const char *servicePrincipalName[1] = {NULL};
+       ADS_STATUS ret = ADS_ERROR(LDAP_SUCCESS);
+       char *dn_string = NULL;
+
+       ret = ads_find_machine_acct(ads, (void **)&res, machine_name);
+       if (!ADS_ERR_OK(ret) || ads_count_replies(ads, res) != 1) {
+               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);
+       }
+
+       DEBUG(5,("ads_clear_service_principal_names: Host account for %s found\n", machine_name));
+       ctx = talloc_init("ads_clear_service_principal_names");
+       if (!ctx) {
+               ads_msgfree(ads, res);
+               return ADS_ERROR(LDAP_NO_MEMORY);
+       }
+
+       if (!(mods = ads_init_mods(ctx))) {
+               talloc_destroy(ctx);
+               ads_msgfree(ads, res);
+               return ADS_ERROR(LDAP_NO_MEMORY);
+       }
+       ret = ads_mod_strlist(ctx, &mods, "servicePrincipalName", servicePrincipalName);
+       if (!ADS_ERR_OK(ret)) {
+               DEBUG(1,("ads_clear_service_principal_names: Error creating strlist.\n"));
+               ads_msgfree(ads, res);
+               talloc_destroy(ctx);
+               return ret;
+       }
+       dn_string = ads_get_dn(ads, res);
+       if (!dn_string) {
+               talloc_destroy(ctx);
+               ads_msgfree(ads, res);
+               return ADS_ERROR(LDAP_NO_MEMORY);
+       }
+       ret = ads_gen_mod(ads, dn_string, mods);
+       ads_memfree(ads,dn_string);
+       if (!ADS_ERR_OK(ret)) {
+               DEBUG(1,("ads_clear_service_principal_names: Error: Updating Service Principals for machine %s in LDAP\n",
+                       machine_name));
+               ads_msgfree(ads, res);
+               talloc_destroy(ctx);
+               return ret;
+       }
+
+       ads_msgfree(ads, res);
+       talloc_destroy(ctx);
+       return ret;
+}
+
+/**
+ * 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 spn A string of the service principal to add, i.e. 'host'
+ * @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 *spn)
 {
        ADS_STATUS ret;
+       TALLOC_CTX *ctx;
+       LDAPMessage *res = NULL;
+       char *host_spn, *psp1, *psp2, *psp3;
+       ADS_MODLIST mods;
+       fstring my_fqdn;
+       char *dn_string = NULL;
+       const char *servicePrincipalName[4] = {NULL, NULL, NULL, NULL};
+
+       ret = ads_find_machine_acct(ads, (void **)&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));
+               ads_msgfree(ads, res);
+               return ADS_ERROR(LDAP_NO_SUCH_OBJECT);
+       }
+
+       DEBUG(1,("ads_add_service_principal_name: Host account for %s found\n", machine_name));
+       if (!(ctx = talloc_init("ads_add_service_principal_name"))) {
+               ads_msgfree(ads, res);
+               return ADS_ERROR(LDAP_NO_MEMORY);
+       }
+
+       name_to_fqdn(my_fqdn, machine_name);
+       strlower_m(my_fqdn);
+
+       if (!(host_spn = talloc_asprintf(ctx, "HOST/%s", my_fqdn))) {
+               talloc_destroy(ctx);
+               ads_msgfree(ads, res);
+               return ADS_ERROR(LDAP_NO_SUCH_OBJECT);
+       }
+
+       /* Add the extra principal */
+       psp1 = talloc_asprintf(ctx, "%s/%s", spn, machine_name);
+       strupper_m(psp1);
+       strlower_m(&psp1[strlen(spn)]);
+       DEBUG(5,("ads_add_service_principal_name: INFO: Adding %s to host %s\n", psp1, machine_name));
+       servicePrincipalName[0] = psp1;
+       psp2 = talloc_asprintf(ctx, "%s/%s.%s", spn, machine_name, ads->config.realm);
+       strupper_m(psp2);
+       strlower_m(&psp2[strlen(spn)]);
+       DEBUG(5,("ads_add_service_principal_name: INFO: Adding %s to host %s\n", psp2, machine_name));
+       servicePrincipalName[1] = psp2;
+
+       /* Add another principal in case the realm != the DNS domain, so that
+        * the KDC doesn't send "server principal unknown" errors to clients
+        * which use the DNS name in determining service principal names. */
+       psp3 = talloc_asprintf(ctx, "%s/%s", spn, my_fqdn);
+       strupper_m(psp3);
+       strlower_m(&psp3[strlen(spn)]);
+       if (strcmp(psp2, psp3) != 0) {
+               DEBUG(5,("ads_add_service_principal_name: INFO: Adding %s to host %s\n", psp3, machine_name));
+               servicePrincipalName[2] = psp3;
+       }
+
+       if (!(mods = ads_init_mods(ctx))) {
+               talloc_destroy(ctx);
+               ads_msgfree(ads, res);
+               return ADS_ERROR(LDAP_NO_MEMORY);
+       }
+       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"));
+               talloc_destroy(ctx);
+               ads_msgfree(ads, res);
+               return ret;
+       }
+       dn_string = ads_get_dn(ads, res);
+       if (!dn_string) {
+               talloc_destroy(ctx);
+               ads_msgfree(ads, res);
+               return ADS_ERROR(LDAP_NO_MEMORY);
+       }
+       ret = ads_gen_mod(ads, dn_string, mods);
+       ads_memfree(ads,dn_string);
+       if (!ADS_ERR_OK(ret)) {
+               DEBUG(1,("ads_add_service_principal_name: Error: Updating Service Principals in LDAP\n"));
+               talloc_destroy(ctx);
+               ads_msgfree(ads, res);
+               return ret;
+       }
+
+       talloc_destroy(ctx);
+       ads_msgfree(ads, res);
+       return ret;
+}
+
+/**
+ * adds a machine account to the ADS server
+ * @param ads An intialized 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
+ * @return 0 upon success, or non-zero otherwise
+**/
+
+static ADS_STATUS ads_add_machine_acct(ADS_STRUCT *ads, const char *machine_name, 
+                                      uint32 account_type,
+                                      const char *org_unit)
+{
+       ADS_STATUS ret, status;
        char *host_spn, *host_upn, *new_dn, *samAccountName, *controlstr;
-       char *ou_str;
        TALLOC_CTX *ctx;
        ADS_MODLIST mods;
        const char *objectClass[] = {"top", "person", "organizationalPerson",
                                     "user", "computer", NULL};
-       const char *servicePrincipalName[5] = {NULL, NULL, NULL, NULL, NULL};
-       char *psp, *psp2;
+       const char *servicePrincipalName[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
+       char *psp, *psp2, *psp3, *psp4;
        unsigned acct_control;
+       unsigned exists=0;
+       fstring my_fqdn;
+       LDAPMessage *res = NULL;
+       int i, next_spn;
 
-       if (!(ctx = talloc_init("machine_account")))
+       if (!(ctx = talloc_init("ads_add_machine_acct")))
                return ADS_ERROR(LDAP_NO_MEMORY);
 
        ret = ADS_ERROR(LDAP_NO_MEMORY);
 
-       if (!(host_spn = talloc_asprintf(ctx, "HOST/%s", hostname)))
+       name_to_fqdn(my_fqdn, machine_name);
+
+       status = ads_find_machine_acct(ads, (void **)&res, machine_name);
+       if (ADS_ERR_OK(status) && ads_count_replies(ads, res) == 1) {
+               char *dn_string = ads_get_dn(ads, res);
+               if (!dn_string) {
+                       DEBUG(1, ("ads_add_machine_acct: ads_get_dn returned NULL (malloc failure?)\n"));
+                       goto done;
+               }
+               new_dn = talloc_strdup(ctx, dn_string);
+               ads_memfree(ads,dn_string);
+               DEBUG(0, ("ads_add_machine_acct: Host account for %s already exists - modifying old account\n",
+                       machine_name));
+               exists=1;
+       } else {
+               char *ou_str = ads_ou_string(ads,org_unit);
+               if (!ou_str) {
+                       DEBUG(1, ("ads_add_machine_acct: ads_ou_string returned NULL (malloc failure?)\n"));
+                       goto done;
+               }
+               new_dn = talloc_asprintf(ctx, "cn=%s,%s,%s", machine_name, ou_str, 
+                               ads->config.bind_path);
+
+               SAFE_FREE(ou_str);
+       }
+
+       if (!new_dn) {
                goto done;
-       if (!(host_upn = talloc_asprintf(ctx, "%s@%s", host_spn, ads->config.realm)))
+       }
+
+       if (!(host_spn = talloc_asprintf(ctx, "HOST/%s", machine_name)))
                goto done;
-       ou_str = ads_ou_string(org_unit);
-       if (!ou_str) {
-               DEBUG(1, ("ads_ou_string returned NULL (malloc failure?)\n"));
+       if (!(host_upn = talloc_asprintf(ctx, "%s@%s", host_spn, ads->config.realm)))
                goto done;
-       }
-       new_dn = talloc_asprintf(ctx, "cn=%s,%s,%s", hostname, ou_str, 
-                                ads->config.bind_path);
-       servicePrincipalName[0] = talloc_asprintf(ctx, "HOST/%s", hostname);
+       servicePrincipalName[0] = talloc_asprintf(ctx, "HOST/%s", machine_name);
        psp = talloc_asprintf(ctx, "HOST/%s.%s", 
-                             hostname, 
-                             ads->config.realm);
-       strlower(&psp[5]);
+                               machine_name, 
+                               ads->config.realm);
+       strlower_m(&psp[5]);
        servicePrincipalName[1] = psp;
-       servicePrincipalName[2] = talloc_asprintf(ctx, "CIFS/%s", hostname);
+       servicePrincipalName[2] = talloc_asprintf(ctx, "CIFS/%s", machine_name);
        psp2 = talloc_asprintf(ctx, "CIFS/%s.%s", 
-                              hostname, 
+                              machine_name, 
                               ads->config.realm);
-       strlower(&psp2[5]);
+       strlower_m(&psp2[5]);
        servicePrincipalName[3] = psp2;
 
-       free(ou_str);
-       if (!new_dn)
-               goto done;
+       /* Ensure servicePrincipalName[4] and [5] are unique. */
+       strlower_m(my_fqdn);
+       psp3 = talloc_asprintf(ctx, "CIFS/%s", my_fqdn);
+       strlower_m(&psp3[5]);
+
+       next_spn = 4;
+       for (i = 0; i < next_spn; i++) {
+               if (strequal(servicePrincipalName[i], psp3))
+                       break;
+       }
+       if (i == next_spn) {
+               servicePrincipalName[next_spn++] = psp3;
+       }
+
+       psp4 = talloc_asprintf(ctx, "HOST/%s", my_fqdn);
+       strlower_m(&psp4[5]);
+       for (i = 0; i < next_spn; i++) {
+               if (strequal(servicePrincipalName[i], psp4))
+                       break;
+       }
+       if (i == next_spn) {
+               servicePrincipalName[next_spn++] = psp4;
+       }
 
-       if (!(samAccountName = talloc_asprintf(ctx, "%s$", hostname)))
+       if (!(samAccountName = talloc_asprintf(ctx, "%s$", machine_name))) {
                goto done;
+       }
 
-       acct_control = UF_WORKSTATION_TRUST_ACCOUNT | UF_DONT_EXPIRE_PASSWD;
+       acct_control = account_type | UF_DONT_EXPIRE_PASSWD;
 #ifndef ENCTYPE_ARCFOUR_HMAC
        acct_control |= UF_USE_DES_KEY_ONLY;
 #endif
-       if (!(controlstr = talloc_asprintf(ctx, "%u", acct_control)))
+
+       if (!(controlstr = talloc_asprintf(ctx, "%u", acct_control))) {
                goto done;
+       }
 
-       if (!(mods = ads_init_mods(ctx)))
+       if (!(mods = ads_init_mods(ctx))) {
                goto done;
-       
-       ads_mod_str(ctx, &mods, "cn", hostname);
-       ads_mod_str(ctx, &mods, "sAMAccountName", samAccountName);
-       ads_mod_strlist(ctx, &mods, "objectClass", objectClass);
+       }
+
+       if (!exists) {
+               ads_mod_str(ctx, &mods, "cn", machine_name);
+               ads_mod_str(ctx, &mods, "sAMAccountName", samAccountName);
+               ads_mod_str(ctx, &mods, "userAccountControl", controlstr);
+               ads_mod_strlist(ctx, &mods, "objectClass", objectClass);
+       }
+       ads_mod_str(ctx, &mods, "dNSHostName", my_fqdn);
        ads_mod_str(ctx, &mods, "userPrincipalName", host_upn);
        ads_mod_strlist(ctx, &mods, "servicePrincipalName", servicePrincipalName);
-       ads_mod_str(ctx, &mods, "dNSHostName", hostname);
-       ads_mod_str(ctx, &mods, "userAccountControl", controlstr);
        ads_mod_str(ctx, &mods, "operatingSystem", "Samba");
-       ads_mod_str(ctx, &mods, "operatingSystemVersion", VERSION);
+       ads_mod_str(ctx, &mods, "operatingSystemVersion", SAMBA_VERSION_STRING);
+
+       if (!exists)  {
+               ret = ads_gen_add(ads, new_dn, mods);
+       } else {
+               ret = ads_gen_mod(ads, new_dn, mods);
+       }
 
-       ads_gen_add(ads, new_dn, mods);
-       ret = ads_set_machine_sd(ads, hostname, new_dn);
+       if (!ADS_ERR_OK(ret)) {
+               goto done;
+       }
 
+       /* Do not fail if we can't set security descriptor
+        * it shouldn't be mandatory and probably we just 
+        * don't have enough rights to do it.
+        */
+       if (!exists) {
+               status = ads_set_machine_sd(ads, machine_name, new_dn);
+       
+               if (!ADS_ERR_OK(status)) {
+                       DEBUG(0, ("Warning: ads_set_machine_sd: %s\n",
+                                       ads_errstr(status)));
+               }
+       }
 done:
+       ads_msgfree(ads, res);
        talloc_destroy(ctx);
        return ret;
 }
@@ -1112,20 +1528,14 @@ static void dump_binary(const char *field, struct berval **values)
        }
 }
 
-struct uuid {
-        uint32   i1;
-        uint16   i2;
-        uint16   i3;
-        uint8    s[8];
-};
-
 static void dump_guid(const char *field, struct berval **values)
 {
        int i;
-       GUID guid;
+       UUID_FLAT guid;
        for (i=0; values[i]; i++) {
                memcpy(guid.info, values[i]->bv_val, sizeof(guid.info));
-               printf("%s: %s\n", field, uuid_string_static(guid));
+               printf("%s: %s\n", field, 
+                      smb_uuid_string_static(smb_uuid_unpack_static(guid)));
        }
 }
 
@@ -1199,6 +1609,7 @@ static BOOL ads_dump_field(char *field, void **values, void *data_area)
                {"nTSecurityDescriptor", False, dump_sd},
                {"dnsRecord", False, dump_binary},
                {"objectSid", False, dump_sid},
+               {"tokenGroups", False, dump_sid},
                {NULL, True, NULL}
        };
        int i;
@@ -1314,44 +1725,50 @@ int ads_count_replies(ADS_STRUCT *ads, void *res)
  * Join a machine to a realm
  *  Creates the machine account and sets the machine password
  * @param ads connection to ads server
- * @param hostname name of host to add
+ * @param machine name of host to add
  * @param org_unit Organizational unit to place machine in
  * @return status of join
  **/
-ADS_STATUS ads_join_realm(ADS_STRUCT *ads, const char *hostname, const char *org_unit)
+ADS_STATUS ads_join_realm(ADS_STRUCT *ads, const char *machine_name, 
+                         uint32 account_type, const char *org_unit)
 {
        ADS_STATUS status;
-       LDAPMessage *res;
-       char *host;
+       LDAPMessage *res = NULL;
+       char *machine;
 
-       /* hostname must be lowercase */
-       host = strdup(hostname);
-       strlower(host);
+       /* machine name must be lowercase */
+       machine = SMB_STRDUP(machine_name);
+       strlower_m(machine);
 
-       status = ads_find_machine_acct(ads, (void **)&res, host);
+       /*
+       status = ads_find_machine_acct(ads, (void **)&res, machine);
        if (ADS_ERR_OK(status) && ads_count_replies(ads, res) == 1) {
-               DEBUG(0, ("Host account for %s already exists - deleting old account\n", host));
-               status = ads_leave_realm(ads, host);
+               DEBUG(0, ("Host account for %s already exists - deleting old account\n", machine));
+               status = ads_leave_realm(ads, machine);
                if (!ADS_ERR_OK(status)) {
                        DEBUG(0, ("Failed to delete host '%s' from the '%s' realm.\n", 
-                                 host, ads->config.realm));
+                                 machine, ads->config.realm));
                        return status;
                }
        }
+       */
 
-       status = ads_add_machine_acct(ads, host, org_unit);
+       status = ads_add_machine_acct(ads, machine, account_type, org_unit);
        if (!ADS_ERR_OK(status)) {
-               DEBUG(0, ("ads_add_machine_acct: %s\n", ads_errstr(status)));
+               DEBUG(0, ("ads_join_realm: ads_add_machine_acct failed (%s): %s\n", machine, ads_errstr(status)));
+               SAFE_FREE(machine);
                return status;
        }
 
-       status = ads_find_machine_acct(ads, (void **)&res, host);
+       status = ads_find_machine_acct(ads, (void **)&res, machine);
        if (!ADS_ERR_OK(status)) {
-               DEBUG(0, ("Host account test failed\n"));
+               DEBUG(0, ("ads_join_realm: Host account test failed for machine %s\n", machine));
+               SAFE_FREE(machine);
                return status;
        }
 
-       free(host);
+       SAFE_FREE(machine);
+       ads_msgfree(ads, res);
 
        return status;
 }
@@ -1365,13 +1782,13 @@ ADS_STATUS ads_join_realm(ADS_STRUCT *ads, const char *hostname, const char *org
 ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
 {
        ADS_STATUS status;
-       void *res;
+       void *res, *msg;
        char *hostnameDN, *host; 
        int rc;
 
        /* hostname must be lowercase */
-       host = strdup(hostname);
-       strlower(host);
+       host = SMB_STRDUP(hostname);
+       strlower_m(host);
 
        status = ads_find_machine_acct(ads, &res, host);
        if (!ADS_ERR_OK(status)) {
@@ -1379,7 +1796,12 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
            return status;
        }
 
-       hostnameDN = ads_get_dn(ads, (LDAPMessage *)res);
+       msg = ads_first_entry(ads, res);
+       if (!msg) {
+               return ADS_ERROR_SYSTEM(ENOENT);
+       }
+
+       hostnameDN = ads_get_dn(ads, (LDAPMessage *)msg);
        rc = ldap_delete_s(ads->ld, hostnameDN);
        ads_memfree(ads, hostnameDN);
        if (rc != LDAP_SUCCESS) {
@@ -1406,8 +1828,8 @@ ADS_STATUS ads_leave_realm(ADS_STRUCT *ads, const char *hostname)
  **/
 ADS_STATUS ads_set_machine_sd(ADS_STRUCT *ads, const char *hostname, char *dn)
 {
-       const char     *attrs[] = {"ntSecurityDescriptor", "objectSid", 0};
-       char           *exp     = 0;
+       const char     *attrs[] = {"nTSecurityDescriptor", "objectSid", 0};
+       char           *expr     = 0;
        size_t          sd_size = 0;
        struct berval   bval = {0, NULL};
        prs_struct      ps_wire;
@@ -1420,8 +1842,12 @@ ADS_STATUS ads_set_machine_sd(ADS_STRUCT *ads, const char *hostname, char *dn)
        NTSTATUS    status;
        ADS_STATUS  ret;
        DOM_SID     sid;
-       SEC_DESC   *psd = 0;
-       TALLOC_CTX *ctx = 0;    
+       SEC_DESC   *psd = NULL;
+       TALLOC_CTX *ctx = NULL; 
+
+       /* Avoid segmentation fault in prs_mem_free if
+        * we have to bail out before prs_init */
+       ps_wire.is_dynamic = False;
 
        if (!ads) return ADS_ERROR(LDAP_SERVER_DOWN);
 
@@ -1431,7 +1857,7 @@ ADS_STATUS ads_set_machine_sd(ADS_STRUCT *ads, const char *hostname, char *dn)
                return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
        }
 
-       if (asprintf(&exp, "(samAccountName=%s$)", escaped_hostname) == -1) {
+       if (asprintf(&expr, "(samAccountName=%s$)", escaped_hostname) == -1) {
                DEBUG(1, ("ads_set_machine_sd: asprintf failed!\n"));
                SAFE_FREE(escaped_hostname);
                return ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
@@ -1439,7 +1865,7 @@ ADS_STATUS ads_set_machine_sd(ADS_STRUCT *ads, const char *hostname, char *dn)
 
        SAFE_FREE(escaped_hostname);
 
-       ret = ads_search(ads, (void *) &res, exp, attrs);
+       ret = ads_search(ads, (void *) &res, expr, attrs);
 
        if (!ADS_ERR_OK(ret)) return ret;
 
@@ -1448,7 +1874,11 @@ ADS_STATUS ads_set_machine_sd(ADS_STRUCT *ads, const char *hostname, char *dn)
                goto ads_set_sd_error;
        }
 
-       ads_pull_sid(ads, msg, attrs[1], &sid); 
+       if (!ads_pull_sid(ads, msg, attrs[1], &sid)) {
+               ret = ADS_ERROR_NT(NT_STATUS_INVALID_PARAMETER);
+               goto ads_set_sd_error;
+       }
+
        if (!(ctx = talloc_init("sec_io_desc"))) {
                ret =  ADS_ERROR(LDAP_NO_MEMORY);
                goto ads_set_sd_error;
@@ -1466,7 +1896,10 @@ ADS_STATUS ads_set_machine_sd(ADS_STRUCT *ads, const char *hostname, char *dn)
                goto ads_set_sd_error;
        }
 
-       prs_init(&ps_wire, sd_size, ctx, MARSHALL);
+       if (!prs_init(&ps_wire, sd_size, ctx, MARSHALL)) {
+               ret = ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
+       }
+
        if (!sec_io_desc("sd_wire", &psd, &ps_wire, 1)) {
                ret = ADS_ERROR(LDAP_NO_MEMORY);
                goto ads_set_sd_error;
@@ -1477,16 +1910,24 @@ ADS_STATUS ads_set_machine_sd(ADS_STRUCT *ads, const char *hostname, char *dn)
 #endif
        if (!(mods = ads_init_mods(ctx))) return ADS_ERROR(LDAP_NO_MEMORY);
 
-       bval.bv_len = sd_size;
-       bval.bv_val = talloc(ctx, sd_size);
+       bval.bv_len = prs_offset(&ps_wire);
+       bval.bv_val = TALLOC(ctx, bval.bv_len);
        if (!bval.bv_val) {
                ret = ADS_ERROR(LDAP_NO_MEMORY);
                goto ads_set_sd_error;
        }
-       prs_copy_all_data_out((char *)&bval.bv_val, &ps_wire);
 
-       ads_mod_ber(ctx, &mods, attrs[0], &bval);
-       ret = ads_gen_mod(ads, dn, mods);
+       prs_set_offset(&ps_wire, 0);
+
+       if (!prs_copy_data_out(bval.bv_val, &ps_wire, bval.bv_len)) {
+               ret = ADS_ERROR(LDAP_NO_MEMORY);
+               goto ads_set_sd_error;          
+       }
+
+       ret = ads_mod_ber(ctx, &mods, attrs[0], &bval);
+       if (ADS_ERR_OK(ret)) {
+               ret = ads_gen_mod(ads, dn, mods);
+       }
 
 ads_set_sd_error:
        ads_msgfree(ads, res);
@@ -1531,7 +1972,7 @@ char *ads_pull_string(ADS_STRUCT *ads,
        char **values;
        char *ret = NULL;
        char *ux_string;
-       int rc;
+       size_t rc;
 
        values = ldap_get_values(ads->ld, msg, field);
        if (!values)
@@ -1540,7 +1981,7 @@ char *ads_pull_string(ADS_STRUCT *ads,
        if (values[0]) {
                rc = pull_utf8_talloc(mem_ctx, &ux_string, 
                                      values[0]);
-               if (rc != -1)
+               if (rc != (size_t)-1)
                        ret = ux_string;
                
        }
@@ -1557,27 +1998,26 @@ char *ads_pull_string(ADS_STRUCT *ads,
  * @return Result strings in talloc context
  **/
 char **ads_pull_strings(ADS_STRUCT *ads, 
-                      TALLOC_CTX *mem_ctx, void *msg, const char *field)
+                       TALLOC_CTX *mem_ctx, void *msg, const char *field,
+                       size_t *num_values)
 {
        char **values;
        char **ret = NULL;
-       int i, n;
+       int i;
 
        values = ldap_get_values(ads->ld, msg, field);
        if (!values)
                return NULL;
 
-       for (i=0;values[i];i++)
-               /* noop */ ;
-       n = i;
+       *num_values = ldap_count_values(values);
 
-       ret = talloc(mem_ctx, sizeof(char *) * (n+1));
+       ret = TALLOC_ARRAY(mem_ctx, char *, *num_values + 1);
        if (!ret) {
                ldap_value_free(values);
                return NULL;
        }
 
-       for (i=0;i<n;i++) {
+       for (i=0;i<*num_values;i++) {
                if (pull_utf8_talloc(mem_ctx, &ret[i], values[i]) == -1) {
                        ldap_value_free(values);
                        return NULL;
@@ -1589,6 +2029,131 @@ char **ads_pull_strings(ADS_STRUCT *ads,
        return ret;
 }
 
+/**
+ * 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
+ * @param msg Results of search
+ * @param field Attribute to retrieve
+ * @param current_strings strings returned by a previous call to this function
+ * @param next_attribute The next query should ask for this attribute
+ * @param num_values How many values did we get this time?
+ * @param more_values Are there more values to get?
+ * @return Result strings in talloc context
+ **/
+char **ads_pull_strings_range(ADS_STRUCT *ads, 
+                             TALLOC_CTX *mem_ctx,
+                             void *msg, const char *field,
+                             char **current_strings,
+                             const char **next_attribute,
+                             size_t *num_strings,
+                             BOOL *more_strings)
+{
+       char *attr;
+       char *expected_range_attrib, *range_attr;
+       BerElement *ptr = NULL;
+       char **strings;
+       char **new_strings;
+       size_t num_new_strings;
+       unsigned long int range_start;
+       unsigned long int range_end;
+       
+       /* we might have been given the whole lot anyway */
+       if ((strings = ads_pull_strings(ads, mem_ctx, msg, field, num_strings))) {
+               *more_strings = False;
+               return strings;
+       }
+
+       expected_range_attrib = talloc_asprintf(mem_ctx, "%s;Range=", field);
+
+       /* look for Range result */
+       for (attr = ldap_first_attribute(ads->ld, (LDAPMessage *)msg, &ptr); 
+            attr; 
+            attr = ldap_next_attribute(ads->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))) {
+                       range_attr = attr;
+                       break;
+               }
+               ldap_memfree(attr);
+       }
+       if (!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", 
+                  &range_start, &range_end) == 2) {
+               *more_strings = True;
+       } else {
+               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", 
+                                 range_attr));
+                       ldap_memfree(range_attr);
+                       *more_strings = False;
+                       return NULL;
+               }
+       }
+
+       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",
+                         range_attr, *num_strings + 1, range_start));
+               ldap_memfree(range_attr);
+               *more_strings = False;
+               return NULL;
+       }
+
+       new_strings = ads_pull_strings(ads, mem_ctx, msg, range_attr, &num_new_strings);
+       
+       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, 
+                         (unsigned long int)num_new_strings));
+               ldap_memfree(range_attr);
+               *more_strings = False;
+               return NULL;
+       }
+
+       strings = TALLOC_REALLOC_ARRAY(mem_ctx, current_strings, char *,
+                                *num_strings + num_new_strings);
+       
+       if (strings == NULL) {
+               ldap_memfree(range_attr);
+               *more_strings = False;
+               return NULL;
+       }
+       
+       memcpy(&strings[*num_strings], new_strings,
+              sizeof(*new_strings) * num_new_strings);
+
+       (*num_strings) += num_new_strings;
+
+       if (*more_strings) {
+               *next_attribute = talloc_asprintf(mem_ctx,
+                                                 "%s;range=%d-*", 
+                                                 field,
+                                                 *num_strings);
+               
+               if (!*next_attribute) {
+                       DEBUG(1, ("talloc_asprintf for next attribute failed!\n"));
+                       ldap_memfree(range_attr);
+                       *more_strings = False;
+                       return NULL;
+               }
+       }
+
+       ldap_memfree(range_attr);
+
+       return strings;
+}
 
 /**
  * pull a single uint32 from a ADS result
@@ -1624,16 +2189,18 @@ BOOL ads_pull_uint32(ADS_STRUCT *ads,
  * @return boolean indicating success
  **/
 BOOL ads_pull_guid(ADS_STRUCT *ads,
-                  void *msg, GUID *guid)
+                  void *msg, struct uuid *guid)
 {
        char **values;
+       UUID_FLAT flat_guid;
 
        values = ldap_get_values(ads->ld, msg, "objectGUID");
        if (!values)
                return False;
        
        if (values[0]) {
-               memcpy(guid, values[0], sizeof(GUID));
+               memcpy(&flat_guid.info, values[0], sizeof(UUID_FLAT));
+               smb_uuid_unpack(flat_guid, guid);
                ldap_value_free(values);
                return True;
        }
@@ -1693,7 +2260,7 @@ int ads_pull_sids(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
        for (i=0; values[i]; i++)
                /* nop */ ;
 
-       (*sids) = talloc(mem_ctx, sizeof(DOM_SID) * i);
+       (*sids) = TALLOC_ARRAY(mem_ctx, DOM_SID, i);
        if (!(*sids)) {
                ldap_value_free_len(values);
                return 0;
@@ -1702,8 +2269,11 @@ int ads_pull_sids(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
        count = 0;
        for (i=0; values[i]; i++) {
                ret = sid_parse(values[i]->bv_val, values[i]->bv_len, &(*sids)[count]);
-               if (ret)
+               if (ret) {
+                       fstring sid;
+                       DEBUG(10, ("pulling SID: %s\n", sid_to_string(sid, &(*sids)[count])));
                        count++;
+               }
        }
        
        ldap_value_free_len(values);
@@ -1754,13 +2324,19 @@ BOOL ads_pull_sd(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx,
  */
 char *ads_pull_username(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, void *msg)
 {
+#if 0  /* JERRY */
        char *ret, *p;
 
+       /* lookup_name() only works on the sAMAccountName to 
+          returning the username portion of userPrincipalName
+          breaks winbindd_getpwnam() */
+
        ret = ads_pull_string(ads, mem_ctx, msg, "userPrincipalName");
-       if (ret && (p = strchr(ret, '@'))) {
+       if (ret && (p = strchr_m(ret, '@'))) {
                *p = 0;
                return ret;
        }
+#endif
        return ads_pull_string(ads, mem_ctx, msg, "sAMAccountName");
 }
 
@@ -1778,8 +2354,9 @@ ADS_STATUS ads_USN(ADS_STRUCT *ads, uint32 *usn)
        ADS_STATUS status;
        void *res;
 
-       status = ads_do_search(ads, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
-       if (!ADS_ERR_OK(status)) return status;
+       status = ads_do_search_retry(ads, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
+       if (!ADS_ERR_OK(status)) 
+               return status;
 
        if (ads_count_replies(ads, res) != 1) {
                return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
@@ -1833,34 +2410,43 @@ ADS_STATUS ads_server_info(ADS_STRUCT *ads)
        }
 
        status = ads_do_search(ads, "", LDAP_SCOPE_BASE, "(objectclass=*)", attrs, &res);
-       if (!ADS_ERR_OK(status)) return status;
+       if (!ADS_ERR_OK(status)) {
+               talloc_destroy(ctx);
+               return status;
+       }
 
        value = ads_pull_string(ads, ctx, res, "ldapServiceName");
        if (!value) {
+               ads_msgfree(ads, res);
+               talloc_destroy(ctx);
                return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
        }
 
        timestr = ads_pull_string(ads, ctx, res, "currentTime");
        if (!timestr) {
+               ads_msgfree(ads, res);
+               talloc_destroy(ctx);
                return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
        }
 
-       ldap_msgfree(res);
+       ads_msgfree(ads, res);
 
        p = strchr(value, ':');
        if (!p) {
                talloc_destroy(ctx);
-               DEBUG(1, ("ads_server_info: returned ldap server name did not contain a ':' so was deemed invalid\n"));
+               DEBUG(1, ("ads_server_info: returned ldap server name did not contain a ':' "
+                         "so was deemed invalid\n"));
                return ADS_ERROR(LDAP_DECODING_ERROR);
        }
 
        SAFE_FREE(ads->config.ldap_server_name);
 
-       ads->config.ldap_server_name = strdup(p+1);
+       ads->config.ldap_server_name = SMB_STRDUP(p+1);
        p = strchr(ads->config.ldap_server_name, '$');
        if (!p || p[1] != '@') {
                talloc_destroy(ctx);
-               DEBUG(1, ("ads_server_info: returned ldap server name (%s) does not contain '$@' so was deemed invalid\n", ads->config.ldap_server_name));
+               DEBUG(1, ("ads_server_info: returned ldap server name (%s) does not contain '$@'"
+                         " so was deemed invalid\n", ads->config.ldap_server_name));
                SAFE_FREE(ads->config.ldap_server_name);
                return ADS_ERROR(LDAP_DECODING_ERROR);
        }
@@ -1870,7 +2456,7 @@ ADS_STATUS ads_server_info(ADS_STRUCT *ads)
        SAFE_FREE(ads->config.realm);
        SAFE_FREE(ads->config.bind_path);
 
-       ads->config.realm = strdup(p+2);
+       ads->config.realm = SMB_STRDUP(p+2);
        ads->config.bind_path = ads_build_dn(ads->config.realm);
 
        DEBUG(3,("got ldap server name %s@%s, using bind path: %s\n", 
@@ -1889,77 +2475,6 @@ ADS_STATUS ads_server_info(ADS_STRUCT *ads)
        return ADS_SUCCESS;
 }
 
-
-/**
- * find the list of trusted domains
- * @param ads connection to ads server
- * @param mem_ctx TALLOC_CTX for allocating results
- * @param num_trusts pointer to number of trusts
- * @param names pointer to trusted domain name list
- * @param sids pointer to list of sids of trusted domains
- * @return the count of SIDs pulled
- **/
-ADS_STATUS ads_trusted_domains(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, 
-                              int *num_trusts, 
-                              char ***names, 
-                              char ***alt_names,
-                              DOM_SID **sids)
-{
-       const char *attrs[] = {"name", "flatname", "securityIdentifier", 
-                              "trustDirection", NULL};
-       ADS_STATUS status;
-       void *res, *msg;
-       int count, i;
-
-       *num_trusts = 0;
-
-       status = ads_search(ads, &res, "(objectcategory=trustedDomain)", attrs);
-       if (!ADS_ERR_OK(status)) return status;
-
-       count = ads_count_replies(ads, res);
-       if (count == 0) {
-               ads_msgfree(ads, res);
-               return ADS_ERROR(LDAP_NO_RESULTS_RETURNED);
-       }
-
-       (*names) = talloc(mem_ctx, sizeof(char *) * count);
-       (*alt_names) = talloc(mem_ctx, sizeof(char *) * count);
-       (*sids) = talloc(mem_ctx, sizeof(DOM_SID) * count);
-       if (! *names || ! *sids) return ADS_ERROR(LDAP_NO_MEMORY);
-
-       for (i=0, msg = ads_first_entry(ads, res); msg; msg = ads_next_entry(ads, msg)) {
-               uint32 direction;
-
-               /* direction is a 2 bit bitfield, 1 means they trust us 
-                  but we don't trust them, so we should not list them
-                  as users from that domain can't login */
-               if (ads_pull_uint32(ads, msg, "trustDirection", &direction) &&
-                   direction == 1) {
-                       continue;
-               }
-               
-               (*names)[i] = ads_pull_string(ads, mem_ctx, msg, "name");
-               (*alt_names)[i] = ads_pull_string(ads, mem_ctx, msg, "flatname");
-
-               if ((*alt_names)[i] && (*alt_names)[i][0]) {
-                       /* we prefer the flatname as the primary name
-                          for consistency with RPC */
-                       char *name = (*alt_names)[i];
-                       (*alt_names)[i] = (*names)[i];
-                       (*names)[i] = name;
-               }
-               if (ads_pull_sid(ads, msg, "securityIdentifier", &(*sids)[i])) {
-                       i++;
-               }
-       }
-
-       ads_msgfree(ads, res);
-
-       *num_trusts = i;
-
-       return ADS_SUCCESS;
-}
-
 /**
  * find the domain sid for our domain
  * @param ads connection to ads server
@@ -1972,10 +2487,11 @@ ADS_STATUS ads_domain_sid(ADS_STRUCT *ads, DOM_SID *sid)
        void *res;
        ADS_STATUS rc;
 
-       rc = ads_do_search(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)) {
+               ads_msgfree(ads, res);
                return ADS_ERROR_SYSTEM(ENOENT);
        }
        ads_msgfree(ads, res);
@@ -1995,9 +2511,9 @@ bin/net -Uadministrator%XXXXX ads search '(&(objectclass=crossref)(dnsroot=VNET3
 but you need to force the bind path to match the configurationNamingContext from the rootDSE
 
 */
-ADS_STATUS ads_workgroup_name(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, char **workgroup)
+ADS_STATUS ads_workgroup_name(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, const char **workgroup)
 {
-       char *exp;
+       char *expr;
        ADS_STATUS rc;
        char **principles;
        char *prefix;
@@ -2005,19 +2521,25 @@ ADS_STATUS ads_workgroup_name(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, char **workg
        int i;
        void *res;
        const char *attrs[] = {"servicePrincipalName", NULL};
+       size_t num_principals;
 
        (*workgroup) = NULL;
 
-       asprintf(&exp, "(&(objectclass=computer)(dnshostname=%s.%s))", 
+       asprintf(&expr, "(&(objectclass=computer)(dnshostname=%s.%s))", 
                 ads->config.ldap_server_name, ads->config.realm);
-       rc = ads_search(ads, &res, exp, attrs);
-       free(exp);
+       if (expr == NULL) {
+               ADS_ERROR_NT(NT_STATUS_NO_MEMORY);
+       }
+
+       rc = ads_search(ads, &res, expr, attrs);
+       free(expr);
 
        if (!ADS_ERR_OK(rc)) {
                return rc;
        }
 
-       principles = ads_pull_strings(ads, mem_ctx, res, "servicePrincipalName");
+       principles = ads_pull_strings(ads, mem_ctx, res,
+                                     "servicePrincipalName", &num_principals);
 
        ads_msgfree(ads, res);
 
@@ -2032,8 +2554,8 @@ ADS_STATUS ads_workgroup_name(ADS_STRUCT *ads, TALLOC_CTX *mem_ctx, char **workg
        prefix_length = strlen(prefix);
 
        for (i=0;principles[i]; i++) {
-               if (strncasecmp(principles[i], prefix, prefix_length) == 0 &&
-                   strcasecmp(ads->config.realm, principles[i]+prefix_length) != 0 &&
+               if (strnequal(principles[i], prefix, prefix_length) &&
+                   !strequal(ads->config.realm, principles[i]+prefix_length) &&
                    !strchr(principles[i]+prefix_length, '.')) {
                        /* found an alternate (short) name for the domain. */
                        DEBUG(3,("Found alternate name '%s' for realm '%s'\n",