s3-registry: Check return code of push_reg_sz().
[kai/samba.git] / source3 / winbindd / winbindd_cache.c
index 65bbe75cd7f68057f43c69fbe9dae24a67650b7b..e3406a5858f2a1f74ed775df8b173a5d4b150651 100644 (file)
 */
 
 #include "includes.h"
+#include "system/filesys.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"
+#include "passdb/machine_sid.h"
+#include "util_tdb.h"
 
 #undef DBGC_CLASS
 #define DBGC_CLASS DBGC_WINBIND
 
-#define WINBINDD_CACHE_VERSION 1
+#define WINBINDD_CACHE_VER1 1 /* initial db version */
+#define WINBINDD_CACHE_VER2 2 /* second version with timeouts for NDR entries */
+
+#define WINBINDD_CACHE_VERSION WINBINDD_CACHE_VER2
 #define WINBINDD_CACHE_VERSION_KEYSTR "WINBINDD_CACHE_VERSION"
 
 extern struct winbindd_methods reconnect_methods;
@@ -40,6 +49,7 @@ extern struct winbindd_methods reconnect_methods;
 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.
@@ -49,8 +59,6 @@ extern struct winbindd_methods builtin_passdb_methods;
 
 static const char *non_centry_keys[] = {
        "SEQNUM/",
-       "DR/",
-       "DE/",
        "WINBINDD_OFFLINE",
        WINBINDD_CACHE_VERSION_KEYSTR,
        NULL
@@ -92,6 +100,7 @@ struct winbind_cache {
 struct cache_entry {
        NTSTATUS status;
        uint32 sequence_number;
+       uint64_t timeout;
        uint8 *data;
        uint32 len, ofs;
 };
@@ -102,35 +111,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)
 {
@@ -142,6 +122,13 @@ static struct winbind_cache *get_cache(struct winbindd_domain *domain)
                domain->backend = &builtin_passdb_methods;
                domain->initialized = True;
        }
+
+       if (strequal(domain->name, get_global_sam_name()) &&
+           sid_check_is_our_sam(&domain->sid)) {
+               domain->backend = &sam_passdb_methods;
+               domain->initialized = True;
+       }
+
        if ( !domain->initialized ) {
                init_dc_connection( domain );
        }
@@ -222,6 +209,21 @@ static bool centry_check_bytes(struct cache_entry *centry, size_t nbytes)
        return true;
 }
 
+/*
+  pull a uint64_t from a cache entry
+*/
+static uint64_t centry_uint64_t(struct cache_entry *centry)
+{
+       uint64_t ret;
+
+       if (!centry_check_bytes(centry, 8)) {
+               smb_panic_fn("centry_uint64_t");
+       }
+       ret = BVAL(centry->data, centry->ofs);
+       centry->ofs += 8;
+       return ret;
+}
+
 /*
   pull a uint32 from a cache entry 
 */
@@ -246,7 +248,7 @@ static uint16 centry_uint16(struct cache_entry *centry)
        if (!centry_check_bytes(centry, 2)) {
                smb_panic_fn("centry_uint16");
        }
-       ret = CVAL(centry->data, centry->ofs);
+       ret = SVAL(centry->data, centry->ofs);
        centry->ofs += 2;
        return ret;
 }
@@ -276,7 +278,7 @@ static NTTIME centry_nttime(struct cache_entry *centry)
        }
        ret = IVAL(centry->data, centry->ofs);
        centry->ofs += 4;
-       ret += (uint64_t)IVAL(centry->data, centry->ofs) << 32;
+       ret += (uint64)IVAL(centry->data, centry->ofs) << 32;
        centry->ofs += 4;
        return ret;
 }
@@ -308,7 +310,7 @@ static char *centry_string(struct cache_entry *centry, TALLOC_CTX *mem_ctx)
                smb_panic_fn("centry_string");
        }
 
-       ret = TALLOC_ARRAY(mem_ctx, char, len+1);
+       ret = talloc_array(mem_ctx, char, len+1);
        if (!ret) {
                smb_panic_fn("centry_string out of memory\n");
        }
@@ -338,7 +340,7 @@ static char *centry_hash16(struct cache_entry *centry, TALLOC_CTX *mem_ctx)
                return NULL;
        }
 
-       ret = TALLOC_ARRAY(mem_ctx, char, 16);
+       ret = talloc_array(mem_ctx, char, 16);
        if (!ret) {
                smb_panic_fn("centry_hash out of memory\n");
        }
@@ -483,9 +485,9 @@ bool wcache_store_seqnum(const char *domain_name, uint32_t seqnum,
        ret = tdb_store_bystring(wcache->tdb, key_str,
                                 make_tdb_data(buf, sizeof(buf)), TDB_REPLACE);
        TALLOC_FREE(key_str);
-       if (ret == -1) {
+       if (ret != 0) {
                DEBUG(10, ("tdb_store_bystring failed: %s\n",
-                          tdb_errorstr(wcache->tdb)));
+                          tdb_errorstr_compat(wcache->tdb)));
                TALLOC_FREE(key_str);
                return false;
        }
@@ -514,7 +516,7 @@ 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;
        }
 
