libcli/security Provide a common, top level libcli/security/security.h
[ira/wip.git] / source3 / winbindd / winbindd_cache.c
index 4d81ee39600e5a1a071d43d1e3186b560bf7149b..9ee8f6ab2a6add3a76c8483cc6958ba1e8fe3f8e 100644 (file)
@@ -8,23 +8,29 @@
    Copyright (C) Volker Lendecke 2005
    Copyright (C) Guenther Deschner 2005
    Copyright (C) Michael Adam    2007
-   
+
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
-   
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
-   
+
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "includes.h"
 #include "winbindd.h"
+#include "tdb_validate.h"
+#include "../libcli/auth/libcli_auth.h"
+#include "../librpc/gen_ndr/ndr_wbint.h"
+#include "ads.h"
+#include "nss_info.h"
+#include "../libcli/security/security.h"
 
 #undef DBGC_CLASS
 #define DBGC_CLASS DBGC_WINBIND
 #define WINBINDD_CACHE_VERSION_KEYSTR "WINBINDD_CACHE_VERSION"
 
 extern struct winbindd_methods reconnect_methods;
-extern bool opt_nocache;
 #ifdef HAVE_ADS
 extern struct winbindd_methods ads_methods;
 #endif
+extern struct winbindd_methods builtin_passdb_methods;
+extern struct winbindd_methods sam_passdb_methods;
 
 /*
  * JRA. KEEP THIS LIST UP TO DATE IF YOU ADD CACHE ENTRIES.
@@ -99,35 +106,6 @@ void (*smb_panic_fn)(const char *const why) = smb_panic;
 
 static struct winbind_cache *wcache;
 
-void winbindd_check_cache_size(time_t t)
-{
-       static time_t last_check_time;
-       struct stat st;
-
-       if (last_check_time == (time_t)0)
-               last_check_time = t;
-
-       if (t - last_check_time < 60 && t - last_check_time > 0)
-               return;
-
-       if (wcache == NULL || wcache->tdb == NULL) {
-               DEBUG(0, ("Unable to check size of tdb cache - cache not open !\n"));
-               return;
-       }
-
-       if (fstat(tdb_fd(wcache->tdb), &st) == -1) {
-               DEBUG(0, ("Unable to check size of tdb cache %s!\n", strerror(errno) ));
-               return;
-       }
-
-       if (st.st_size > WINBINDD_MAX_CACHE_SIZE) {
-               DEBUG(10,("flushing cache due to size (%lu) > (%lu)\n",
-                       (unsigned long)st.st_size,
-                       (unsigned long)WINBINDD_MAX_CACHE_SIZE));
-               wcache_flush_cache();
-       }
-}
-
 /* get the winbind_cache structure */
 static struct winbind_cache *get_cache(struct winbindd_domain *domain)
 {
@@ -135,6 +113,17 @@ static struct winbind_cache *get_cache(struct winbindd_domain *domain)
 
        /* We have to know what type of domain we are dealing with first. */
 
+       if (domain->internal) {
+               domain->backend = &builtin_passdb_methods;
+               domain->initialized = True;
+       }
+
+       if (strequal(domain->name, get_global_sam_name()) &&
+           dom_sid_equal(&domain->sid, get_global_sam_sid())) {
+               domain->backend = &sam_passdb_methods;
+               domain->initialized = True;
+       }
+
        if ( !domain->initialized ) {
                init_dc_connection( domain );
        }
@@ -183,7 +172,7 @@ static struct winbind_cache *get_cache(struct winbindd_domain *domain)
 
        if (ret)
                return ret;
-       
+
        ret = SMB_XMALLOC_P(struct winbind_cache);
        ZERO_STRUCTP(ret);
 
@@ -343,14 +332,18 @@ static char *centry_hash16(struct cache_entry *centry, TALLOC_CTX *mem_ctx)
 /* pull a sid from a cache entry, using the supplied
    talloc context 
 */
-static bool centry_sid(struct cache_entry *centry, TALLOC_CTX *mem_ctx, DOM_SID *sid)
+static bool centry_sid(struct cache_entry *centry, struct dom_sid *sid)
 {
        char *sid_string;
-       sid_string = centry_string(centry, mem_ctx);
-       if ((sid_string == NULL) || (!string_to_sid(sid, sid_string))) {
+       bool ret;
+
+       sid_string = centry_string(centry, talloc_tos());
+       if (sid_string == NULL) {
                return false;
        }
-       return true;
+       ret = string_to_sid(sid, sid_string);
+       TALLOC_FREE(sid_string);
+       return ret;
 }
 
 
@@ -382,32 +375,57 @@ static bool wcache_server_down(struct winbindd_domain *domain)
        return ret;
 }
 
-static NTSTATUS fetch_cache_seqnum( struct winbindd_domain *domain, time_t now )
+static bool wcache_fetch_seqnum(const char *domain_name, uint32_t *seqnum,
+                               uint32_t *last_seq_check)
 {
+       char *key;
        TDB_DATA data;
-       fstring key;
-       uint32 time_diff;
-       
-       if (!wcache->tdb) {
-               DEBUG(10,("fetch_cache_seqnum: tdb == NULL\n"));
-               return NT_STATUS_UNSUCCESSFUL;
+
+       if (wcache->tdb == NULL) {
+               DEBUG(10,("wcache_fetch_seqnum: tdb == NULL\n"));
+               return false;
        }
-               
-       fstr_sprintf( key, "SEQNUM/%s", domain->name );
-       
-       data = tdb_fetch_bystring( wcache->tdb, key );
-       if ( !data.dptr || data.dsize!=8 ) {
-               DEBUG(10,("fetch_cache_seqnum: invalid data size key [%s]\n", key ));
-               return NT_STATUS_UNSUCCESSFUL;
+
+       key = talloc_asprintf(talloc_tos(), "SEQNUM/%s", domain_name);
+       if (key == NULL) {
+               DEBUG(10, ("talloc failed\n"));
+               return false;
+       }
+
+       data = tdb_fetch_bystring(wcache->tdb, key);
+       TALLOC_FREE(key);
+
+       if (data.dptr == NULL) {
+               DEBUG(10, ("wcache_fetch_seqnum: %s not found\n",
+                          domain_name));
+               return false;
+       }
+       if (data.dsize != 8) {
+               DEBUG(10, ("wcache_fetch_seqnum: invalid data size %d\n",
+                          (int)data.dsize));
+               SAFE_FREE(data.dptr);
+               return false;
        }
-       
-       domain->sequence_number = IVAL(data.dptr, 0);
-       domain->last_seq_check  = IVAL(data.dptr, 4);
-       
+
+       *seqnum = IVAL(data.dptr, 0);
+       *last_seq_check = IVAL(data.dptr, 4);
        SAFE_FREE(data.dptr);
 
+       return true;
+}
+
+static NTSTATUS fetch_cache_seqnum( struct winbindd_domain *domain, time_t now )
+{
+       uint32 last_check, time_diff;
+
+       if (!wcache_fetch_seqnum(domain->name, &domain->sequence_number,
+                                &last_check)) {
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+       domain->last_seq_check = last_check;
+
        /* have we expired? */
-       
+
        time_diff = now - domain->last_seq_check;
        if ( time_diff > lp_winbind_cache_time() ) {
                DEBUG(10,("fetch_cache_seqnum: timeout [%s][%u @ %u]\n",
@@ -423,34 +441,47 @@ static NTSTATUS fetch_cache_seqnum( struct winbindd_domain *domain, time_t now )
        return NT_STATUS_OK;
 }
 
-static NTSTATUS store_cache_seqnum( struct winbindd_domain *domain )
+bool wcache_store_seqnum(const char *domain_name, uint32_t seqnum,
+                        time_t last_seq_check)
 {
-       TDB_DATA data;
-       fstring key_str;
-       uint8 buf[8];
-       
-       if (!wcache->tdb) {
-               DEBUG(10,("store_cache_seqnum: tdb == NULL\n"));
-               return NT_STATUS_UNSUCCESSFUL;
+       char *key_str;
+       uint8_t buf[8];
+       int ret;
+
+       if (wcache->tdb == NULL) {
+               DEBUG(10, ("wcache_store_seqnum: wcache->tdb == NULL\n"));
+               return false;
        }
-               
-       fstr_sprintf( key_str, "SEQNUM/%s", domain->name );
-       
-       SIVAL(buf, 0, domain->sequence_number);
-       SIVAL(buf, 4, domain->last_seq_check);
-       data.dptr = buf;
-       data.dsize = 8;
-       
-       if ( tdb_store_bystring( wcache->tdb, key_str, data, TDB_REPLACE) == -1 ) {
-               DEBUG(10,("store_cache_seqnum: tdb_store fail key [%s]\n", key_str ));
-               return NT_STATUS_UNSUCCESSFUL;
+
+       key_str = talloc_asprintf(talloc_tos(), "SEQNUM/%s", domain_name);
+       if (key_str == NULL) {
+               DEBUG(10, ("talloc_asprintf failed\n"));
+               return false;
        }
 
-       DEBUG(10,("store_cache_seqnum: success [%s][%u @ %u]\n", 
-               domain->name, domain->sequence_number, 
-               (uint32)domain->last_seq_check));
-       
-       return NT_STATUS_OK;
+       SIVAL(buf, 0, seqnum);
+       SIVAL(buf, 4, last_seq_check);
+
+       ret = tdb_store_bystring(wcache->tdb, key_str,
+                                make_tdb_data(buf, sizeof(buf)), TDB_REPLACE);
+       TALLOC_FREE(key_str);
+       if (ret == -1) {
+               DEBUG(10, ("tdb_store_bystring failed: %s\n",
+                          tdb_errorstr(wcache->tdb)));
+               TALLOC_FREE(key_str);
+               return false;
+       }
+
+       DEBUG(10, ("wcache_store_seqnum: success [%s][%u @ %u]\n",
+                  domain_name, seqnum, (unsigned)last_seq_check));
+
+       return true;
+}
+
+static bool store_cache_seqnum( struct winbindd_domain *domain )
+{
+       return wcache_store_seqnum(domain->name, domain->sequence_number,
+                                  domain->last_seq_check);
 }
 
 /*
@@ -465,10 +496,10 @@ static void refresh_sequence_number(struct winbindd_domain *domain, bool force)
        time_t t = time(NULL);
        unsigned cache_time = lp_winbind_cache_time();
 
-       if ( IS_DOMAIN_OFFLINE(domain) ) {
+       if (is_domain_offline(domain)) {
                return;
        }
-       
+
        get_cache( domain );
 
 #if 0  /* JERRY -- disable as the default cache time is now 5 minutes */
@@ -481,17 +512,22 @@ static void refresh_sequence_number(struct winbindd_domain *domain, bool force)
        time_diff = t - domain->last_seq_check;
 
        /* see if we have to refetch the domain sequence number */
-       if (!force && (time_diff < cache_time)) {
+       if (!force && (time_diff < cache_time) &&
+                       (domain->sequence_number != DOM_SEQUENCE_NONE) &&
+                       NT_STATUS_IS_OK(domain->last_status)) {
                DEBUG(10, ("refresh_sequence_number: %s time ok\n", domain->name));
                goto done;
        }
-       
+
        /* try to get the sequence number from the tdb cache first */
        /* this will update the timestamp as well */
-       
+
        status = fetch_cache_seqnum( domain, t );
-       if ( NT_STATUS_IS_OK(status) )
-               goto done;      
+       if (NT_STATUS_IS_OK(status) &&
+                       (domain->sequence_number != DOM_SEQUENCE_NONE) &&
+                       NT_STATUS_IS_OK(domain->last_status)) {
+               goto done;
+       }
 
        /* important! make sure that we know if this is a native 
           mode domain or not.  And that we can contact it. */
@@ -515,11 +551,11 @@ static void refresh_sequence_number(struct winbindd_domain *domain, bool force)
                DEBUG(10,("refresh_sequence_number: failed with %s\n", nt_errstr(status)));
                domain->sequence_number = DOM_SEQUENCE_NONE;
        }
-       
+
        domain->last_status = status;
        domain->last_seq_check = time(NULL);
-       
-       /* save the new sequence number ni the cache */
+
+       /* save the new sequence number in the cache */
        store_cache_seqnum( domain );
 
 done:
@@ -599,13 +635,33 @@ static struct cache_entry *wcache_fetch_raw(char *kstr)
                centry_free(centry);
                return NULL;
        }
-       
+
        centry->status = centry_ntstatus(centry);
        centry->sequence_number = centry_uint32(centry);
 
        return centry;
 }
 
+static bool is_my_own_sam_domain(struct winbindd_domain *domain)
+{
+       if (strequal(domain->name, get_global_sam_name()) &&
+            dom_sid_equal(&domain->sid, get_global_sam_sid())) {
+               return true;
+       }
+
+       return false;
+}
+
+static bool is_builtin_domain(struct winbindd_domain *domain)
+{
+       if (strequal(domain->name, "BUILTIN") &&
+           dom_sid_equal(&domain->sid, &global_sid_Builtin)) {
+               return true;
+       }
+
+       return false;
+}
+
 /*
   fetch an entry from the cache, with a varargs key. auto-fetch the sequence
   number and return status
@@ -621,7 +677,9 @@ static struct cache_entry *wcache_fetch(struct winbind_cache *cache,
        char *kstr;
        struct cache_entry *centry;
 
-       if (opt_nocache) {
+       if (!winbindd_use_cache() ||
+           is_my_own_sam_domain(domain) ||
+           is_builtin_domain(domain)) {
                return NULL;
        }
 
@@ -753,7 +811,7 @@ static void centry_put_hash16(struct cache_entry *centry, const uint8 val[16])
        centry->ofs += 16;
 }
 
-static void centry_put_sid(struct cache_entry *centry, const DOM_SID *sid) 
+static void centry_put_sid(struct cache_entry *centry, const struct dom_sid *sid)
 {
        fstring sid_string;
        centry_put_string(centry, sid_to_fstring(sid_string, sid));
@@ -823,7 +881,7 @@ static void centry_end(struct cache_entry *centry, const char *format, ...)
        char *kstr;
        TDB_DATA key, data;
 
-       if (opt_nocache) {
+       if (!winbindd_use_cache()) {
                return;
        }
 
@@ -841,7 +899,7 @@ static void centry_end(struct cache_entry *centry, const char *format, ...)
 
 static void wcache_save_name_to_sid(struct winbindd_domain *domain, 
                                    NTSTATUS status, const char *domain_name,
-                                   const char *name, const DOM_SID *sid, 
+                                   const char *name, const struct dom_sid *sid,
                                    enum lsa_SidType type)
 {
        struct cache_entry *centry;
@@ -861,7 +919,7 @@ static void wcache_save_name_to_sid(struct winbindd_domain *domain,
 }
 
 static void wcache_save_sid_to_name(struct winbindd_domain *domain, NTSTATUS status, 
-                                   const DOM_SID *sid, const char *domain_name, const char *name, enum lsa_SidType type)
+                                   const struct dom_sid *sid, const char *domain_name, const char *name, enum lsa_SidType type)
 {
        struct cache_entry *centry;
        fstring sid_string;
@@ -883,7 +941,8 @@ static void wcache_save_sid_to_name(struct winbindd_domain *domain, NTSTATUS sta
 }
 
 
-static void wcache_save_user(struct winbindd_domain *domain, NTSTATUS status, WINBIND_USERINFO *info)
+static void wcache_save_user(struct winbindd_domain *domain, NTSTATUS status,
+                            struct wbint_userinfo *info)
 {
        struct cache_entry *centry;
        fstring sid_string;
@@ -929,6 +988,8 @@ static void wcache_save_lockout_policy(struct winbindd_domain *domain,
        centry_free(centry);
 }
 
+
+
 static void wcache_save_password_policy(struct winbindd_domain *domain,
                                        NTSTATUS status,
                                        struct samr_DomInfo1 *policy)
@@ -952,7 +1013,210 @@ static void wcache_save_password_policy(struct winbindd_domain *domain,
        centry_free(centry);
 }
 
-NTSTATUS wcache_cached_creds_exist(struct winbindd_domain *domain, const DOM_SID *sid)
+/***************************************************************************
+ ***************************************************************************/
+
+static void wcache_save_username_alias(struct winbindd_domain *domain,
+                                      NTSTATUS status,
+                                      const char *name, const char *alias)
+{
+       struct cache_entry *centry;
+       fstring uname;
+
+       if ( (centry = centry_start(domain, status)) == NULL )
+               return;
+
+       centry_put_string( centry, alias );
+
+       fstrcpy(uname, name);
+       strupper_m(uname);
+       centry_end(centry, "NSS/NA/%s", uname);
+
+       DEBUG(10,("wcache_save_username_alias: %s -> %s\n", name, alias ));
+
+       centry_free(centry);
+}
+
+static void wcache_save_alias_username(struct winbindd_domain *domain,
+                                      NTSTATUS status,
+                                      const char *alias, const char *name)
+{
+       struct cache_entry *centry;
+       fstring uname;
+
+       if ( (centry = centry_start(domain, status)) == NULL )
+               return;
+
+       centry_put_string( centry, name );
+
+       fstrcpy(uname, alias);
+       strupper_m(uname);
+       centry_end(centry, "NSS/AN/%s", uname);
+
+       DEBUG(10,("wcache_save_alias_username: %s -> %s\n", alias, name ));
+
+       centry_free(centry);
+}
+
+/***************************************************************************
+ ***************************************************************************/
+
+NTSTATUS resolve_username_to_alias( TALLOC_CTX *mem_ctx,
+                                   struct winbindd_domain *domain,
+                                   const char *name, char **alias )
+{
+       struct winbind_cache *cache = get_cache(domain);
+       struct cache_entry *centry = NULL;
+       NTSTATUS status;
+       char *upper_name;
+
+       if ( domain->internal )
+               return NT_STATUS_NOT_SUPPORTED;
+
+       if (!cache->tdb)
+               goto do_query;
+
+       if ( (upper_name = SMB_STRDUP(name)) == NULL )
+               return NT_STATUS_NO_MEMORY;
+       strupper_m(upper_name);
+
+       centry = wcache_fetch(cache, domain, "NSS/NA/%s", upper_name);
+
+       SAFE_FREE( upper_name );
+
+       if (!centry)
+               goto do_query;
+
+       status = centry->status;
+
+       if (!NT_STATUS_IS_OK(status)) {
+               centry_free(centry);
+               return status;
+       }
+
+       *alias = centry_string( centry, mem_ctx );
+
+       centry_free(centry);
+
+       DEBUG(10,("resolve_username_to_alias: [Cached] - mapped %s to %s\n",
+                 name, *alias ? *alias : "(none)"));
+
+       return (*alias) ? NT_STATUS_OK : NT_STATUS_OBJECT_NAME_NOT_FOUND;
+
+do_query:
+
+       /* If its not in cache and we are offline, then fail */
+
+       if ( get_global_winbindd_state_offline() || !domain->online ) {
+               DEBUG(8,("resolve_username_to_alias: rejecting query "
+                        "in offline mode\n"));
+               return NT_STATUS_NOT_FOUND;
+       }
+
+       status = nss_map_to_alias( mem_ctx, domain->name, name, alias );
+
+       if ( NT_STATUS_IS_OK( status ) ) {
+               wcache_save_username_alias(domain, status, name, *alias);
+       }
+
+       if ( NT_STATUS_EQUAL( status, NT_STATUS_NONE_MAPPED ) ) {
+               wcache_save_username_alias(domain, status, name, "(NULL)");
+       }
+
+       DEBUG(5,("resolve_username_to_alias: backend query returned %s\n",
+                nt_errstr(status)));
+
+       if ( NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ) {
+               set_domain_offline( domain );
+       }
+
+       return status;
+}
+
+/***************************************************************************
+ ***************************************************************************/
+
+NTSTATUS resolve_alias_to_username( TALLOC_CTX *mem_ctx,
+                                   struct winbindd_domain *domain,
+                                   const char *alias, char **name )
+{
+       struct winbind_cache *cache = get_cache(domain);
+       struct cache_entry *centry = NULL;
+       NTSTATUS status;
+       char *upper_name;
+
+       if ( domain->internal )
+               return  NT_STATUS_NOT_SUPPORTED;
+
+       if (!cache->tdb)
+               goto do_query;
+
+       if ( (upper_name = SMB_STRDUP(alias)) == NULL )
+               return NT_STATUS_NO_MEMORY;
+       strupper_m(upper_name);
+
+       centry = wcache_fetch(cache, domain, "NSS/AN/%s", upper_name);
+
+       SAFE_FREE( upper_name );
+
+       if (!centry)
+               goto do_query;
+
+       status = centry->status;
+
+       if (!NT_STATUS_IS_OK(status)) {
+               centry_free(centry);
+               return status;
+       }
+
+       *name = centry_string( centry, mem_ctx );
+
+       centry_free(centry);
+
+       DEBUG(10,("resolve_alias_to_username: [Cached] - mapped %s to %s\n",
+                 alias, *name ? *name : "(none)"));
+
+       return (*name) ? NT_STATUS_OK : NT_STATUS_OBJECT_NAME_NOT_FOUND;
+
+do_query:
+
+       /* If its not in cache and we are offline, then fail */
+
+       if ( get_global_winbindd_state_offline() || !domain->online ) {
+               DEBUG(8,("resolve_alias_to_username: rejecting query "
+                        "in offline mode\n"));
+               return NT_STATUS_NOT_FOUND;
+       }
+
+       /* an alias cannot contain a domain prefix or '@' */
+
+       if (strchr(alias, '\\') || strchr(alias, '@')) {
+               DEBUG(10,("resolve_alias_to_username: skipping fully "
+                         "qualified name %s\n", alias));
+               return NT_STATUS_OBJECT_NAME_INVALID;
+       }
+
+       status = nss_map_from_alias( mem_ctx, domain->name, alias, name );
+
+       if ( NT_STATUS_IS_OK( status ) ) {
+               wcache_save_alias_username( domain, status, alias, *name );
+       }
+
+       if (NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED)) {
+               wcache_save_alias_username(domain, status, alias, "(NULL)");
+       }
+
+       DEBUG(5,("resolve_alias_to_username: backend query returned %s\n",
+                nt_errstr(status)));
+
+       if ( NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND) ) {
+               set_domain_offline( domain );
+       }
+
+       return status;
+}
+
+NTSTATUS wcache_cached_creds_exist(struct winbindd_domain *domain, const struct dom_sid *sid)
 {
        struct winbind_cache *cache = get_cache(domain);
        TDB_DATA data;
@@ -987,7 +1251,7 @@ NTSTATUS wcache_cached_creds_exist(struct winbindd_domain *domain, const DOM_SID
 
 NTSTATUS wcache_get_creds(struct winbindd_domain *domain, 
                          TALLOC_CTX *mem_ctx, 
-                         const DOM_SID *sid,
+                         const struct dom_sid *sid,
                          const uint8 **cached_nt_pass,
                          const uint8 **cached_salt)
 {
@@ -1067,8 +1331,7 @@ NTSTATUS wcache_get_creds(struct winbindd_domain *domain,
 /* Store creds for a SID - only writes out new salted ones. */
 
 NTSTATUS wcache_save_creds(struct winbindd_domain *domain, 
-                          TALLOC_CTX *mem_ctx, 
-                          const DOM_SID *sid, 
+                          const struct dom_sid *sid,
                           const uint8 nt_pass[NT_HASH_LEN])
 {
        struct cache_entry *centry;
@@ -1114,12 +1377,13 @@ NTSTATUS wcache_save_creds(struct winbindd_domain *domain,
 static NTSTATUS query_user_list(struct winbindd_domain *domain,
                                TALLOC_CTX *mem_ctx,
                                uint32 *num_entries, 
-                               WINBIND_USERINFO **info)
+                               struct wbint_userinfo **info)
 {
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
        NTSTATUS status;
        unsigned int i, retry;
+       bool old_status = domain->online;
 
        if (!cache->tdb)
                goto do_query;
@@ -1128,12 +1392,13 @@ static NTSTATUS query_user_list(struct winbindd_domain *domain,
        if (!centry)
                goto do_query;
 
+do_fetch_cache:
        *num_entries = centry_uint32(centry);
-       
+
        if (*num_entries == 0)
                goto do_cached;
 
-       (*info) = TALLOC_ARRAY(mem_ctx, WINBIND_USERINFO, *num_entries);
+       (*info) = TALLOC_ARRAY(mem_ctx, struct wbint_userinfo, *num_entries);
        if (! (*info)) {
                smb_panic_fn("query_user_list out of memory");
        }
@@ -1142,8 +1407,8 @@ static NTSTATUS query_user_list(struct winbindd_domain *domain,
                (*info)[i].full_name = centry_string(centry, mem_ctx);
                (*info)[i].homedir = centry_string(centry, mem_ctx);
                (*info)[i].shell = centry_string(centry, mem_ctx);
-               centry_sid(centry, mem_ctx, &(*info)[i].user_sid);
-               centry_sid(centry, mem_ctx, &(*info)[i].group_sid);
+               centry_sid(centry, &(*info)[i].user_sid);
+               centry_sid(centry, &(*info)[i].group_sid);
        }
 
 do_cached:     
@@ -1188,12 +1453,44 @@ do_query:
                                  "connection cache\n"));
                        invalidate_cm_connection(&domain->conn);
                }
+               if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+                   NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+                       if (!domain->internal && old_status) {
+                               set_domain_offline(domain);
+                       }
+                       /* store partial response. */
+                       if (*num_entries > 0) {
+                               /*
+                                * humm, what about the status used for cache?
+                                * Should it be NT_STATUS_OK?
+                                */
+                               break;
+                       }
+                       /*
+                        * domain is offline now, and there is no user entries,
+                        * try to fetch from cache again.
+                        */
+                       if (cache->tdb && !domain->online && !domain->internal && old_status) {
+                               centry = wcache_fetch(cache, domain, "UL/%s", domain->name);
+                               /* partial response... */
+                               if (!centry) {
+                                       goto skip_save;
+                               } else {
+                                       goto do_fetch_cache;
+                               }
+                       } else {
+                               goto skip_save;
+                       }
+               }
 
        } while (NT_STATUS_V(status) == NT_STATUS_V(NT_STATUS_UNSUCCESSFUL) && 
                 (retry++ < 5));
 
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        centry = centry_start(domain, status);
        if (!centry)
                goto skip_save;
@@ -1237,7 +1534,9 @@ static NTSTATUS enum_dom_groups(struct winbindd_domain *domain,
        struct cache_entry *centry = NULL;
        NTSTATUS status;
        unsigned int i;
+       bool old_status;
 
+       old_status = domain->online;
        if (!cache->tdb)
                goto do_query;
 
@@ -1245,8 +1544,9 @@ static NTSTATUS enum_dom_groups(struct winbindd_domain *domain,
        if (!centry)
                goto do_query;
 
+do_fetch_cache:
        *num_entries = centry_uint32(centry);
-       
+
        if (*num_entries == 0)
                goto do_cached;
 
@@ -1283,8 +1583,26 @@ do_query:
 
        status = domain->backend->enum_dom_groups(domain, mem_ctx, num_entries, info);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+           NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (cache->tdb &&
+                       !domain->online &&
+                       !domain->internal &&
+                       old_status) {
+                       centry = wcache_fetch(cache, domain, "GL/%s/domain", domain->name);
+                       if (centry) {
+                               goto do_fetch_cache;
+                       }
+               }
+       }
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        centry = centry_start(domain, status);
        if (!centry)
                goto skip_save;
@@ -1311,7 +1629,9 @@ static NTSTATUS enum_local_groups(struct winbindd_domain *domain,
        struct cache_entry *centry = NULL;
        NTSTATUS status;
        unsigned int i;
+       bool old_status;
 
+       old_status = domain->online;
        if (!cache->tdb)
                goto do_query;
 
@@ -1319,8 +1639,9 @@ static NTSTATUS enum_local_groups(struct winbindd_domain *domain,
        if (!centry)
                goto do_query;
 
+do_fetch_cache:
        *num_entries = centry_uint32(centry);
-       
+
        if (*num_entries == 0)
                goto do_cached;
 
@@ -1367,8 +1688,26 @@ do_query:
 
        status = domain->backend->enum_local_groups(domain, mem_ctx, num_entries, info);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (cache->tdb &&
+                       !domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       centry = wcache_fetch(cache, domain, "GL/%s/local", domain->name);
+                       if (centry) {
+                               goto do_fetch_cache;
+                       }
+               }
+       }
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        centry = centry_start(domain, status);
        if (!centry)
                goto skip_save;
@@ -1385,42 +1724,64 @@ skip_save:
        return status;
 }
 
-/* convert a single name to a sid in a domain */
-static NTSTATUS name_to_sid(struct winbindd_domain *domain,
-                           TALLOC_CTX *mem_ctx,
-                           enum winbindd_cmd orig_cmd,
+NTSTATUS wcache_name_to_sid(struct winbindd_domain *domain,
                            const char *domain_name,
                            const char *name,
-                           DOM_SID *sid,
+                           struct dom_sid *sid,
                            enum lsa_SidType *type)
 {
        struct winbind_cache *cache = get_cache(domain);
-       struct cache_entry *centry = NULL;
+       struct cache_entry *centry;
        NTSTATUS status;
-       fstring uname;
+       char *uname;
 
-       if (!cache->tdb)
-               goto do_query;
+       if (cache->tdb == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
+
+       uname = talloc_strdup_upper(talloc_tos(), name);
+       if (uname == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
 
-       fstrcpy(uname, name);
-       strupper_m(uname);
        centry = wcache_fetch(cache, domain, "NS/%s/%s", domain_name, uname);
-       if (!centry)
-               goto do_query;
+       TALLOC_FREE(uname);
+       if (centry == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
 
        status = centry->status;
        if (NT_STATUS_IS_OK(status)) {
                *type = (enum lsa_SidType)centry_uint32(centry);
-               centry_sid(centry, mem_ctx, sid);
+               centry_sid(centry, sid);
        }
 
-       DEBUG(10,("name_to_sid: [Cached] - cached name for domain %s status: %s\n",
-               domain->name, nt_errstr(status) ));
+       DEBUG(10,("name_to_sid: [Cached] - cached name for domain %s status: "
+                 "%s\n", domain->name, nt_errstr(status) ));
 
        centry_free(centry);
        return status;
+}
+
+/* convert a single name to a sid in a domain */
+static NTSTATUS name_to_sid(struct winbindd_domain *domain,
+                           TALLOC_CTX *mem_ctx,
+                           const char *domain_name,
+                           const char *name,
+                           uint32_t flags,
+                           struct dom_sid *sid,
+                           enum lsa_SidType *type)
+{
+       NTSTATUS status;
+       bool old_status;
+
+       old_status = domain->online;
+
+       status = wcache_name_to_sid(domain, domain_name, name, sid, type);
+       if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
+               return status;
+       }
 
-do_query:
        ZERO_STRUCTP(sid);
 
        /* If the seq number check indicated that there is a problem
@@ -1437,9 +1798,22 @@ do_query:
        DEBUG(10,("name_to_sid: [Cached] - doing backend query for name for domain %s\n",
                domain->name ));
 
-       status = domain->backend->name_to_sid(domain, mem_ctx, orig_cmd, 
-                                             domain_name, name, sid, type);
+       status = domain->backend->name_to_sid(domain, mem_ctx, domain_name,
+                                             name, flags, sid, type);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (!domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       NTSTATUS cache_status;
+                       cache_status = wcache_name_to_sid(domain, domain_name, name, sid, type);
+                       return cache_status;
+               }
+       }
        /* and save it */
        refresh_sequence_number(domain, false);
 
@@ -1454,46 +1828,71 @@ do_query:
                        wcache_save_sid_to_name(domain, status, sid, domain_name, name, *type);
                }
        }
-       
+
        return status;
 }
 
-/* convert a sid to a user or group name. The sid is guaranteed to be in the domain
-   given */
-static NTSTATUS sid_to_name(struct winbindd_domain *domain,
+NTSTATUS wcache_sid_to_name(struct winbindd_domain *domain,
+                           const struct dom_sid *sid,
                            TALLOC_CTX *mem_ctx,
-                           const DOM_SID *sid,
                            char **domain_name,
                            char **name,
                            enum lsa_SidType *type)
 {
        struct winbind_cache *cache = get_cache(domain);
-       struct cache_entry *centry = NULL;
+       struct cache_entry *centry;
+       char *sid_string;
        NTSTATUS status;
-       fstring sid_string;
 
-       if (!cache->tdb)
-               goto do_query;
+       if (cache->tdb == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
 
-       centry = wcache_fetch(cache, domain, "SN/%s",
-                             sid_to_fstring(sid_string, sid));
-       if (!centry)
-               goto do_query;
+       sid_string = sid_string_tos(sid);
+       if (sid_string == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
 
-       status = centry->status;
-       if (NT_STATUS_IS_OK(status)) {
+       centry = wcache_fetch(cache, domain, "SN/%s", sid_string);
+       TALLOC_FREE(sid_string);
+       if (centry == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
+
+       if (NT_STATUS_IS_OK(centry->status)) {
                *type = (enum lsa_SidType)centry_uint32(centry);
                *domain_name = centry_string(centry, mem_ctx);
                *name = centry_string(centry, mem_ctx);
        }
 
-       DEBUG(10,("sid_to_name: [Cached] - cached name for domain %s status: %s\n",
-               domain->name, nt_errstr(status) ));
-
+       status = centry->status;
        centry_free(centry);
+
+       DEBUG(10,("sid_to_name: [Cached] - cached name for domain %s status: "
+                 "%s\n", domain->name, nt_errstr(status) ));
+
        return status;
+}
+
+/* convert a sid to a user or group name. The sid is guaranteed to be in the domain
+   given */
+static NTSTATUS sid_to_name(struct winbindd_domain *domain,
+                           TALLOC_CTX *mem_ctx,
+                           const struct dom_sid *sid,
+                           char **domain_name,
+                           char **name,
+                           enum lsa_SidType *type)
+{
+       NTSTATUS status;
+       bool old_status;
+
+       old_status = domain->online;
+       status = wcache_sid_to_name(domain, sid, mem_ctx, domain_name, name,
+                                   type);
+       if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
+               return status;
+       }
 
-do_query:
        *name = NULL;
        *domain_name = NULL;
 
@@ -1513,8 +1912,25 @@ do_query:
 
        status = domain->backend->sid_to_name(domain, mem_ctx, sid, domain_name, name, type);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (!domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       NTSTATUS cache_status;
+                       cache_status = wcache_sid_to_name(domain, sid, mem_ctx,
+                                                       domain_name, name, type);
+                       return cache_status;
+               }
+       }
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        wcache_save_sid_to_name(domain, status, sid, *domain_name, *name, *type);
 
        /* We can't save the name to sid mapping here, as with sid history a
@@ -1525,7 +1941,7 @@ do_query:
 
 static NTSTATUS rids_to_names(struct winbindd_domain *domain,
                              TALLOC_CTX *mem_ctx,
-                             const DOM_SID *domain_sid,
+                             const struct dom_sid *domain_sid,
                              uint32 *rids,
                              size_t num_rids,
                              char **domain_name,
@@ -1537,7 +1953,9 @@ static NTSTATUS rids_to_names(struct winbindd_domain *domain,
        NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
        bool have_mapped;
        bool have_unmapped;
+       bool old_status;
 
+       old_status = domain->online;
        *domain_name = NULL;
        *names = NULL;
        *types = NULL;
@@ -1561,7 +1979,7 @@ static NTSTATUS rids_to_names(struct winbindd_domain *domain,
        have_mapped = have_unmapped = false;
 
        for (i=0; i<num_rids; i++) {
-               DOM_SID sid;
+               struct dom_sid sid;
                struct cache_entry *centry;
                fstring tmp;
 
@@ -1622,16 +2040,83 @@ static NTSTATUS rids_to_names(struct winbindd_domain *domain,
                                                rids, num_rids, domain_name,
                                                names, types);
 
+       if (NT_STATUS_EQUAL(result, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(result, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (cache->tdb &&
+                       !domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       have_mapped = have_unmapped = false;
+
+                       for (i=0; i<num_rids; i++) {
+                               struct dom_sid sid;
+                               struct cache_entry *centry;
+                               fstring tmp;
+
+                               if (!sid_compose(&sid, domain_sid, rids[i])) {
+                                       result = NT_STATUS_INTERNAL_ERROR;
+                                       goto error;
+                               }
+
+                               centry = wcache_fetch(cache, domain, "SN/%s",
+                                                     sid_to_fstring(tmp, &sid));
+                               if (!centry) {
+                                       (*types)[i] = SID_NAME_UNKNOWN;
+                                       (*names)[i] = talloc_strdup(*names, "");
+                                       continue;
+                               }
+
+                               (*types)[i] = SID_NAME_UNKNOWN;
+                               (*names)[i] = talloc_strdup(*names, "");
+
+                               if (NT_STATUS_IS_OK(centry->status)) {
+                                       char *dom;
+                                       have_mapped = true;
+                                       (*types)[i] = (enum lsa_SidType)centry_uint32(centry);
+
+                                       dom = centry_string(centry, mem_ctx);
+                                       if (*domain_name == NULL) {
+                                               *domain_name = dom;
+                                       } else {
+                                               talloc_free(dom);
+                                       }
+
+                                       (*names)[i] = centry_string(centry, *names);
+
+                               } else if (NT_STATUS_EQUAL(centry->status, NT_STATUS_NONE_MAPPED)) {
+                                       have_unmapped = true;
+
+                               } else {
+                                       /* something's definitely wrong */
+                                       result = centry->status;
+                                       goto error;
+                               }
+
+                               centry_free(centry);
+                       }
+
+                       if (!have_mapped) {
+                               return NT_STATUS_NONE_MAPPED;
+                       }
+                       if (!have_unmapped) {
+                               return NT_STATUS_OK;
+                       }
+                       return STATUS_SOME_UNMAPPED;
+               }
+       }
        /*
          None of the queried rids has been found so save all negative entries
        */
        if (NT_STATUS_EQUAL(result, NT_STATUS_NONE_MAPPED)) {
                for (i = 0; i < num_rids; i++) {
-                       DOM_SID sid;
+                       struct dom_sid sid;
                        const char *name = "";
                        const enum lsa_SidType type = SID_NAME_UNKNOWN;
                        NTSTATUS status = NT_STATUS_NONE_MAPPED;
-                       
+
                        if (!sid_compose(&sid, domain_sid, rids[i])) {
                                return NT_STATUS_INTERNAL_ERROR;
                        }
@@ -1654,7 +2139,7 @@ static NTSTATUS rids_to_names(struct winbindd_domain *domain,
        refresh_sequence_number(domain, false);
 
        for (i=0; i<num_rids; i++) {
-               DOM_SID sid;
+               struct dom_sid sid;
                NTSTATUS status;
 
                if (!sid_compose(&sid, domain_sid, rids[i])) {
@@ -1672,44 +2157,51 @@ static NTSTATUS rids_to_names(struct winbindd_domain *domain,
        return result;
 
  error:
-       
        TALLOC_FREE(*names);
        TALLOC_FREE(*types);
        return result;
 }
 
-/* Lookup user information from a rid */
-static NTSTATUS query_user(struct winbindd_domain *domain, 
-                          TALLOC_CTX *mem_ctx, 
-                          const DOM_SID *user_sid, 
-                          WINBIND_USERINFO *info)
+NTSTATUS wcache_query_user(struct winbindd_domain *domain,
+                          TALLOC_CTX *mem_ctx,
+                          const struct dom_sid *user_sid,
+                          struct wbint_userinfo *info)
 {
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
        NTSTATUS status;
-       fstring tmp;
+       char *sid_string;
 
-       if (!cache->tdb)
-               goto do_query;
+       if (cache->tdb == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
 
-       centry = wcache_fetch(cache, domain, "U/%s",
-                             sid_to_fstring(tmp, user_sid));
-       
-       /* If we have an access denied cache entry and a cached info3 in the
-           samlogon cache then do a query.  This will force the rpc back end
-           to return the info3 data. */
+       sid_string = sid_string_tos(user_sid);
+       if (sid_string == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
 
-       if (NT_STATUS_V(domain->last_status) == NT_STATUS_V(NT_STATUS_ACCESS_DENIED) &&
+       centry = wcache_fetch(cache, domain, "U/%s", sid_string);
+       TALLOC_FREE(sid_string);
+       if (centry == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
+
+       /*
+        * If we have an access denied cache entry and a cached info3
+        * in the samlogon cache then do a query.  This will force the
+        * rpc back end to return the info3 data.
+        */
+
+       if (NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED) &&
            netsamlogon_cache_have(user_sid)) {
-               DEBUG(10, ("query_user: cached access denied and have cached info3\n"));
+               DEBUG(10, ("query_user: cached access denied and have cached "
+                          "info3\n"));
                domain->last_status = NT_STATUS_OK;
                centry_free(centry);
-               goto do_query;
+               return NT_STATUS_NOT_FOUND;
        }
-       
-       if (!centry)
-               goto do_query;
-       
+
        /* if status is not ok then this is a negative hit
           and the rest of the data doesn't matter */
        status = centry->status;
@@ -1719,93 +2211,145 @@ static NTSTATUS query_user(struct winbindd_domain *domain,
                info->homedir = centry_string(centry, mem_ctx);
                info->shell = centry_string(centry, mem_ctx);
                info->primary_gid = centry_uint32(centry);
-               centry_sid(centry, mem_ctx, &info->user_sid);
-               centry_sid(centry, mem_ctx, &info->group_sid);
+               centry_sid(centry, &info->user_sid);
+               centry_sid(centry, &info->group_sid);
        }
 
-       DEBUG(10,("query_user: [Cached] - cached info for domain %s status: %s\n",
-               domain->name, nt_errstr(status) ));
+       DEBUG(10,("query_user: [Cached] - cached info for domain %s status: "
+                 "%s\n", domain->name, nt_errstr(status) ));
 
        centry_free(centry);
        return status;
+}
+
+/* Lookup user information from a rid */
+static NTSTATUS query_user(struct winbindd_domain *domain,
+                          TALLOC_CTX *mem_ctx,
+                          const struct dom_sid *user_sid,
+                          struct wbint_userinfo *info)
+{
+       NTSTATUS status;
+       bool old_status;
+
+       old_status = domain->online;
+       status = wcache_query_user(domain, mem_ctx, user_sid, info);
+       if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
+               return status;
+       }
 
-do_query:
        ZERO_STRUCTP(info);
 
        /* Return status value returned by seq number check */
 
        if (!NT_STATUS_IS_OK(domain->last_status))
                return domain->last_status;
-       
+
        DEBUG(10,("query_user: [Cached] - doing backend query for info for domain %s\n",
                domain->name ));
 
        status = domain->backend->query_user(domain, mem_ctx, user_sid, info);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (!domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       NTSTATUS cache_status;
+                       cache_status = wcache_query_user(domain, mem_ctx, user_sid, info);
+                       return cache_status;
+               }
+       }
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        wcache_save_user(domain, status, info);
 
        return status;
 }
 
-
-/* Lookup groups a user is a member of. */
-static NTSTATUS lookup_usergroups(struct winbindd_domain *domain,
+NTSTATUS wcache_lookup_usergroups(struct winbindd_domain *domain,
                                  TALLOC_CTX *mem_ctx,
-                                 const DOM_SID *user_sid, 
-                                 uint32 *num_groups, DOM_SID **user_gids)
+                                 const struct dom_sid *user_sid,
+                                 uint32_t *pnum_sids,
+                                 struct dom_sid **psids)
 {
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
        NTSTATUS status;
-       unsigned int i;
+       uint32_t i, num_sids;
+       struct dom_sid *sids;
        fstring sid_string;
 
-       if (!cache->tdb)
-               goto do_query;
+       if (cache->tdb == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
 
        centry = wcache_fetch(cache, domain, "UG/%s",
                              sid_to_fstring(sid_string, user_sid));
-       
+       if (centry == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
+
        /* If we have an access denied cache entry and a cached info3 in the
            samlogon cache then do a query.  This will force the rpc back end
            to return the info3 data. */
 
-       if (NT_STATUS_V(domain->last_status) == NT_STATUS_V(NT_STATUS_ACCESS_DENIED) &&
-           netsamlogon_cache_have(user_sid)) {
-               DEBUG(10, ("lookup_usergroups: cached access denied and have cached info3\n"));
+       if (NT_STATUS_EQUAL(domain->last_status, NT_STATUS_ACCESS_DENIED)
+           && netsamlogon_cache_have(user_sid)) {
+               DEBUG(10, ("lookup_usergroups: cached access denied and have "
+                          "cached info3\n"));
                domain->last_status = NT_STATUS_OK;
                centry_free(centry);
-               goto do_query;
+               return NT_STATUS_NOT_FOUND;
        }
-       
-       if (!centry)
-               goto do_query;
-
-       *num_groups = centry_uint32(centry);
-       
-       if (*num_groups == 0)
-               goto do_cached;
 
-       (*user_gids) = TALLOC_ARRAY(mem_ctx, DOM_SID, *num_groups);
-       if (! (*user_gids)) {
-               smb_panic_fn("lookup_usergroups out of memory");
+       num_sids = centry_uint32(centry);
+       sids = talloc_array(mem_ctx, struct dom_sid, num_sids);
+       if (sids == NULL) {
+               centry_free(centry);
+               return NT_STATUS_NO_MEMORY;
        }
-       for (i=0; i<(*num_groups); i++) {
-               centry_sid(centry, mem_ctx, &(*user_gids)[i]);
+
+       for (i=0; i<num_sids; i++) {
+               centry_sid(centry, &sids[i]);
        }
 
-do_cached:     
        status = centry->status;
 
-       DEBUG(10,("lookup_usergroups: [Cached] - cached info for domain %s status: %s\n",
-               domain->name, nt_errstr(status) ));
+       DEBUG(10,("lookup_usergroups: [Cached] - cached info for domain %s "
+                 "status: %s\n", domain->name, nt_errstr(status)));
 
        centry_free(centry);
+
+       *pnum_sids = num_sids;
+       *psids = sids;
        return status;
+}
+
+/* Lookup groups a user is a member of. */
+static NTSTATUS lookup_usergroups(struct winbindd_domain *domain,
+                                 TALLOC_CTX *mem_ctx,
+                                 const struct dom_sid *user_sid,
+                                 uint32 *num_groups, struct dom_sid **user_gids)
+{
+       struct cache_entry *centry = NULL;
+       NTSTATUS status;
+       unsigned int i;
+       fstring sid_string;
+       bool old_status;
+
+       old_status = domain->online;
+       status = wcache_lookup_usergroups(domain, mem_ctx, user_sid,
+                                         num_groups, user_gids);
+       if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
+               return status;
+       }
 
-do_query:
        (*num_groups) = 0;
        (*user_gids) = NULL;
 
@@ -1819,11 +2363,28 @@ do_query:
 
        status = domain->backend->lookup_usergroups(domain, mem_ctx, user_sid, num_groups, user_gids);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (!domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       NTSTATUS cache_status;
+                       cache_status = wcache_lookup_usergroups(domain, mem_ctx, user_sid,
+                                                         num_groups, user_gids);
+                       return cache_status;
+               }
+       }
        if ( NT_STATUS_EQUAL(status, NT_STATUS_SYNCHRONIZATION_REQUIRED) )
                goto skip_save;
-       
+
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        centry = centry_start(domain, status);
        if (!centry)
                goto skip_save;
@@ -1840,58 +2401,74 @@ skip_save:
        return status;
 }
 
-static NTSTATUS lookup_useraliases(struct winbindd_domain *domain,
-                                  TALLOC_CTX *mem_ctx,
-                                  uint32 num_sids, const DOM_SID *sids,
-                                  uint32 *num_aliases, uint32 **alias_rids)
+static char *wcache_make_sidlist(TALLOC_CTX *mem_ctx, uint32_t num_sids,
+                                const struct dom_sid *sids)
+{
+       uint32_t i;
+       char *sidlist;
+
+       sidlist = talloc_strdup(mem_ctx, "");
+       if (sidlist == NULL) {
+               return NULL;
+       }
+       for (i=0; i<num_sids; i++) {
+               fstring tmp;
+               sidlist = talloc_asprintf_append_buffer(
+                       sidlist, "/%s", sid_to_fstring(tmp, &sids[i]));
+               if (sidlist == NULL) {
+                       return NULL;
+               }
+       }
+       return sidlist;
+}
+
+NTSTATUS wcache_lookup_useraliases(struct winbindd_domain *domain,
+                                  TALLOC_CTX *mem_ctx, uint32_t num_sids,
+                                  const struct dom_sid *sids,
+                                  uint32_t *pnum_aliases, uint32_t **paliases)
 {
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
+       uint32_t num_aliases;
+       uint32_t *aliases;
        NTSTATUS status;
-       char *sidlist = talloc_strdup(mem_ctx, "");
+       char *sidlist;
        int i;
 
-       if (!cache->tdb)
-               goto do_query;
+       if (cache->tdb == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
 
        if (num_sids == 0) {
-               *num_aliases = 0;
-               *alias_rids = NULL;
+               *pnum_aliases = 0;
+               *paliases = NULL;
                return NT_STATUS_OK;
        }
 
        /* We need to cache indexed by the whole list of SIDs, the aliases
         * resulting might come from any of the SIDs. */
 
-       for (i=0; i<num_sids; i++) {
-               fstring tmp;
-               sidlist = talloc_asprintf(mem_ctx, "%s/%s", sidlist,
-                                         sid_to_fstring(tmp, &sids[i]));
-               if (sidlist == NULL)
-                       return NT_STATUS_NO_MEMORY;
+       sidlist = wcache_make_sidlist(talloc_tos(), num_sids, sids);
+       if (sidlist == NULL) {
+               return NT_STATUS_NO_MEMORY;
        }
 
        centry = wcache_fetch(cache, domain, "UA%s", sidlist);
+       TALLOC_FREE(sidlist);
+       if (centry == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
 
-       if (!centry)
-               goto do_query;
-
-       *num_aliases = centry_uint32(centry);
-       *alias_rids = NULL;
-
-       if (*num_aliases) {
-               (*alias_rids) = TALLOC_ARRAY(mem_ctx, uint32, *num_aliases);
-
-               if ((*alias_rids) == NULL) {
-                       centry_free(centry);
-                       return NT_STATUS_NO_MEMORY;
-               }
-       } else {
-               (*alias_rids) = NULL;
+       num_aliases = centry_uint32(centry);
+       aliases = talloc_array(mem_ctx, uint32_t, num_aliases);
+       if (aliases == NULL) {
+               centry_free(centry);
+               return NT_STATUS_NO_MEMORY;
        }
 
-       for (i=0; i<(*num_aliases); i++)
-               (*alias_rids)[i] = centry_uint32(centry);
+       for (i=0; i<num_aliases; i++) {
+               aliases[i] = centry_uint32(centry);
+       }
 
        status = centry->status;
 
@@ -1899,9 +2476,31 @@ static NTSTATUS lookup_useraliases(struct winbindd_domain *domain,
                  "status %s\n", domain->name, nt_errstr(status)));
 
        centry_free(centry);
+
+       *pnum_aliases = num_aliases;
+       *paliases = aliases;
+
        return status;
+}
+
+static NTSTATUS lookup_useraliases(struct winbindd_domain *domain,
+                                  TALLOC_CTX *mem_ctx,
+                                  uint32 num_sids, const struct dom_sid *sids,
+                                  uint32 *num_aliases, uint32 **alias_rids)
+{
+       struct cache_entry *centry = NULL;
+       NTSTATUS status;
+       char *sidlist;
+       int i;
+       bool old_status;
+
+       old_status = domain->online;
+       status = wcache_lookup_useraliases(domain, mem_ctx, num_sids, sids,
+                                          num_aliases, alias_rids);
+       if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
+               return status;
+       }
 
- do_query:
        (*num_aliases) = 0;
        (*alias_rids) = NULL;
 
@@ -1911,12 +2510,34 @@ static NTSTATUS lookup_useraliases(struct winbindd_domain *domain,
        DEBUG(10,("lookup_usergroups: [Cached] - doing backend query for info "
                  "for domain %s\n", domain->name ));
 
+       sidlist = wcache_make_sidlist(talloc_tos(), num_sids, sids);
+       if (sidlist == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
        status = domain->backend->lookup_useraliases(domain, mem_ctx,
                                                     num_sids, sids,
                                                     num_aliases, alias_rids);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (!domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       NTSTATUS cache_status;
+                       cache_status = wcache_lookup_useraliases(domain, mem_ctx, num_sids,
+                                                                sids, num_aliases, alias_rids);
+                       return cache_status;
+               }
+       }
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        centry = centry_start(domain, status);
        if (!centry)
                goto skip_save;
@@ -1930,61 +2551,97 @@ static NTSTATUS lookup_useraliases(struct winbindd_domain *domain,
        return status;
 }
 
-
-static NTSTATUS lookup_groupmem(struct winbindd_domain *domain,
+NTSTATUS wcache_lookup_groupmem(struct winbindd_domain *domain,
                                TALLOC_CTX *mem_ctx,
-                               const DOM_SID *group_sid, uint32 *num_names, 
-                               DOM_SID **sid_mem, char ***names, 
-                               uint32 **name_types)
+                               const struct dom_sid *group_sid,
+                               uint32_t *num_names,
+                               struct dom_sid **sid_mem, char ***names,
+                               uint32_t **name_types)
 {
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
        NTSTATUS status;
        unsigned int i;
-       fstring sid_string;
+       char *sid_string;
 
-       if (!cache->tdb)
-               goto do_query;
+       if (cache->tdb == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
 
-       centry = wcache_fetch(cache, domain, "GM/%s",
-                             sid_to_fstring(sid_string, group_sid));
-       if (!centry)
-               goto do_query;
+       sid_string = sid_string_tos(group_sid);
+       if (sid_string == NULL) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       centry = wcache_fetch(cache, domain, "GM/%s", sid_string);
+       TALLOC_FREE(sid_string);
+       if (centry == NULL) {
+               return NT_STATUS_NOT_FOUND;
+       }
+
+       *sid_mem = NULL;
+       *names = NULL;
+       *name_types = NULL;
 
        *num_names = centry_uint32(centry);
-       
-       if (*num_names == 0)
-               goto do_cached;
+       if (*num_names == 0) {
+               centry_free(centry);
+               return NT_STATUS_OK;
+       }
 
-       (*sid_mem) = TALLOC_ARRAY(mem_ctx, DOM_SID, *num_names);
-       (*names) = TALLOC_ARRAY(mem_ctx, char *, *num_names);
-       (*name_types) = TALLOC_ARRAY(mem_ctx, uint32, *num_names);
+       *sid_mem = talloc_array(mem_ctx, struct dom_sid, *num_names);
+       *names = talloc_array(mem_ctx, char *, *num_names);
+       *name_types = talloc_array(mem_ctx, uint32, *num_names);
 
-       if (! (*sid_mem) || ! (*names) || ! (*name_types)) {
-               smb_panic_fn("lookup_groupmem out of memory");
+       if ((*sid_mem == NULL) || (*names == NULL) || (*name_types == NULL)) {
+               TALLOC_FREE(*sid_mem);
+               TALLOC_FREE(*names);
+               TALLOC_FREE(*name_types);
+               centry_free(centry);
+               return NT_STATUS_NO_MEMORY;
        }
 
        for (i=0; i<(*num_names); i++) {
-               centry_sid(centry, mem_ctx, &(*sid_mem)[i]);
+               centry_sid(centry, &(*sid_mem)[i]);
                (*names)[i] = centry_string(centry, mem_ctx);
                (*name_types)[i] = centry_uint32(centry);
        }
 
-do_cached:     
        status = centry->status;
 
-       DEBUG(10,("lookup_groupmem: [Cached] - cached info for domain %s status: %s\n",
-               domain->name, nt_errstr(status)));
+       DEBUG(10,("lookup_groupmem: [Cached] - cached info for domain %s "
+                 "status: %s\n", domain->name, nt_errstr(status)));
 
        centry_free(centry);
        return status;
+}
+
+static NTSTATUS lookup_groupmem(struct winbindd_domain *domain,
+                               TALLOC_CTX *mem_ctx,
+                               const struct dom_sid *group_sid,
+                               enum lsa_SidType type,
+                               uint32 *num_names,
+                               struct dom_sid **sid_mem, char ***names,
+                               uint32 **name_types)
+{
+       struct cache_entry *centry = NULL;
+       NTSTATUS status;
+       unsigned int i;
+       fstring sid_string;
+       bool old_status;
+
+       old_status = domain->online;
+       status = wcache_lookup_groupmem(domain, mem_ctx, group_sid, num_names,
+                                       sid_mem, names, name_types);
+       if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
+               return status;
+       }
 
-do_query:
        (*num_names) = 0;
        (*sid_mem) = NULL;
        (*names) = NULL;
        (*name_types) = NULL;
-       
+
        /* Return status value returned by seq number check */
 
        if (!NT_STATUS_IS_OK(domain->last_status))
@@ -1993,11 +2650,30 @@ do_query:
        DEBUG(10,("lookup_groupmem: [Cached] - doing backend query for info for domain %s\n",
                domain->name ));
 
-       status = domain->backend->lookup_groupmem(domain, mem_ctx, group_sid, num_names, 
+       status = domain->backend->lookup_groupmem(domain, mem_ctx, group_sid,
+                                                 type, num_names,
                                                  sid_mem, names, name_types);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (!domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       NTSTATUS cache_status;
+                       cache_status = wcache_lookup_groupmem(domain, mem_ctx, group_sid,
+                                                             num_names, sid_mem, names,
+                                                             name_types);
+                       return cache_status;
+               }
+       }
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        centry = centry_start(domain, status);
        if (!centry)
                goto skip_save;
@@ -2029,72 +2705,101 @@ static NTSTATUS sequence_number(struct winbindd_domain *domain, uint32 *seq)
  * Guenther */
 static NTSTATUS trusted_domains(struct winbindd_domain *domain,
                                TALLOC_CTX *mem_ctx,
-                               uint32 *num_domains,
-                               char ***names,
-                               char ***alt_names,
-                               DOM_SID **dom_sids)
+                               struct netr_DomainTrustList *trusts)
 {
-       struct winbind_cache *cache = get_cache(domain);
-       struct cache_entry *centry = NULL;
        NTSTATUS status;
+       struct winbind_cache *cache;
+       struct winbindd_tdc_domain *dom_list = NULL;
+       size_t num_domains = 0;
+       bool retval = false;
        int i;
-       if (!cache->tdb)
+       bool old_status;
+
+       old_status = domain->online;
+       trusts->count = 0;
+       trusts->array = NULL;
+
+       cache = get_cache(domain);
+       if (!cache || !cache->tdb) {
                goto do_query;
-       centry = wcache_fetch(cache, domain, "TRUSTDOMS/%s", domain->name);
-       
-       if (!centry) {
-               goto do_query;
        }
-       *num_domains = centry_uint32(centry);
-       
-       if (*num_domains) {
-               (*names)        = TALLOC_ARRAY(mem_ctx, char *, *num_domains);
-               (*alt_names)    = TALLOC_ARRAY(mem_ctx, char *, *num_domains);
-               (*dom_sids)     = TALLOC_ARRAY(mem_ctx, DOM_SID, *num_domains);
-               if (! (*dom_sids) || ! (*names) || ! (*alt_names)) {
-                       smb_panic_fn("trusted_domains out of memory");
-               }
-       } else {
-               (*names) = NULL;
-               (*alt_names) = NULL;
-               (*dom_sids) = NULL;
+
+       if (domain->online) {
+               goto do_query;
        }
-       for (i=0; i<(*num_domains); i++) {
-               (*names)[i] = centry_string(centry, mem_ctx);
-               (*alt_names)[i] = centry_string(centry, mem_ctx);
-               centry_sid(centry, mem_ctx, &(*dom_sids)[i]);
+
+       retval = wcache_tdc_fetch_list(&dom_list, &num_domains);
+       if (!retval || !num_domains || !dom_list) {
+               TALLOC_FREE(dom_list);
+               goto do_query;
        }
 
-       status = centry->status;
-       DEBUG(10,("trusted_domains: [Cached] - cached info for domain %s (%d trusts) status: %s\n",
-               domain->name, *num_domains, nt_errstr(status) ));
-       centry_free(centry);
-       return status;
+do_fetch_cache:
+       trusts->array = TALLOC_ZERO_ARRAY(mem_ctx, struct netr_DomainTrust, num_domains);
+       if (!trusts->array) {
+               TALLOC_FREE(dom_list);
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       for (i = 0; i < num_domains; i++) {
+               struct netr_DomainTrust *trust;
+               struct dom_sid *sid;
+               struct winbindd_domain *dom;
+
+               dom = find_domain_from_name_noinit(dom_list[i].domain_name);
+               if (dom && dom->internal) {
+                       continue;
+               }
+
+               trust = &trusts->array[trusts->count];
+               trust->netbios_name = talloc_strdup(trusts->array, dom_list[i].domain_name);
+               trust->dns_name = talloc_strdup(trusts->array, dom_list[i].dns_name);
+               sid = talloc(trusts->array, struct dom_sid);
+               if (!trust->netbios_name || !trust->dns_name ||
+                       !sid) {
+                       TALLOC_FREE(dom_list);
+                       TALLOC_FREE(trusts->array);
+                       return NT_STATUS_NO_MEMORY;
+               }
+
+               trust->trust_flags = dom_list[i].trust_flags;
+               trust->trust_attributes = dom_list[i].trust_attribs;
+               trust->trust_type = dom_list[i].trust_type;
+               sid_copy(sid, &dom_list[i].sid);
+               trust->sid = sid;
+               trusts->count++;
+       }
+
+       TALLOC_FREE(dom_list);
+       return NT_STATUS_OK;
+
 do_query:
-       (*num_domains) = 0;
-       (*dom_sids) = NULL;
-       (*names) = NULL;
-       (*alt_names) = NULL;
        /* Return status value returned by seq number check */
 
        if (!NT_STATUS_IS_OK(domain->last_status))
                return domain->last_status;
-       
+
        DEBUG(10,("trusted_domains: [Cached] - doing backend query for info for domain %s\n",
                domain->name ));
-       status = domain->backend->trusted_domains(domain, mem_ctx, num_domains,
-                                               names, alt_names, dom_sids);
 
+       status = domain->backend->trusted_domains(domain, mem_ctx, trusts);
+
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (!domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       retval = wcache_tdc_fetch_list(&dom_list, &num_domains);
+                       if (retval && num_domains && dom_list) {
+                               TALLOC_FREE(trusts->array);
+                               trusts->count = 0;
+                               goto do_fetch_cache;
+                       }
+               }
+       }
        /* no trusts gives NT_STATUS_NO_MORE_ENTRIES resetting to NT_STATUS_OK
         * so that the generic centry handling still applies correctly -
         * Guenther*/
@@ -2102,33 +2807,6 @@ do_query:
        if (!NT_STATUS_IS_ERR(status)) {
                status = NT_STATUS_OK;
        }
-
-
-#if 0    /* Disabled as we want the trust dom list to be managed by
-           the main parent and always to make the query.  --jerry */
-
-       /* and save it */
-       refresh_sequence_number(domain, false);
-       centry = centry_start(domain, status);
-       if (!centry)
-               goto skip_save;
-
-       centry_put_uint32(centry, *num_domains);
-
-       for (i=0; i<(*num_domains); i++) {
-               centry_put_string(centry, (*names)[i]);
-               centry_put_string(centry, (*alt_names)[i]);
-               centry_put_sid(centry, &(*dom_sids)[i]);
-       }
-       
-       centry_end(centry, "TRUSTDOMS/%s", domain->name);
-       centry_free(centry);
-skip_save:
-#endif
-
        return status;
 }      
 
@@ -2140,7 +2818,9 @@ static NTSTATUS lockout_policy(struct winbindd_domain *domain,
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
        NTSTATUS status;
+       bool old_status;
 
+       old_status = domain->online;
        if (!cache->tdb)
                goto do_query;
 
@@ -2149,6 +2829,7 @@ static NTSTATUS lockout_policy(struct winbindd_domain *domain,
        if (!centry)
                goto do_query;
 
+do_fetch_cache:
        policy->lockout_duration = centry_nttime(centry);
        policy->lockout_window = centry_nttime(centry);
        policy->lockout_threshold = centry_uint16(centry);
@@ -2174,8 +2855,26 @@ do_query:
 
        status = domain->backend->lockout_policy(domain, mem_ctx, policy);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (cache->tdb &&
+                       !domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       centry = wcache_fetch(cache, domain, "LOC_POL/%s", domain->name);
+                       if (centry) {
+                               goto do_fetch_cache;
+                       }
+               }
+       }
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        wcache_save_lockout_policy(domain, status, policy);
 
        return status;
@@ -2189,7 +2888,9 @@ static NTSTATUS password_policy(struct winbindd_domain *domain,
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
        NTSTATUS status;
+       bool old_status;
 
+       old_status = domain->online;
        if (!cache->tdb)
                goto do_query;
 
@@ -2198,6 +2899,7 @@ static NTSTATUS password_policy(struct winbindd_domain *domain,
        if (!centry)
                goto do_query;
 
+do_fetch_cache:
        policy->min_password_length = centry_uint16(centry);
        policy->password_history_length = centry_uint16(centry);
        policy->password_properties = centry_uint32(centry);
@@ -2225,8 +2927,26 @@ do_query:
 
        status = domain->backend->password_policy(domain, mem_ctx, policy);
 
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+               NT_STATUS_EQUAL(status, NT_STATUS_DOMAIN_CONTROLLER_NOT_FOUND)) {
+               if (!domain->internal && old_status) {
+                       set_domain_offline(domain);
+               }
+               if (cache->tdb &&
+                       !domain->internal &&
+                       !domain->online &&
+                       old_status) {
+                       centry = wcache_fetch(cache, domain, "PWD_POL/%s", domain->name);
+                       if (centry) {
+                               goto do_fetch_cache;
+                       }
+               }
+       }
        /* and save it */
        refresh_sequence_number(domain, false);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
+       }
        wcache_save_password_policy(domain, status, policy);
 
        return status;
@@ -2250,6 +2970,8 @@ static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf,
 void wcache_invalidate_samlogon(struct winbindd_domain *domain, 
                                struct netr_SamInfo3 *info3)
 {
+        struct dom_sid sid;
+        fstring key_str, sid_string;
        struct winbind_cache *cache;
 
        /* dont clear cached U/SID and UG/SID entries when we want to logon
@@ -2263,7 +2985,25 @@ void wcache_invalidate_samlogon(struct winbindd_domain *domain,
                return;
 
        cache = get_cache(domain);
-       netsamlogon_clear_cached_user(cache->tdb, info3);
+
+        if (!cache->tdb) {
+                return;
+        }
+
+       sid_compose(&sid, info3->base.domain_sid, info3->base.rid);
+
+       /* Clear U/SID cache entry */
+       fstr_sprintf(key_str, "U/%s", sid_to_fstring(sid_string, &sid));
+       DEBUG(10, ("wcache_invalidate_samlogon: clearing %s\n", key_str));
+       tdb_delete(cache->tdb, string_tdb_data(key_str));
+
+       /* Clear UG/SID cache entry */
+       fstr_sprintf(key_str, "UG/%s", sid_to_fstring(sid_string, &sid));
+       DEBUG(10, ("wcache_invalidate_samlogon: clearing %s\n", key_str));
+       tdb_delete(cache->tdb, string_tdb_data(key_str));
+
+       /* Samba/winbindd never needs this. */
+       netsamlogon_clear_cached_user(info3);
 }
 
 bool wcache_invalidate_cache(void)
@@ -2286,6 +3026,39 @@ bool wcache_invalidate_cache(void)
        return true;
 }
 
+bool wcache_invalidate_cache_noinit(void)
+{
+       struct winbindd_domain *domain;
+
+       for (domain = domain_list(); domain; domain = domain->next) {
+               struct winbind_cache *cache;
+
+               /* Skip uninitialized domains. */
+               if (!domain->initialized && !domain->internal) {
+                       continue;
+               }
+
+               cache = get_cache(domain);
+
+               DEBUG(10, ("wcache_invalidate_cache: invalidating cache "
+                          "entries for %s\n", domain->name));
+               if (cache) {
+                       if (cache->tdb) {
+                               tdb_traverse(cache->tdb, traverse_fn, NULL);
+                               /*
+                                * Flushing cache has nothing to with domains.
+                                * return here if we successfully flushed once.
+                                * To avoid unnecessary traversing the cache.
+                                */
+                               return true;
+                       } else {
+                               return false;
+                       }
+               }
+       }
+       return true;
+}
+
 bool init_wcache(void)
 {
        if (wcache == NULL) {
@@ -2297,9 +3070,10 @@ bool init_wcache(void)
                return true;
 
        /* when working offline we must not clear the cache on restart */
-       wcache->tdb = tdb_open_log(lock_path("winbindd_cache.tdb"),
+       wcache->tdb = tdb_open_log(cache_path("winbindd_cache.tdb"),
                                WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE, 
-                               lp_winbind_offline_logon() ? TDB_DEFAULT : (TDB_DEFAULT | TDB_CLEAR_IF_FIRST), 
+                               TDB_INCOMPATIBLE_HASH |
+                                       (lp_winbind_offline_logon() ? TDB_DEFAULT : (TDB_DEFAULT | TDB_CLEAR_IF_FIRST)),
                                O_RDWR|O_CREAT, 0600);
 
        if (wcache->tdb == NULL) {
@@ -2340,242 +3114,86 @@ bool initialize_winbindd_cache(void)
                tdb_close(wcache->tdb);
                wcache->tdb = NULL;
 
-               if (unlink(lock_path("winbindd_cache.tdb")) == -1) {
+               if (unlink(cache_path("winbindd_cache.tdb")) == -1) {
                        DEBUG(0,("initialize_winbindd_cache: unlink %s failed %s ",
-                               lock_path("winbindd_cache.tdb"),
+                               cache_path("winbindd_cache.tdb"),
                                strerror(errno) ));
                        return false;
                }
                if (!init_wcache()) {
                        DEBUG(0,("initialize_winbindd_cache: re-initialization "
                                        "init_wcache failed.\n"));
-                       return false;
-               }
-
-               /* Write the version. */
-               if (!tdb_store_uint32(wcache->tdb, WINBINDD_CACHE_VERSION_KEYSTR, WINBINDD_CACHE_VERSION)) {
-                       DEBUG(0,("initialize_winbindd_cache: version number store failed %s\n",
-                               tdb_errorstr(wcache->tdb) ));
-                       return false;
-               }
-       }
-
-       tdb_close(wcache->tdb);
-       wcache->tdb = NULL;
-       return true;
-}
-
-void close_winbindd_cache(void)
-{
-       if (!wcache) {
-               return;
-       }
-       if (wcache->tdb) {
-               tdb_close(wcache->tdb);
-               wcache->tdb = NULL;
-       }
-}
-
-void cache_store_response(pid_t pid, struct winbindd_response *response)
-{
-       fstring key_str;
-
-       if (!init_wcache())
-               return;
-
-       DEBUG(10, ("Storing response for pid %d, len %d\n",
-                  pid, response->length));
-
-       fstr_sprintf(key_str, "DR/%d", pid);
-       if (tdb_store(wcache->tdb, string_tdb_data(key_str), 
-                     make_tdb_data((uint8 *)response, sizeof(*response)),
-                     TDB_REPLACE) == -1)
-               return;
-
-       if (response->length == sizeof(*response))
-               return;
-
-       /* There's extra data */
-
-       DEBUG(10, ("Storing extra data: len=%d\n",
-                  (int)(response->length - sizeof(*response))));
-
-       fstr_sprintf(key_str, "DE/%d", pid);
-       if (tdb_store(wcache->tdb, string_tdb_data(key_str),
-                     make_tdb_data((uint8 *)response->extra_data.data,
-                                   response->length - sizeof(*response)),
-                     TDB_REPLACE) == 0)
-               return;
-
-       /* We could not store the extra data, make sure the tdb does not
-        * contain a main record with wrong dangling extra data */
-
-       fstr_sprintf(key_str, "DR/%d", pid);
-       tdb_delete(wcache->tdb, string_tdb_data(key_str));
-
-       return;
-}
-
-bool cache_retrieve_response(pid_t pid, struct winbindd_response * response)
-{
-       TDB_DATA data;
-       fstring key_str;
-
-       if (!init_wcache())
-               return false;
-
-       DEBUG(10, ("Retrieving response for pid %d\n", pid));
-
-       fstr_sprintf(key_str, "DR/%d", pid);
-       data = tdb_fetch(wcache->tdb, string_tdb_data(key_str));
-
-       if (data.dptr == NULL)
-               return false;
-
-       if (data.dsize != sizeof(*response))
-               return false;
-
-       memcpy(response, data.dptr, data.dsize);
-       SAFE_FREE(data.dptr);
-
-       if (response->length == sizeof(*response)) {
-               response->extra_data.data = NULL;
-               return true;
-       }
-
-       /* There's extra data */
-
-       DEBUG(10, ("Retrieving extra data length=%d\n",
-                  (int)(response->length - sizeof(*response))));
-
-       fstr_sprintf(key_str, "DE/%d", pid);
-       data = tdb_fetch(wcache->tdb, string_tdb_data(key_str));
-
-       if (data.dptr == NULL) {
-               DEBUG(0, ("Did not find extra data\n"));
-               return false;
-       }
+                       return false;
+               }
 
-       if (data.dsize != (response->length - sizeof(*response))) {
-               DEBUG(0, ("Invalid extra data length: %d\n", (int)data.dsize));
-               SAFE_FREE(data.dptr);
-               return false;
+               /* Write the version. */
+               if (!tdb_store_uint32(wcache->tdb, WINBINDD_CACHE_VERSION_KEYSTR, WINBINDD_CACHE_VERSION)) {
+                       DEBUG(0,("initialize_winbindd_cache: version number store failed %s\n",
+                               tdb_errorstr(wcache->tdb) ));
+                       return false;
+               }
        }
 
-       dump_data(11, (uint8 *)data.dptr, data.dsize);
-
-       response->extra_data.data = data.dptr;
+       tdb_close(wcache->tdb);
+       wcache->tdb = NULL;
        return true;
 }
 
-void cache_cleanup_response(pid_t pid)
+void close_winbindd_cache(void)
 {
-       fstring key_str;
-
-       if (!init_wcache())
+       if (!wcache) {
                return;
-
-       fstr_sprintf(key_str, "DR/%d", pid);
-       tdb_delete(wcache->tdb, string_tdb_data(key_str));
-
-       fstr_sprintf(key_str, "DE/%d", pid);
-       tdb_delete(wcache->tdb, string_tdb_data(key_str));
-
-       return;
+       }
+       if (wcache->tdb) {
+               tdb_close(wcache->tdb);
+               wcache->tdb = NULL;
+       }
 }
 
-
-bool lookup_cached_sid(TALLOC_CTX *mem_ctx, const DOM_SID *sid,
+bool lookup_cached_sid(TALLOC_CTX *mem_ctx, const struct dom_sid *sid,
                       char **domain_name, char **name,
                       enum lsa_SidType *type)
 {
        struct winbindd_domain *domain;
-       struct winbind_cache *cache;
-       struct cache_entry *centry = NULL;
        NTSTATUS status;
-       fstring tmp;
 
        domain = find_lookup_domain_from_sid(sid);
        if (domain == NULL) {
                return false;
        }
-
-       cache = get_cache(domain);
-
-       if (cache->tdb == NULL) {
-               return false;
-       }
-
-       centry = wcache_fetch(cache, domain, "SN/%s",
-                             sid_to_fstring(tmp, sid));
-       if (centry == NULL) {
-               return false;
-       }
-
-       if (NT_STATUS_IS_OK(centry->status)) {
-               *type = (enum lsa_SidType)centry_uint32(centry);
-               *domain_name = centry_string(centry, mem_ctx);
-               *name = centry_string(centry, mem_ctx);
-       }
-
-       status = centry->status;
-       centry_free(centry);
+       status = wcache_sid_to_name(domain, sid, mem_ctx, domain_name, name,
+                                   type);
        return NT_STATUS_IS_OK(status);
 }
 
-bool lookup_cached_name(TALLOC_CTX *mem_ctx,
-                       const char *domain_name,
+bool lookup_cached_name(const char *domain_name,
                        const char *name,
-                       DOM_SID *sid,
+                       struct dom_sid *sid,
                        enum lsa_SidType *type)
 {
        struct winbindd_domain *domain;
-       struct winbind_cache *cache;
-       struct cache_entry *centry = NULL;
        NTSTATUS status;
-       fstring uname;
-       bool original_online_state;     
+       bool original_online_state;
 
        domain = find_lookup_domain_from_name(domain_name);
        if (domain == NULL) {
                return false;
        }
 
-       cache = get_cache(domain);
-
-       if (cache->tdb == NULL) {
-               return false;
-       }
-
-       fstrcpy(uname, name);
-       strupper_m(uname);
-       
        /* If we are doing a cached logon, temporarily set the domain
           offline so the cache won't expire the entry */
-       
+
        original_online_state = domain->online;
        domain->online = false;
-       centry = wcache_fetch(cache, domain, "NS/%s/%s", domain_name, uname);
+       status = wcache_name_to_sid(domain, domain_name, name, sid, type);
        domain->online = original_online_state;
-       
-       if (centry == NULL) {
-               return false;
-       }
-
-       if (NT_STATUS_IS_OK(centry->status)) {
-               *type = (enum lsa_SidType)centry_uint32(centry);
-               centry_sid(centry, mem_ctx, sid);
-       }
 
-       status = centry->status;
-       centry_free(centry);
-       
        return NT_STATUS_IS_OK(status);
 }
 
 void cache_name2sid(struct winbindd_domain *domain, 
                    const char *domain_name, const char *name,
-                   enum lsa_SidType type, const DOM_SID *sid)
+                   enum lsa_SidType type, const struct dom_sid *sid)
 {
        refresh_sequence_number(domain, false);
        wcache_save_name_to_sid(domain, NT_STATUS_OK, domain_name, name,
@@ -2620,13 +3238,15 @@ void wcache_flush_cache(void)
                tdb_close(wcache->tdb);
                wcache->tdb = NULL;
        }
-       if (opt_nocache)
+       if (!winbindd_use_cache()) {
                return;
+       }
 
        /* when working offline we must not clear the cache on restart */
-       wcache->tdb = tdb_open_log(lock_path("winbindd_cache.tdb"),
+       wcache->tdb = tdb_open_log(cache_path("winbindd_cache.tdb"),
                                WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE, 
-                               lp_winbind_offline_logon() ? TDB_DEFAULT : (TDB_DEFAULT | TDB_CLEAR_IF_FIRST), 
+                               TDB_INCOMPATIBLE_HASH |
+                               (lp_winbind_offline_logon() ? TDB_DEFAULT : (TDB_DEFAULT | TDB_CLEAR_IF_FIRST)),
                                O_RDWR|O_CREAT, 0600);
 
        if (!wcache->tdb) {
@@ -2689,17 +3309,17 @@ static int traverse_fn_get_credlist(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DAT
                }
 
                ZERO_STRUCTP(cred);
-               
+
                /* save a copy of the key */
-               
+
                fstrcpy(cred->name, (const char *)kbuf.dptr);           
                DLIST_ADD(wcache_cred_list, cred);
        }
-       
+
        return 0;
 }
 
-NTSTATUS wcache_remove_oldest_cached_creds(struct winbindd_domain *domain, const DOM_SID *sid) 
+NTSTATUS wcache_remove_oldest_cached_creds(struct winbindd_domain *domain, const struct dom_sid *sid)
 {
        struct winbind_cache *cache = get_cache(domain);
        NTSTATUS status;
@@ -2712,7 +3332,7 @@ NTSTATUS wcache_remove_oldest_cached_creds(struct winbindd_domain *domain, const
 
        /* we possibly already have an entry */
        if (sid && NT_STATUS_IS_OK(wcache_cached_creds_exist(domain, sid))) {
-       
+
                fstring key_str, tmp;
 
                DEBUG(11,("we already have an entry, deleting that\n"));
@@ -2745,7 +3365,7 @@ NTSTATUS wcache_remove_oldest_cached_creds(struct winbindd_domain *domain, const
                        status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
                        goto done;
                }
-       
+
                t = IVAL(data.dptr, 0);
                SAFE_FREE(data.dptr);
 
@@ -2775,7 +3395,7 @@ NTSTATUS wcache_remove_oldest_cached_creds(struct winbindd_domain *domain, const
 done:
        SAFE_FREE(wcache_cred_list);
        SAFE_FREE(oldest);
-       
+
        return status;
 }
 
@@ -2900,8 +3520,8 @@ static int validate_ns(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
 
        (void)centry_uint32(centry);
        if (NT_STATUS_IS_OK(centry->status)) {
-               DOM_SID sid;
-               (void)centry_sid(centry, mem_ctx, &sid);
+               struct dom_sid sid;
+               (void)centry_sid(centry, &sid);
        }
 
        centry_free(centry);
@@ -2940,7 +3560,7 @@ static int validate_u(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
                      struct tdb_validation_status *state)
 {
        struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
-       DOM_SID sid;
+       struct dom_sid sid;
 
        if (!centry) {
                return 1;
@@ -2951,8 +3571,8 @@ static int validate_u(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
        (void)centry_string(centry, mem_ctx);
        (void)centry_string(centry, mem_ctx);
        (void)centry_uint32(centry);
-       (void)centry_sid(centry, mem_ctx, &sid);
-       (void)centry_sid(centry, mem_ctx, &sid);
+       (void)centry_sid(centry, &sid);
+       (void)centry_sid(centry, &sid);
 
        centry_free(centry);
 
@@ -3048,13 +3668,13 @@ static int validate_ul(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
        num_entries = (int32)centry_uint32(centry);
 
        for (i=0; i< num_entries; i++) {
-               DOM_SID sid;
+               struct dom_sid sid;
                (void)centry_string(centry, mem_ctx);
                (void)centry_string(centry, mem_ctx);
                (void)centry_string(centry, mem_ctx);
                (void)centry_string(centry, mem_ctx);
-               (void)centry_sid(centry, mem_ctx, &sid);
-               (void)centry_sid(centry, mem_ctx, &sid);
+               (void)centry_sid(centry, &sid);
+               (void)centry_sid(centry, &sid);
        }
 
        centry_free(centry);
@@ -3077,7 +3697,7 @@ static int validate_gl(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
        }
 
        num_entries = centry_uint32(centry);
-       
+
        for (i=0; i< num_entries; i++) {
                (void)centry_string(centry, mem_ctx);
                (void)centry_string(centry, mem_ctx);
@@ -3106,8 +3726,8 @@ static int validate_ug(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
        num_groups = centry_uint32(centry);
 
        for (i=0; i< num_groups; i++) {
-               DOM_SID sid;
-               centry_sid(centry, mem_ctx, &sid);
+               struct dom_sid sid;
+               centry_sid(centry, &sid);
        }
 
        centry_free(centry);
@@ -3157,8 +3777,8 @@ static int validate_gm(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
        num_names = centry_uint32(centry);
 
        for (i=0; i< num_names; i++) {
-               DOM_SID sid;
-               centry_sid(centry, mem_ctx, &sid);
+               struct dom_sid sid;
+               centry_sid(centry, &sid);
                (void)centry_string(centry, mem_ctx);
                (void)centry_uint32(centry);
        }
@@ -3204,31 +3824,68 @@ static int validate_de(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
        return 0;
 }
 
-static int validate_trustdoms(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
-                             struct tdb_validation_status *state)
+static int validate_pwinfo(TALLOC_CTX *mem_ctx, const char *keystr,
+                          TDB_DATA dbuf, struct tdb_validation_status *state)
 {
        struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
-       int32 num_domains, i;
 
        if (!centry) {
                return 1;
        }
 
-       num_domains = centry_uint32(centry);
-       
-       for (i=0; i< num_domains; i++) {
-               DOM_SID sid;
-               (void)centry_string(centry, mem_ctx);
-               (void)centry_string(centry, mem_ctx);
-               (void)centry_sid(centry, mem_ctx, &sid);
+       (void)centry_string(centry, mem_ctx);
+       (void)centry_string(centry, mem_ctx);
+       (void)centry_string(centry, mem_ctx);
+       (void)centry_uint32(centry);
+
+       centry_free(centry);
+
+       if (!(state->success)) {
+               return 1;
+       }
+       DEBUG(10,("validate_pwinfo: %s ok\n", keystr));
+       return 0;
+}
+
+static int validate_nss_an(TALLOC_CTX *mem_ctx, const char *keystr,
+                          TDB_DATA dbuf,
+                          struct tdb_validation_status *state)
+{
+       struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
+
+       if (!centry) {
+               return 1;
+       }
+
+       (void)centry_string( centry, mem_ctx );
+
+       centry_free(centry);
+
+       if (!(state->success)) {
+               return 1;
+       }
+       DEBUG(10,("validate_pwinfo: %s ok\n", keystr));
+       return 0;
+}
+
+static int validate_nss_na(TALLOC_CTX *mem_ctx, const char *keystr,
+                          TDB_DATA dbuf,
+                          struct tdb_validation_status *state)
+{
+       struct cache_entry *centry = create_centry_validate(keystr, dbuf, state);
+
+       if (!centry) {
+               return 1;
        }
 
+       (void)centry_string( centry, mem_ctx );
+
        centry_free(centry);
 
        if (!(state->success)) {
                return 1;
        }
-       DEBUG(10,("validate_trustdoms: %s ok\n", keystr));
+       DEBUG(10,("validate_pwinfo: %s ok\n", keystr));
        return 0;
 }
 
@@ -3263,6 +3920,16 @@ static int validate_offline(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA db
        return 0;
 }
 
+static int validate_ndr(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
+                       struct tdb_validation_status *state)
+{
+       /*
+        * Ignore validation for now. The proper way to do this is with a
+        * checksum. Just pure parsing does not really catch much.
+        */
+       return 0;
+}
+
 static int validate_cache_version(TALLOC_CTX *mem_ctx, const char *keystr, TDB_DATA dbuf,
                                  struct tdb_validation_status *state)
 {
@@ -3302,9 +3969,12 @@ struct key_val_struct {
        {"GM/", validate_gm},
        {"DR/", validate_dr},
        {"DE/", validate_de},
-       {"TRUSTDOMS/", validate_trustdoms},
+       {"NSS/PWINFO/", validate_pwinfo},
        {"TRUSTDOMCACHE/", validate_trustdomcache},
+       {"NSS/NA/", validate_nss_na},
+       {"NSS/AN/", validate_nss_an},
        {"WINBINDD_OFFLINE", validate_offline},
+       {"NDR/", validate_ndr},
        {WINBINDD_CACHE_VERSION_KEYSTR, validate_cache_version},
        {NULL, NULL}
 };
@@ -3317,12 +3987,17 @@ struct key_val_struct {
 static int cache_traverse_validate_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, void *state)
 {
        int i;
+       unsigned int max_key_len = 1024;
        struct tdb_validation_status *v_state = (struct tdb_validation_status *)state;
 
        /* Paranoia check. */
-       if (kbuf.dsize > 1024) {
-               DEBUG(0,("cache_traverse_validate_fn: key length too large (%u) > 1024\n\n",
-                               (unsigned int)kbuf.dsize ));
+       if (strncmp("UA/", (const char *)kbuf.dptr, 3) == 0) {
+               max_key_len = 1024 * 1024;
+       }
+       if (kbuf.dsize > max_key_len) {
+               DEBUG(0, ("cache_traverse_validate_fn: key length too large: "
+                         "(%u) > (%u)\n\n",
+                         (unsigned int)kbuf.dsize, (unsigned int)max_key_len));
                return 1;
        }
 
@@ -3380,7 +4055,7 @@ static void validate_panic(const char *const why)
 int winbindd_validate_cache(void)
 {
        int ret = -1;
-       const char *tdb_path = lock_path("winbindd_cache.tdb");
+       const char *tdb_path = cache_path("winbindd_cache.tdb");
        TDB_CONTEXT *tdb = NULL;
 
        DEBUG(10, ("winbindd_validate_cache: replacing panic function\n"));
@@ -3389,6 +4064,7 @@ int winbindd_validate_cache(void)
 
        tdb = tdb_open_log(tdb_path, 
                           WINBINDD_CACHE_TDB_DEFAULT_HASH_SIZE,
+                          TDB_INCOMPATIBLE_HASH |
                           ( lp_winbind_offline_logon() 
                             ? TDB_DEFAULT 
                             : TDB_DEFAULT | TDB_CLEAR_IF_FIRST ),
@@ -3422,7 +4098,7 @@ done:
 int winbindd_validate_cache_nobackup(void)
 {
        int ret = -1;
-       const char *tdb_path = lock_path("winbindd_cache.tdb");
+       const char *tdb_path = cache_path("winbindd_cache.tdb");
 
        DEBUG(10, ("winbindd_validate_cache: replacing panic function\n"));
        smb_panic_fn = validate_panic;
@@ -3445,6 +4121,20 @@ int winbindd_validate_cache_nobackup(void)
        return ret;
 }
 
+bool winbindd_cache_validate_and_initialize(void)
+{
+       close_winbindd_cache();
+
+       if (lp_winbind_offline_logon()) {
+               if (winbindd_validate_cache() < 0) {
+                       DEBUG(0, ("winbindd cache tdb corrupt and no backup "
+                                 "could be restored.\n"));
+               }
+       }
+
+       return initialize_winbindd_cache();
+}
+
 /*********************************************************************
  ********************************************************************/
 
@@ -3456,19 +4146,19 @@ static bool add_wbdomain_to_tdc_array( struct winbindd_domain *new_dom,
        size_t idx;
        int i;
        bool set_only = false;
-       
+
        /* don't allow duplicates */
 
        idx = *num_domains;
        list = *domains;
-       
+
        for ( i=0; i< (*num_domains); i++ ) {
                if ( strequal( new_dom->name, list[i].domain_name ) ) {
                        DEBUG(10,("add_wbdomain_to_tdc_array: Found existing record for %s\n",
                                  new_dom->name));
                        idx = i;
                        set_only = true;
-                       
+
                        break;
                }
        }
@@ -3493,8 +4183,11 @@ static bool add_wbdomain_to_tdc_array( struct winbindd_domain *new_dom,
        list[idx].domain_name = talloc_strdup( list, new_dom->name );
        list[idx].dns_name = talloc_strdup( list, new_dom->alt_name );
 
-       if ( !is_null_sid( &new_dom->sid ) )
+       if ( !is_null_sid( &new_dom->sid ) ) {
                sid_copy( &list[idx].sid, &new_dom->sid );
+       } else {
+               sid_copy(&list[idx].sid, &global_sid_NULL);
+       }
 
        if ( new_dom->domain_flags != 0x0 )
                list[idx].trust_flags = new_dom->domain_flags;  
@@ -3504,7 +4197,7 @@ static bool add_wbdomain_to_tdc_array( struct winbindd_domain *new_dom,
 
        if ( new_dom->domain_trust_attribs != 0x0 )
                list[idx].trust_attribs = new_dom->domain_trust_attribs;
-       
+
        if ( !set_only ) {
                *domains = list;
                *num_domains = idx + 1; 
@@ -3520,16 +4213,17 @@ static TDB_DATA make_tdc_key( const char *domain_name )
 {
        char *keystr = NULL;
        TDB_DATA key = { NULL, 0 };
-       
+
        if ( !domain_name ) {
                DEBUG(5,("make_tdc_key: Keyname workgroup is NULL!\n"));
                return key;
        }
-              
-               
-       asprintf( &keystr, "TRUSTDOMCACHE/%s", domain_name );
+
+       if (asprintf( &keystr, "TRUSTDOMCACHE/%s", domain_name ) == -1) {
+               return key;
+       }
        key = string_term_tdb_data(keystr);
-       
+
        return key;     
 }
 
@@ -3547,12 +4241,12 @@ static int pack_tdc_domains( struct winbindd_tdc_domain *domains,
 
        DEBUG(10,("pack_tdc_domains: Packing %d trusted domains\n",
                  (int)num_domains));
-       
+
        buflen = 0;
-       
+
  again: 
        len = 0;
-       
+
        /* Store the number of array items first */
        len += tdb_pack( buffer+len, buflen-len, "d", 
                         num_domains );
@@ -3567,7 +4261,7 @@ static int pack_tdc_domains( struct winbindd_tdc_domain *domains,
                                  domains[i].domain_name,
                                  domains[i].dns_name ? domains[i].dns_name : "UNKNOWN" ));
                }
-               
+
                len += tdb_pack( buffer+len, buflen-len, "fffddd",
                                 domains[i].domain_name,
                                 domains[i].dns_name,
@@ -3589,7 +4283,7 @@ static int pack_tdc_domains( struct winbindd_tdc_domain *domains,
        }
 
        *buf = buffer;  
-       
+
  done: 
        return buflen;  
 }
@@ -3619,7 +4313,7 @@ static size_t unpack_tdc_domains( unsigned char *buf, int buflen,
                DEBUG(0,("unpack_tdc_domains: Failed to talloc() domain list!\n"));
                return 0;               
        }
-       
+
        for ( i=0; i<num_domains; i++ ) {
                len += tdb_unpack( buf+len, buflen-len, "fffddd",
                                   domain_name,
@@ -3639,7 +4333,7 @@ static size_t unpack_tdc_domains( unsigned char *buf, int buflen,
                          "SID %s, flags = 0x%x, attribs = 0x%x, type = 0x%x\n",
                          domain_name, dns_name, sid_string,
                          flags, attribs, type));
-               
+
                list[i].domain_name = talloc_strdup( list, domain_name );
                list[i].dns_name = talloc_strdup( list, dns_name );
                if ( !string_to_sid( &(list[i].sid), sid_string ) ) {                   
@@ -3652,7 +4346,7 @@ static size_t unpack_tdc_domains( unsigned char *buf, int buflen,
        }
 
        *domains = list;
-       
+
        return num_domains;
 }
 
@@ -3664,30 +4358,30 @@ static bool wcache_tdc_store_list( struct winbindd_tdc_domain *domains, size_t n
        TDB_DATA key = make_tdc_key( lp_workgroup() );   
        TDB_DATA data = { NULL, 0 };
        int ret;
-       
+
        if ( !key.dptr )
                return false;
-       
+
        /* See if we were asked to delete the cache entry */
 
        if ( !domains ) {
                ret = tdb_delete( wcache->tdb, key );
                goto done;
        }
-       
+
        data.dsize = pack_tdc_domains( domains, num_domains, &data.dptr );
-       
+
        if ( !data.dptr ) {
                ret = -1;
                goto done;
        }
-               
+
        ret = tdb_store( wcache->tdb, key, data, 0 );
 
  done:
        SAFE_FREE( data.dptr );
        SAFE_FREE( key.dptr );
-       
+
        return ( ret != -1 );   
 }
 
@@ -3704,18 +4398,18 @@ bool wcache_tdc_fetch_list( struct winbindd_tdc_domain **domains, size_t *num_do
 
        if ( !key.dptr )
                return false;
-       
+
        data = tdb_fetch( wcache->tdb, key );
 
        SAFE_FREE( key.dptr );
-       
+
        if ( !data.dptr ) 
                return false;
-       
+
        *num_domains = unpack_tdc_domains( data.dptr, data.dsize, domains );
 
        SAFE_FREE( data.dptr );
-       
+
        if ( !*domains )
                return false;
 
@@ -3738,15 +4432,15 @@ bool wcache_tdc_add_domain( struct winbindd_domain *domain )
                  domain->domain_flags,
                  domain->domain_trust_attribs,
                  domain->domain_type));        
-       
+
        if ( !init_wcache() ) {
                return false;
        }
-       
+
        /* fetch the list */
 
        wcache_tdc_fetch_list( &dom_list, &num_domains );
-       
+
        /* add the new domain */
 
        if ( !add_wbdomain_to_tdc_array( domain, &dom_list, &num_domains ) ) {
@@ -3758,13 +4452,13 @@ bool wcache_tdc_add_domain( struct winbindd_domain *domain )
        if ( !wcache_tdc_store_list( dom_list, num_domains ) ) {
                goto done;              
        }
-       
+
        /* Success */
 
        ret = true;
  done:
        TALLOC_FREE( dom_list );
-       
+
        return ret;     
 }
 
@@ -3783,22 +4477,22 @@ struct winbindd_tdc_domain * wcache_tdc_fetch_domain( TALLOC_CTX *ctx, const cha
        if ( !init_wcache() ) {
                return false;
        }
-       
+
        /* fetch the list */
 
        wcache_tdc_fetch_list( &dom_list, &num_domains );
-       
+
        for ( i=0; i<num_domains; i++ ) {
                if ( strequal(name, dom_list[i].domain_name) ||
                     strequal(name, dom_list[i].dns_name) )
                {
                        DEBUG(10,("wcache_tdc_fetch_domain: Found domain %s\n",
                                  name));
-                       
+
                        d = TALLOC_P( ctx, struct winbindd_tdc_domain );
                        if ( !d )
                                break;                  
-                       
+
                        d->domain_name = talloc_strdup( d, dom_list[i].domain_name );
                        d->dns_name = talloc_strdup( d, dom_list[i].dns_name );
                        sid_copy( &d->sid, &dom_list[i].sid );
@@ -3811,7 +4505,7 @@ struct winbindd_tdc_domain * wcache_tdc_fetch_domain( TALLOC_CTX *ctx, const cha
        }
 
         TALLOC_FREE( dom_list );
-       
+
        return d;       
 }
 
@@ -3825,7 +4519,7 @@ void wcache_tdc_clear( void )
                return;
 
        wcache_tdc_store_list( NULL, 0 );
-       
+
        return; 
 }
 
@@ -3835,7 +4529,7 @@ void wcache_tdc_clear( void )
 
 static void wcache_save_user_pwinfo(struct winbindd_domain *domain, 
                                    NTSTATUS status,
-                                   const DOM_SID *user_sid,
+                                   const struct dom_sid *user_sid,
                                    const char *homedir,
                                    const char *shell,
                                    const char *gecos,
@@ -3851,7 +4545,7 @@ static void wcache_save_user_pwinfo(struct winbindd_domain *domain,
        centry_put_string( centry, shell );
        centry_put_string( centry, gecos );
        centry_put_uint32( centry, gid );
-       
+
        centry_end(centry, "NSS/PWINFO/%s", sid_to_fstring(tmp, user_sid) );
 
        DEBUG(10,("wcache_save_user_pwinfo: %s\n", sid_string_dbg(user_sid) ));
@@ -3859,12 +4553,14 @@ static void wcache_save_user_pwinfo(struct winbindd_domain *domain,
        centry_free(centry);
 }
 
+#ifdef HAVE_ADS
+
 NTSTATUS nss_get_info_cached( struct winbindd_domain *domain, 
-                             const DOM_SID *user_sid,
+                             const struct dom_sid *user_sid,
                              TALLOC_CTX *ctx,
                              ADS_STRUCT *ads, LDAPMessage *msg,
-                             char **homedir, char **shell, char **gecos,
-                             gid_t *p_gid)
+                             const char **homedir, const char **shell,
+                             const char **gecos, gid_t *p_gid)
 {
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
@@ -3876,7 +4572,7 @@ NTSTATUS nss_get_info_cached( struct winbindd_domain *domain,
 
        centry = wcache_fetch(cache, domain, "NSS/PWINFO/%s",
                              sid_to_fstring(tmp, user_sid));
-       
+
        if (!centry)
                goto do_query;
 
@@ -3893,11 +4589,18 @@ NTSTATUS nss_get_info_cached( struct winbindd_domain *domain,
        return NT_STATUS_OK;
 
 do_query:
-       
+
        nt_status = nss_get_info( domain->name, user_sid, ctx, ads, msg, 
                                  homedir, shell, gecos, p_gid );
 
+       DEBUG(10, ("nss_get_info returned %s\n", nt_errstr(nt_status)));
+
        if ( NT_STATUS_IS_OK(nt_status) ) {
+               DEBUG(10, ("result:\n\thomedir = '%s'\n", *homedir));
+                DEBUGADD(10, ("\tshell = '%s'\n", *shell));
+                DEBUGADD(10, ("\tgecos = '%s'\n", *gecos));
+                DEBUGADD(10, ("\tgid = '%u'\n", (unsigned int)*p_gid));
+
                wcache_save_user_pwinfo( domain, nt_status, user_sid,
                                         *homedir, *shell, *gecos, *p_gid );
        }       
@@ -3911,6 +4614,7 @@ do_query:
        return nt_status;       
 }
 
+#endif
 
 /* the cache backend methods are exposed via this structure */
 struct winbindd_methods cache_methods = {
@@ -3930,3 +4634,142 @@ struct winbindd_methods cache_methods = {
        password_policy,
        trusted_domains
 };
+
+static bool wcache_ndr_key(TALLOC_CTX *mem_ctx, char *domain_name,
+                          uint32_t opnum, const DATA_BLOB *req,
+                          TDB_DATA *pkey)
+{
+       char *key;
+       size_t keylen;
+
+       key = talloc_asprintf(mem_ctx, "NDR/%s/%d/", domain_name, (int)opnum);
+       if (key == NULL) {
+               return false;
+       }
+       keylen = talloc_get_size(key) - 1;
+
+       key = talloc_realloc(mem_ctx, key, char, keylen + req->length);
+       if (key == NULL) {
+               return false;
+       }
+       memcpy(key + keylen, req->data, req->length);
+
+       pkey->dptr = (uint8_t *)key;
+       pkey->dsize = talloc_get_size(key);
+       return true;
+}
+
+static bool wcache_opnum_cacheable(uint32_t opnum)
+{
+       switch (opnum) {
+       case NDR_WBINT_PING:
+       case NDR_WBINT_QUERYSEQUENCENUMBER:
+       case NDR_WBINT_ALLOCATEUID:
+       case NDR_WBINT_ALLOCATEGID:
+       case NDR_WBINT_CHECKMACHINEACCOUNT:
+       case NDR_WBINT_CHANGEMACHINEACCOUNT:
+       case NDR_WBINT_PINGDC:
+               return false;
+       }
+       return true;
+}
+
+bool wcache_fetch_ndr(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
+                     uint32_t opnum, const DATA_BLOB *req, DATA_BLOB *resp)
+{
+       TDB_DATA key, data;
+       bool ret = false;
+
+       if (!wcache_opnum_cacheable(opnum) ||
+           is_my_own_sam_domain(domain) ||
+           is_builtin_domain(domain)) {
+               return false;
+       }
+
+       if (wcache->tdb == NULL) {
+               return false;
+       }
+
+       if (!wcache_ndr_key(talloc_tos(), domain->name, opnum, req, &key)) {
+               return false;
+       }
+       data = tdb_fetch(wcache->tdb, key);
+       TALLOC_FREE(key.dptr);
+
+       if (data.dptr == NULL) {
+               return false;
+       }
+       if (data.dsize < 4) {
+               goto fail;
+       }
+
+       if (!is_domain_offline(domain)) {
+               uint32_t entry_seqnum, dom_seqnum, last_check;
+
+               if (!wcache_fetch_seqnum(domain->name, &dom_seqnum,
+                                        &last_check)) {
+                       goto fail;
+               }
+               entry_seqnum = IVAL(data.dptr, 0);
+               if (entry_seqnum != dom_seqnum) {
+                       DEBUG(10, ("Entry has wrong sequence number: %d\n",
+                                  (int)entry_seqnum));
+                       goto fail;
+               }
+       }
+
+       resp->data = (uint8_t *)talloc_memdup(mem_ctx, data.dptr + 4,
+                                             data.dsize - 4);
+       if (resp->data == NULL) {
+               DEBUG(10, ("talloc failed\n"));
+               goto fail;
+       }
+       resp->length = data.dsize - 4;
+
+       ret = true;
+fail:
+       SAFE_FREE(data.dptr);
+       return ret;
+}
+
+void wcache_store_ndr(struct winbindd_domain *domain, uint32_t opnum,
+                     const DATA_BLOB *req, const DATA_BLOB *resp)
+{
+       TDB_DATA key, data;
+       uint32_t dom_seqnum, last_check;
+
+       if (!wcache_opnum_cacheable(opnum) ||
+           is_my_own_sam_domain(domain) ||
+           is_builtin_domain(domain)) {
+               return;
+       }
+
+       if (wcache->tdb == NULL) {
+               return;
+       }
+
+       if (!wcache_fetch_seqnum(domain->name, &dom_seqnum, &last_check)) {
+               DEBUG(10, ("could not fetch seqnum for domain %s\n",
+                          domain->name));
+               return;
+       }
+
+       if (!wcache_ndr_key(talloc_tos(), domain->name, opnum, req, &key)) {
+               return;
+       }
+
+       data.dsize = resp->length + 4;
+       data.dptr = talloc_array(key.dptr, uint8_t, data.dsize);
+       if (data.dptr == NULL) {
+               goto done;
+       }
+
+       SIVAL(data.dptr, 0, dom_seqnum);
+       memcpy(data.dptr+4, resp->data, resp->length);
+
+       tdb_store(wcache->tdb, key, data, 0);
+
+done:
+       TALLOC_FREE(key.dptr);
+       return;
+}