@@ -614,9 +616,10 @@ static bool centry_expired(struct winbindd_domain *domain, const char *keystr, s
        }
 
        /* if the server is down or the cache entry is not older than the
-          current sequence number then it is OK */
-       if (wcache_server_down(domain) || 
-           centry->sequence_number == domain->sequence_number) {
+          current sequence number or it did not timeout then it is OK */
+       if (wcache_server_down(domain)
+           || ((centry->sequence_number == domain->sequence_number)
+               && (centry->timeout > time(NULL)))) {
                DEBUG(10,("centry_expired: Key %s for domain %s is good.\n",
                        keystr, domain->name ));
                return false;
@@ -636,7 +639,7 @@ static struct cache_entry *wcache_fetch_raw(char *kstr)
        TDB_DATA key;
 
        key = string_tdb_data(kstr);
-       data = tdb_fetch(wcache->tdb, key);
+       data = tdb_fetch_compat(wcache->tdb, key);
        if (!data.dptr) {
                /* a cache miss */
                return NULL;
@@ -647,19 +650,41 @@ static struct cache_entry *wcache_fetch_raw(char *kstr)
        centry->len = data.dsize;
        centry->ofs = 0;
 
-       if (centry->len < 8) {
+       if (centry->len < 16) {
                /* huh? corrupt cache? */
-               DEBUG(10,("wcache_fetch_raw: Corrupt cache for key %s (len < 8) ?\n", kstr));
+               DEBUG(10,("wcache_fetch_raw: Corrupt cache for key %s "
+                         "(len < 16)?\n", kstr));
                centry_free(centry);
                return NULL;
        }
 
        centry->status = centry_ntstatus(centry);
        centry->sequence_number = centry_uint32(centry);
+       centry->timeout = centry_uint64_t(centry);
 
        return centry;
 }
 
+static bool is_my_own_sam_domain(struct winbindd_domain *domain)
+{
+       if (strequal(domain->name, get_global_sam_name()) &&
+           sid_check_is_our_sam(&domain->sid)) {
+               return true;
+       }
+
+       return false;
+}
+
+static bool is_builtin_domain(struct winbindd_domain *domain)
+{
+       if (strequal(domain->name, "BUILTIN") &&
+           sid_check_is_builtin(&domain->sid)) {
+               return true;
+       }
+
+       return false;
+}
+
 /*
   fetch an entry from the cache, with a varargs key. auto-fetch the sequence
   number and return status
@@ -675,7 +700,9 @@ static struct cache_entry *wcache_fetch(struct winbind_cache *cache,
        char *kstr;
        struct cache_entry *centry;
 
-       if (!winbindd_use_cache()) {
+       if (!winbindd_use_cache() ||
+           is_my_own_sam_domain(domain) ||
+           is_builtin_domain(domain)) {
                return NULL;
        }
 
@@ -741,6 +768,16 @@ static void centry_expand(struct cache_entry *centry, uint32 len)
        }
 }
 
+/*
+  push a uint64_t into a centry
+*/
+static void centry_put_uint64_t(struct cache_entry *centry, uint64_t v)
+{
+       centry_expand(centry, 8);
+       SBVAL(centry->data, centry->ofs, v);
+       centry->ofs += 8;
+}
+
 /*
   push a uint32 into a centry 
 */
@@ -757,7 +794,7 @@ static void centry_put_uint32(struct cache_entry *centry, uint32 v)
 static void centry_put_uint16(struct cache_entry *centry, uint16 v)
 {
        centry_expand(centry, 2);
-       SIVAL(centry->data, centry->ofs, v);
+       SSVAL(centry->data, centry->ofs, v);
        centry->ofs += 2;
 }
 
@@ -807,7 +844,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));
@@ -862,8 +899,10 @@ struct cache_entry *centry_start(struct winbindd_domain *domain, NTSTATUS status
        centry->data = SMB_XMALLOC_ARRAY(uint8, centry->len);
        centry->ofs = 0;
        centry->sequence_number = domain->sequence_number;
+       centry->timeout = lp_winbind_cache_time() + time(NULL);
        centry_put_ntstatus(centry, status);
        centry_put_uint32(centry, centry->sequence_number);
+       centry_put_uint64_t(centry, centry->timeout);
        return centry;
 }
 
@@ -895,7 +934,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;
@@ -907,7 +946,7 @@ static void wcache_save_name_to_sid(struct winbindd_domain *domain,
        centry_put_uint32(centry, type);
        centry_put_sid(centry, sid);
        fstrcpy(uname, name);
-       strupper_m(uname);
+       (void)strupper_m(uname);
        centry_end(centry, "NS/%s/%s", domain_name, uname);
        DEBUG(10,("wcache_save_name_to_sid: %s\\%s -> %s (%s)\n", domain_name,
                  uname, sid_string_dbg(sid), nt_errstr(status)));
@@ -915,7 +954,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;
@@ -931,8 +970,8 @@ static void wcache_save_sid_to_name(struct winbindd_domain *domain, NTSTATUS sta
        }
 
        centry_end(centry, "SN/%s", sid_to_fstring(sid_string, sid));
-       DEBUG(10,("wcache_save_sid_to_name: %s -> %s (%s)\n", sid_string, 
-                 name, nt_errstr(status)));
+       DEBUG(10,("wcache_save_sid_to_name: %s -> %s\\%s (%s)\n", sid_string,
+                 domain_name, name, nt_errstr(status)));
        centry_free(centry);
 }
 
@@ -1025,7 +1064,7 @@ static void wcache_save_username_alias(struct winbindd_domain *domain,
        centry_put_string( centry, alias );
 
        fstrcpy(uname, name);
-       strupper_m(uname);
+       (void)strupper_m(uname);
        centry_end(centry, "NSS/NA/%s", uname);
 
        DEBUG(10,("wcache_save_username_alias: %s -> %s\n", name, alias ));
@@ -1046,7 +1085,7 @@ static void wcache_save_alias_username(struct winbindd_domain *domain,
        centry_put_string( centry, name );
 
        fstrcpy(uname, alias);
-       strupper_m(uname);
+       (void)strupper_m(uname);
        centry_end(centry, "NSS/AN/%s", uname);
 
        DEBUG(10,("wcache_save_alias_username: %s -> %s\n", alias, name ));
@@ -1074,7 +1113,10 @@ NTSTATUS resolve_username_to_alias( TALLOC_CTX *mem_ctx,
 
        if ( (upper_name = SMB_STRDUP(name)) == NULL )
                return NT_STATUS_NO_MEMORY;
-       strupper_m(upper_name);
+       if (!strupper_m(upper_name)) {
+               SAFE_FREE(upper_name);
+               return NT_STATUS_INVALID_PARAMETER;
+       }
 
        centry = wcache_fetch(cache, domain, "NSS/NA/%s", upper_name);
 
@@ -1149,7 +1191,10 @@ NTSTATUS resolve_alias_to_username( TALLOC_CTX *mem_ctx,
 
        if ( (upper_name = SMB_STRDUP(alias)) == NULL )
                return NT_STATUS_NO_MEMORY;
-       strupper_m(upper_name);
+       if (!strupper_m(upper_name)) {
+               SAFE_FREE(upper_name);
+               return NT_STATUS_INVALID_PARAMETER;
+       }
 
        centry = wcache_fetch(cache, domain, "NSS/AN/%s", upper_name);
 
@@ -1212,7 +1257,7 @@ do_query:
        return status;
 }
 
-NTSTATUS wcache_cached_creds_exist(struct winbindd_domain *domain, const DOM_SID *sid)
+NTSTATUS wcache_cached_creds_exist(struct winbindd_domain *domain, const struct dom_sid *sid)
 {
        struct winbind_cache *cache = get_cache(domain);
        TDB_DATA data;
@@ -1233,7 +1278,7 @@ NTSTATUS wcache_cached_creds_exist(struct winbindd_domain *domain, const DOM_SID
 
        fstr_sprintf(key_str, "CRED/%s", sid_to_fstring(tmp, sid));
 
-       data = tdb_fetch(cache->tdb, string_tdb_data(key_str));
+       data = tdb_fetch_compat(cache->tdb, string_tdb_data(key_str));
        if (!data.dptr) {
                return NT_STATUS_OBJECT_NAME_NOT_FOUND;
        }
@@ -1247,14 +1292,13 @@ 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)
 {
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
        NTSTATUS status;
-       time_t t;
        uint32 rid;
        fstring tmp;
 
@@ -1281,7 +1325,12 @@ NTSTATUS wcache_get_creds(struct winbindd_domain *domain,
                return NT_STATUS_OBJECT_NAME_NOT_FOUND;
        }
 
-       t = centry_time(centry);
+       /*
+        * We don't use the time element at this moment,
+        * but we have to consume it, so that we don't
+        * neet to change the disk format of the cache.
+        */
+       (void)centry_time(centry);
 
        /* In the salted case this isn't actually the nt_hash itself,
           but the MD5 of the salt + nt_hash. Let the caller
@@ -1327,8 +1376,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;
@@ -1380,6 +1428,7 @@ static NTSTATUS query_user_list(struct winbindd_domain *domain,
        struct cache_entry *centry = NULL;
        NTSTATUS status;
        unsigned int i, retry;
+       bool old_status = domain->online;
 
        if (!cache->tdb)
                goto do_query;
@@ -1388,12 +1437,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, struct wbint_userinfo, *num_entries);
+       (*info) = talloc_array(mem_ctx, struct wbint_userinfo, *num_entries);
        if (! (*info)) {
                smb_panic_fn("query_user_list out of memory");
        }
@@ -1448,12 +1498,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;
@@ -1491,13 +1573,15 @@ skip_save:
 static NTSTATUS enum_dom_groups(struct winbindd_domain *domain,
                                TALLOC_CTX *mem_ctx,
                                uint32 *num_entries, 
-                               struct acct_info **info)
+                               struct wb_acct_info **info)
 {
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
        NTSTATUS status;
        unsigned int i;
+       bool old_status;
 
+       old_status = domain->online;
        if (!cache->tdb)
                goto do_query;
 
@@ -1505,12 +1589,13 @@ 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;
 
-       (*info) = TALLOC_ARRAY(mem_ctx, struct acct_info, *num_entries);
+       (*info) = talloc_array(mem_ctx, struct wb_acct_info, *num_entries);
        if (! (*info)) {
                smb_panic_fn("enum_dom_groups out of memory");
        }
@@ -1543,8 +1628,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;
@@ -1565,13 +1668,15 @@ skip_save:
 static NTSTATUS enum_local_groups(struct winbindd_domain *domain,
                                TALLOC_CTX *mem_ctx,
                                uint32 *num_entries, 
-                               struct acct_info **info)
+                               struct wb_acct_info **info)
 {
        struct winbind_cache *cache = get_cache(domain);
        struct cache_entry *centry = NULL;
        NTSTATUS status;
        unsigned int i;
+       bool old_status;
 
+       old_status = domain->online;
        if (!cache->tdb)
                goto do_query;
 
@@ -1579,12 +1684,13 @@ 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;
 
-       (*info) = TALLOC_ARRAY(mem_ctx, struct acct_info, *num_entries);
+       (*info) = talloc_array(mem_ctx, struct wb_acct_info, *num_entries);
        if (! (*info)) {
                smb_panic_fn("enum_dom_groups out of memory");
        }
@@ -1627,8 +1733,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;
@@ -1690,10 +1814,13 @@ static NTSTATUS name_to_sid(struct winbindd_domain *domain,
                            const char *domain_name,
                            const char *name,
                            uint32_t flags,
-                           DOM_SID *sid,
+                           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)) {
@@ -1719,6 +1846,19 @@ static NTSTATUS name_to_sid(struct winbindd_domain *domain,
        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);
 
@@ -1728,8 +1868,10 @@ static NTSTATUS name_to_sid(struct winbindd_domain *domain,
 
                /* Only save the reverse mapping if this was not a UPN */
                if (!strchr(name, '@')) {
-                       strupper_m(CONST_DISCARD(char *,domain_name));
-                       strlower_m(CONST_DISCARD(char *,name));
+                       if (!strupper_m(discard_const_p(char, domain_name))) {
+                               return NT_STATUS_INVALID_PARAMETER;
+                       }
+                       (void)strlower_m(discard_const_p(char, name));
                        wcache_save_sid_to_name(domain, status, sid, domain_name, name, *type);
                }
        }
@@ -1783,13 +1925,15 @@ NTSTATUS wcache_sid_to_name(struct winbindd_domain *domain,
    given */
 static NTSTATUS sid_to_name(struct winbindd_domain *domain,
                            TALLOC_CTX *mem_ctx,
-                           const DOM_SID *sid,
+                           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)) {
@@ -1815,8 +1959,25 @@ static NTSTATUS sid_to_name(struct winbindd_domain *domain,
 
        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
@@ -1827,7 +1988,7 @@ static NTSTATUS sid_to_name(struct winbindd_domain *domain,
 
 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,
@@ -1839,7 +2000,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;
@@ -1852,8 +2015,8 @@ static NTSTATUS rids_to_names(struct winbindd_domain *domain,
                return NT_STATUS_OK;
        }
 
-       *names = TALLOC_ARRAY(mem_ctx, char *, num_rids);
-       *types = TALLOC_ARRAY(mem_ctx, enum lsa_SidType, num_rids);
+       *names = talloc_array(mem_ctx, char *, num_rids);
+       *types = talloc_array(mem_ctx, enum lsa_SidType, num_rids);
 
        if ((*names == NULL) || (*types == NULL)) {
                result = NT_STATUS_NO_MEMORY;
@@ -1863,7 +2026,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;
 
@@ -1895,7 +2058,8 @@ static NTSTATUS rids_to_names(struct winbindd_domain *domain,
 
                        (*names)[i] = centry_string(centry, *names);
 
-               } else if (NT_STATUS_EQUAL(centry->status, NT_STATUS_NONE_MAPPED)) {
+               } else if (NT_STATUS_EQUAL(centry->status, NT_STATUS_NONE_MAPPED)
+                          || NT_STATUS_EQUAL(centry->status, STATUS_SOME_UNMAPPED)) {
                        have_unmapped = true;
 
                } else {
@@ -1924,12 +2088,79 @@ 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;
@@ -1956,7 +2187,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])) {
@@ -2042,11 +2273,13 @@ NTSTATUS wcache_query_user(struct winbindd_domain *domain,
 /* Lookup user information from a rid */
 static NTSTATUS query_user(struct winbindd_domain *domain,
                           TALLOC_CTX *mem_ctx,
-                          const DOM_SID *user_sid,
+                          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;
@@ -2064,8 +2297,24 @@ static NTSTATUS query_user(struct winbindd_domain *domain,
 
        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;
@@ -2110,6 +2359,7 @@ NTSTATUS wcache_lookup_usergroups(struct winbindd_domain *domain,
        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;
        }
 
@@ -2132,14 +2382,16 @@ NTSTATUS wcache_lookup_usergroups(struct winbindd_domain *domain,
 /* Lookup groups a user is a member of. */
 static NTSTATUS 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 *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)) {
@@ -2159,11 +2411,28 @@ static NTSTATUS lookup_usergroups(struct winbindd_domain *domain,
 
        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;
@@ -2264,14 +2533,16 @@ NTSTATUS wcache_lookup_useraliases(struct winbindd_domain *domain,
 
 static NTSTATUS lookup_useraliases(struct winbindd_domain *domain,
                                   TALLOC_CTX *mem_ctx,
-                                  uint32 num_sids, const DOM_SID *sids,
+                                  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)) {
@@ -2296,8 +2567,25 @@ static NTSTATUS lookup_useraliases(struct winbindd_domain *domain,
                                                     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;
@@ -2349,7 +2637,7 @@ NTSTATUS wcache_lookup_groupmem(struct winbindd_domain *domain,
                return NT_STATUS_OK;
        }
 
-       *sid_mem = talloc_array(mem_ctx, DOM_SID, *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);
 
@@ -2378,17 +2666,19 @@ NTSTATUS wcache_lookup_groupmem(struct winbindd_domain *domain,
 
 static NTSTATUS lookup_groupmem(struct winbindd_domain *domain,
                                TALLOC_CTX *mem_ctx,
-                               const DOM_SID *group_sid,
+                               const struct dom_sid *group_sid,
                                enum lsa_SidType type,
                                uint32 *num_names,
-                               DOM_SID **sid_mem, char ***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)) {
@@ -2412,8 +2702,26 @@ static NTSTATUS lookup_groupmem(struct winbindd_domain *domain,
                                                  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;
@@ -2445,63 +2753,75 @@ 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;
+       bool old_status;
 
-       if (!cache->tdb)
-               goto do_query;
-
-       centry = wcache_fetch(cache, domain, "TRUSTDOMS/%s", domain->name);
+       old_status = domain->online;
+       trusts->count = 0;
+       trusts->array = NULL;
 
-       if (!centry) {
-               goto do_query;
+       cache = get_cache(domain);
+       if (!cache || !cache->tdb) {
+               goto do_query;
        }
 
-       *num_domains = centry_uint32(centry);
+       if (domain->online) {
+               goto do_query;
+       }
 
-       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);
+       retval = wcache_tdc_fetch_list(&dom_list, &num_domains);
+       if (!retval || !num_domains || !dom_list) {
+               TALLOC_FREE(dom_list);
+               goto do_query;
+       }
 
-               if (! (*dom_sids) || ! (*names) || ! (*alt_names)) {
-                       smb_panic_fn("trusted_domains out of memory");
-               }
-       } else {
-               (*names) = NULL;
-               (*alt_names) = NULL;
-               (*dom_sids) = NULL;
+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++) {
-               (*names)[i] = centry_string(centry, mem_ctx);
-               (*alt_names)[i] = centry_string(centry, mem_ctx);
-               if (!centry_sid(centry, &(*dom_sids)[i])) {
-                       sid_copy(&(*dom_sids)[i], &global_sid_NULL);
+       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;
                }
-       }
 
-       status = centry->status;
+               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;
+               }
 
-       DEBUG(10,("trusted_domains: [Cached] - cached info for domain %s (%d trusts) status: %s\n",
-               domain->name, *num_domains, nt_errstr(status) ));
+               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++;
+       }
 
-       centry_free(centry);
-       return status;
+       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))
@@ -2510,9 +2830,24 @@ do_query:
        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*/
@@ -2520,33 +2855,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;
 }      
 
@@ -2558,7 +2866,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;
 
@@ -2567,6 +2877,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);
@@ -2592,8 +2903,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;
@@ -2607,7 +2936,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;
 
@@ -2616,6 +2947,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);
@@ -2643,11 +2975,27 @@ 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)) {
-               wcache_save_password_policy(domain, status, policy);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
        }
+       wcache_save_password_policy(domain, status, policy);
 
        return status;
 }
@@ -2668,9 +3016,8 @@ static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf,
 /* Invalidate the getpwnam and getgroups entries for a winbindd domain */
 
 void wcache_invalidate_samlogon(struct winbindd_domain *domain, 
-                               struct netr_SamInfo3 *info3)
+                               const struct dom_sid *sid)
 {
-        DOM_SID sid;
         fstring key_str, sid_string;
        struct winbind_cache *cache;
 
@@ -2690,21 +3037,18 @@ void wcache_invalidate_samlogon(struct winbindd_domain *domain,
                 return;
         }
 
-       sid_copy(&sid, info3->base.domain_sid);
-       sid_append_rid(&sid, info3->base.rid);
-
        /* Clear U/SID cache entry */
-       fstr_sprintf(key_str, "U/%s", sid_to_fstring(sid_string, &sid));
+       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));
+       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);
+       netsamlogon_clear_cached_user(sid);
 }
 
 bool wcache_invalidate_cache(void)
@@ -2727,6 +3071,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) {
@@ -2738,9 +3115,10 @@ bool init_wcache(void)
                return true;
 
        /* when working offline we must not clear the cache on restart */
-       wcache->tdb = tdb_open_log(cache_path("winbindd_cache.tdb"),
+       wcache->tdb = tdb_open_log(state_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) {
@@ -2781,9 +3159,9 @@ bool initialize_winbindd_cache(void)
                tdb_close(wcache->tdb);
                wcache->tdb = NULL;
 
-               if (unlink(cache_path("winbindd_cache.tdb")) == -1) {
+               if (unlink(state_path("winbindd_cache.tdb")) == -1) {
                        DEBUG(0,("initialize_winbindd_cache: unlink %s failed %s ",
-                               cache_path("winbindd_cache.tdb"),
+                               state_path("winbindd_cache.tdb"),
                                strerror(errno) ));
                        return false;
                }
@@ -2796,7 +3174,7 @@ bool initialize_winbindd_cache(void)
                /* 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) ));
+                               tdb_errorstr_compat(wcache->tdb) ));
                        return false;
                }
        }
@@ -2817,7 +3195,7 @@ void close_winbindd_cache(void)
        }
 }
 
-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)
 {
@@ -2833,10 +3211,9 @@ bool lookup_cached_sid(TALLOC_CTX *mem_ctx, const DOM_SID *sid,
        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;
@@ -2861,7 +3238,7 @@ bool lookup_cached_name(TALLOC_CTX *mem_ctx,
 
 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,
@@ -2911,9 +3288,10 @@ void wcache_flush_cache(void)
        }
 
        /* when working offline we must not clear the cache on restart */
-       wcache->tdb = tdb_open_log(cache_path("winbindd_cache.tdb"),
+       wcache->tdb = tdb_open_log(state_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) {
@@ -2986,7 +3364,7 @@ static int traverse_fn_get_credlist(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DAT
        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;
@@ -3014,7 +3392,7 @@ NTSTATUS wcache_remove_oldest_cached_creds(struct winbindd_domain *domain, const
        ret = tdb_traverse(cache->tdb, traverse_fn_get_credlist, NULL);
        if (ret == 0) {
                return NT_STATUS_OK;
-       } else if ((ret == -1) || (wcache_cred_list == NULL)) {
+       } else if ((ret < 0) || (wcache_cred_list == NULL)) {
                return NT_STATUS_OBJECT_NAME_NOT_FOUND;
        }
 
@@ -3025,7 +3403,7 @@ NTSTATUS wcache_remove_oldest_cached_creds(struct winbindd_domain *domain, const
                TDB_DATA data;
                time_t t;
 
-               data = tdb_fetch(cache->tdb, string_tdb_data(cred->name));
+               data = tdb_fetch_compat(cache->tdb, string_tdb_data(cred->name));
                if (!data.dptr) {
                        DEBUG(10,("wcache_remove_oldest_cached_creds: entry for [%s] not found\n", 
                                cred->name));
@@ -3151,9 +3529,10 @@ static struct cache_entry *create_centry_validate(const char *kstr, TDB_DATA dat
        centry->len = data.dsize;
        centry->ofs = 0;
 
-       if (centry->len < 8) {
+       if (centry->len < 16) {
                /* huh? corrupt cache? */
-               DEBUG(0,("create_centry_validate: Corrupt cache for key %s (len < 8) ?\n", kstr));
+               DEBUG(0,("create_centry_validate: Corrupt cache for key %s "
+                        "(len < 16) ?\n", kstr));
                centry_free(centry);
                state->bad_entry = true;
                state->success = false;
@@ -3162,6 +3541,7 @@ static struct cache_entry *create_centry_validate(const char *kstr, TDB_DATA dat
 
        centry->status = NT_STATUS(centry_uint32(centry));
        centry->sequence_number = centry_uint32(centry);
+       centry->timeout = centry_uint64_t(centry);
        return centry;
 }
 
@@ -3187,7 +3567,7 @@ 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;
+               struct dom_sid sid;
                (void)centry_sid(centry, &sid);
        }
 
@@ -3227,7 +3607,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;
@@ -3335,7 +3715,7 @@ 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);
@@ -3393,7 +3773,7 @@ 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;
+               struct dom_sid sid;
                centry_sid(centry, &sid);
        }
 
@@ -3444,7 +3824,7 @@ 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;
+               struct dom_sid sid;
                centry_sid(centry, &sid);
                (void)centry_string(centry, mem_ctx);
                (void)centry_uint32(centry);
@@ -3556,34 +3936,6 @@ static int validate_nss_na(TALLOC_CTX *mem_ctx, const char *keystr,
        return 0;
 }
 
-static int validate_trustdoms(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, &sid);
-       }
-
-       centry_free(centry);
-
-       if (!(state->success)) {
-               return 1;
-       }
-       DEBUG(10,("validate_trustdoms: %s ok\n", keystr));
-       return 0;
-}
-
 static int validate_trustdomcache(TALLOC_CTX *mem_ctx, const char *keystr, 
                                  TDB_DATA dbuf,
                                  struct tdb_validation_status *state)
@@ -3665,7 +4017,6 @@ struct key_val_struct {
        {"DR/", validate_dr},
        {"DE/", validate_de},
        {"NSS/PWINFO/", validate_pwinfo},
-       {"TRUSTDOMS/", validate_trustdoms},
        {"TRUSTDOMCACHE/", validate_trustdomcache},
        {"NSS/NA/", validate_nss_na},
        {"NSS/AN/", validate_nss_an},
@@ -3743,6 +4094,70 @@ static void validate_panic(const char *const why)
        exit(47);
 }
 
+static int wbcache_update_centry_fn(TDB_CONTEXT *tdb,
+                                   TDB_DATA key,
+                                   TDB_DATA data,
+                                   void *state)
+{
+       uint64_t ctimeout;
+       TDB_DATA blob;
+
+       if (is_non_centry_key(key)) {
+               return 0;
+       }
+
+       if (data.dptr == NULL || data.dsize == 0) {
+               if (tdb_delete(tdb, key) < 0) {
+                       DEBUG(0, ("tdb_delete for [%s] failed!\n",
+                                 key.dptr));
+                       return 1;
+               }
+       }
+
+       /* add timeout to blob (uint64_t) */
+       blob.dsize = data.dsize + 8;
+
+       blob.dptr = SMB_XMALLOC_ARRAY(uint8_t, blob.dsize);
+       if (blob.dptr == NULL) {
+               return 1;
+       }
+       memset(blob.dptr, 0, blob.dsize);
+
+       /* copy status and seqnum */
+       memcpy(blob.dptr, data.dptr, 8);
+
+       /* add timeout */
+       ctimeout = lp_winbind_cache_time() + time(NULL);
+       SBVAL(blob.dptr, 8, ctimeout);
+
+       /* copy the rest */
+       memcpy(blob.dptr + 16, data.dptr + 8, data.dsize - 8);
+
+       if (tdb_store(tdb, key, blob, TDB_REPLACE) < 0) {
+               DEBUG(0, ("tdb_store to update [%s] failed!\n",
+                         key.dptr));
+               SAFE_FREE(blob.dptr);
+               return 1;
+       }
+
+       SAFE_FREE(blob.dptr);
+       return 0;
+}
+
+static bool wbcache_upgrade_v1_to_v2(TDB_CONTEXT *tdb)
+{
+       int rc;
+
+       DEBUG(1, ("Upgrade to version 2 of the winbindd_cache.tdb\n"));
+
+       rc = tdb_traverse(tdb, wbcache_update_centry_fn, NULL);
+       if (rc < 0) {
+               return false;
+       }
+
+       return true;
+}
+
 /***********************************************************************
  Try and validate every entry in the winbindd cache. If we fail here,
  delete the cache tdb and return non-zero.
@@ -3751,15 +4166,17 @@ static void validate_panic(const char *const why)
 int winbindd_validate_cache(void)
 {
        int ret = -1;
-       const char *tdb_path = cache_path("winbindd_cache.tdb");
+       const char *tdb_path = state_path("winbindd_cache.tdb");
        TDB_CONTEXT *tdb = NULL;
+       uint32_t vers_id;
+       bool ok;
 
        DEBUG(10, ("winbindd_validate_cache: replacing panic function\n"));
        smb_panic_fn = validate_panic;
 
-
        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 ),
@@ -3770,6 +4187,30 @@ int winbindd_validate_cache(void)
                          "error opening/initializing tdb\n"));
                goto done;
        }
+
+       /* Version check and upgrade code. */
+       if (!tdb_fetch_uint32(tdb, WINBINDD_CACHE_VERSION_KEYSTR, &vers_id)) {
+               DEBUG(10, ("Fresh database\n"));
+               tdb_store_uint32(tdb, WINBINDD_CACHE_VERSION_KEYSTR, WINBINDD_CACHE_VERSION);
+               vers_id = WINBINDD_CACHE_VERSION;
+       }
+
+       if (vers_id != WINBINDD_CACHE_VERSION) {
+               if (vers_id == WINBINDD_CACHE_VER1) {
+                       ok = wbcache_upgrade_v1_to_v2(tdb);
+                       if (!ok) {
+                               DEBUG(10, ("winbindd_validate_cache: upgrade to version 2 failed.\n"));
+                               unlink(tdb_path);
+                               goto done;
+                       }
+
+                       tdb_store_uint32(tdb,
+                                        WINBINDD_CACHE_VERSION_KEYSTR,
+                                        WINBINDD_CACHE_VERSION);
+                       vers_id = WINBINDD_CACHE_VER2;
+               }
+       }
+
        tdb_close(tdb);
 
        ret = tdb_validate_and_backup(tdb_path, cache_traverse_validate_fn);
@@ -3793,7 +4234,7 @@ done:
 int winbindd_validate_cache_nobackup(void)
 {
        int ret = -1;
-       const char *tdb_path = cache_path("winbindd_cache.tdb");
+       const char *tdb_path = state_path("winbindd_cache.tdb");
 
        DEBUG(10, ("winbindd_validate_cache: replacing panic function\n"));
        smb_panic_fn = validate_panic;
@@ -3860,10 +4301,10 @@ static bool add_wbdomain_to_tdc_array( struct winbindd_domain *new_dom,
 
        if ( !set_only ) {
                if ( !*domains ) {
-                       list = TALLOC_ARRAY( NULL, struct winbindd_tdc_domain, 1 );
+                       list = talloc_array( NULL, struct winbindd_tdc_domain, 1 );
                        idx = 0;
                } else {
-                       list = TALLOC_REALLOC_ARRAY( *domains, *domains, 
+                       list = talloc_realloc( *domains, *domains, 
                                                     struct winbindd_tdc_domain,  
                                                     (*num_domains)+1);
                        idx = *num_domains;             
@@ -4003,7 +4444,7 @@ static size_t unpack_tdc_domains( unsigned char *buf, int buflen,
                return 0;
        }
 
-       list = TALLOC_ARRAY( NULL, struct winbindd_tdc_domain, num_domains );
+       list = talloc_array( NULL, struct winbindd_tdc_domain, num_domains );
        if ( !list ) {
                DEBUG(0,("unpack_tdc_domains: Failed to talloc() domain list!\n"));
                return 0;               
@@ -4077,7 +4518,7 @@ static bool wcache_tdc_store_list( struct winbindd_tdc_domain *domains, size_t n
        SAFE_FREE( data.dptr );
        SAFE_FREE( key.dptr );
 
-       return ( ret != -1 );   
+       return ( ret == 0 );
 }
 
 /*********************************************************************
@@ -4094,7 +4535,7 @@ 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 );
+       data = tdb_fetch_compat( wcache->tdb, key );
 
        SAFE_FREE( key.dptr );
 
@@ -4170,7 +4611,7 @@ struct winbindd_tdc_domain * wcache_tdc_fetch_domain( TALLOC_CTX *ctx, const cha
        DEBUG(10,("wcache_tdc_fetch_domain: Searching for domain %s\n", name));
 
        if ( !init_wcache() ) {
-               return false;
+               return NULL;
        }
 
        /* fetch the list */
@@ -4184,7 +4625,7 @@ struct winbindd_tdc_domain * wcache_tdc_fetch_domain( TALLOC_CTX *ctx, const cha
                        DEBUG(10,("wcache_tdc_fetch_domain: Found domain %s\n",
                                  name));
 
-                       d = TALLOC_P( ctx, struct winbindd_tdc_domain );
+                       d = talloc( ctx, struct winbindd_tdc_domain );
                        if ( !d )
                                break;                  
 
@@ -4204,6 +4645,58 @@ struct winbindd_tdc_domain * wcache_tdc_fetch_domain( TALLOC_CTX *ctx, const cha
        return d;       
 }
 
+/*********************************************************************
+ ********************************************************************/
+
+struct winbindd_tdc_domain*
+       wcache_tdc_fetch_domainbysid(TALLOC_CTX *ctx,
+                                    const struct dom_sid *sid)
+{
+       struct winbindd_tdc_domain *dom_list = NULL;
+       size_t num_domains = 0;
+       int i;
+       struct winbindd_tdc_domain *d = NULL;
+
+       DEBUG(10,("wcache_tdc_fetch_domainbysid: Searching for domain %s\n",
+                 sid_string_dbg(sid)));
+
+       if (!init_wcache()) {
+               return NULL;
+       }
+
+       /* fetch the list */
+
+       wcache_tdc_fetch_list(&dom_list, &num_domains);
+
+       for (i = 0; i<num_domains; i++) {
+               if (dom_sid_equal(sid, &(dom_list[i].sid))) {
+                       DEBUG(10, ("wcache_tdc_fetch_domainbysid: "
+                                  "Found domain %s for SID %s\n",
+                                  dom_list[i].domain_name,
+                                  sid_string_dbg(sid)));
+
+                       d = talloc(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);
+                       d->trust_flags = dom_list[i].trust_flags;
+                       d->trust_type = dom_list[i].trust_type;
+                       d->trust_attribs = dom_list[i].trust_attribs;
+
+                       break;
+               }
+       }
+
+        TALLOC_FREE(dom_list);
+
+       return d;
+}
+
 
 /*********************************************************************
  ********************************************************************/
@@ -4224,7 +4717,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,
@@ -4248,10 +4741,11 @@ 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,
                              const char **homedir, const char **shell,
                              const char **gecos, gid_t *p_gid)
 {
@@ -4283,7 +4777,7 @@ NTSTATUS nss_get_info_cached( struct winbindd_domain *domain,
 
 do_query:
 
-       nt_status = nss_get_info( domain->name, user_sid, ctx, ads, msg, 
+       nt_status = nss_get_info( domain->name, user_sid, ctx,
                                  homedir, shell, gecos, p_gid );
 
        DEBUG(10, ("nss_get_info returned %s\n", nt_errstr(nt_status)));
@@ -4307,6 +4801,7 @@ do_query:
        return nt_status;       
 }
 
+#endif
 
 /* the cache backend methods are exposed via this structure */
 struct winbindd_methods cache_methods = {
@@ -4356,6 +4851,11 @@ 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;
@@ -4367,7 +4867,9 @@ bool wcache_fetch_ndr(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
        TDB_DATA key, data;
        bool ret = false;
 
-       if (!wcache_opnum_cacheable(opnum)) {
+       if (!wcache_opnum_cacheable(opnum) ||
+           is_my_own_sam_domain(domain) ||
+           is_builtin_domain(domain)) {
                return false;
        }
 
@@ -4378,18 +4880,19 @@ bool wcache_fetch_ndr(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
        if (!wcache_ndr_key(talloc_tos(), domain->name, opnum, req, &key)) {
                return false;
        }
-       data = tdb_fetch(wcache->tdb, key);
+       data = tdb_fetch_compat(wcache->tdb, key);
        TALLOC_FREE(key.dptr);
 
        if (data.dptr == NULL) {
                return false;
        }
-       if (data.dsize < 4) {
+       if (data.dsize < 12) {
                goto fail;
        }
 
-       if (IS_DOMAIN_ONLINE(domain)) {
+       if (!is_domain_offline(domain)) {
                uint32_t entry_seqnum, dom_seqnum, last_check;
+               uint64_t entry_timeout;
 
                if (!wcache_fetch_seqnum(domain->name, &dom_seqnum,
                                         &last_check)) {
@@ -4401,15 +4904,20 @@ bool wcache_fetch_ndr(TALLOC_CTX *mem_ctx, struct winbindd_domain *domain,
                                   (int)entry_seqnum));
                        goto fail;
                }
+               entry_timeout = BVAL(data.dptr, 4);
+               if (time(NULL) > entry_timeout) {
+                       DEBUG(10, ("Entry has timed out\n"));
+                       goto fail;
+               }
        }
 
-       resp->data = (uint8_t *)talloc_memdup(mem_ctx, data.dptr + 4,
-                                             data.dsize - 4);
+       resp->data = (uint8_t *)talloc_memdup(mem_ctx, data.dptr + 12,
+                                             data.dsize - 12);
        if (resp->data == NULL) {
                DEBUG(10, ("talloc failed\n"));
                goto fail;
        }
-       resp->length = data.dsize - 4;
+       resp->length = data.dsize - 12;
 
        ret = true;
 fail:
@@ -4422,8 +4930,11 @@ void wcache_store_ndr(struct winbindd_domain *domain, uint32_t opnum,
 {
        TDB_DATA key, data;
        uint32_t dom_seqnum, last_check;
+       uint64_t timeout;
 
-       if (!wcache_opnum_cacheable(opnum)) {
+       if (!wcache_opnum_cacheable(opnum) ||
+           is_my_own_sam_domain(domain) ||
+           is_builtin_domain(domain)) {
                return;
        }
 
@@ -4441,14 +4952,17 @@ void wcache_store_ndr(struct winbindd_domain *domain, uint32_t opnum,
                return;
        }
 
-       data.dsize = resp->length + 4;
+       timeout = time(NULL) + lp_winbind_cache_time();
+
+       data.dsize = resp->length + 12;
        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);
+       SBVAL(data.dptr, 4, timeout);
+       memcpy(data.dptr + 12, resp->data, resp->length);
 
        tdb_store(wcache->tdb, key, data, 0);