r22173: BUG 4491, 4501: Additional fixes for protecting against
[ira/wip.git] / source3 / nsswitch / idmap.c
index 42e3f7abb0353732dd458110b7906a67346ad41c..de98c81f5a9724cc056833b44b83697da0611dc6 100644 (file)
@@ -18,7 +18,8 @@
 
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.*/
+   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+*/
 
 #include "includes.h"
 #include "winbindd.h"
@@ -224,61 +225,100 @@ NTSTATUS idmap_close(void)
 
 static const char *idmap_default_domain[] = { "default domain", NULL };
 
+/****************************************************************************
+ ****************************************************************************/
+
+NTSTATUS idmap_init_cache(void)
+{      
+       /* Always initialize the cache.  We'll have to delay initialization
+          of backends if we are offline */
+
+       if ( idmap_ctx ) {
+               return NT_STATUS_OK;
+       }       
+       
+       if ( (idmap_ctx = talloc_named_const(NULL, 0, "idmap_ctx")) == NULL ) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       if ( (idmap_cache = idmap_cache_init(idmap_ctx)) == NULL ) {
+               return NT_STATUS_UNSUCCESSFUL;
+       }
+
+       return NT_STATUS_OK;
+}
+
+/****************************************************************************
+ ****************************************************************************/
+
 NTSTATUS idmap_init(void)
-{
+{      
        NTSTATUS ret;
+       static NTSTATUS backend_init_status = NT_STATUS_UNSUCCESSFUL;   
        struct idmap_domain *dom;
-       const char *compat_backend = NULL;
-       const char *compat_params = NULL;
+       char *compat_backend = NULL;
+       char *compat_params = NULL;
        const char **dom_list = NULL;
-       char *alloc_backend;
+       char *alloc_backend = NULL;
        BOOL default_already_defined = False;
        BOOL pri_dom_is_in_list = False;
        int compat = 0;
        int i;
 
-       if (idmap_ctx) {
-               return NT_STATUS_OK;
-       }
+       /* Always initialize the cache.  We'll have to delay initialization
+          of backends if we are offline */
 
-       idmap_ctx = talloc_named_const(NULL, 0, "IDMAP MEMORY CONTEXT");
-       if ( ! idmap_ctx) {
-               return NT_STATUS_NO_MEMORY;
+       ret = idmap_init_cache();
+       if ( !NT_STATUS_IS_OK(ret) )
+               return ret;
+
+       if ( NT_STATUS_IS_OK(backend_init_status) ) {
+               return NT_STATUS_OK;
        }
+       
+       /* We can't reliably call intialization code here unless 
+          we are online */
 
-       /* init cache */
-       idmap_cache = idmap_cache_init(idmap_ctx);
-       if ( ! idmap_cache) {
-               return NT_STATUS_UNSUCCESSFUL;
+       if ( get_global_winbindd_state_offline() ) {
+               backend_init_status = NT_STATUS_FILE_IS_OFFLINE;
+               return backend_init_status;             
        }
 
-       /* register static backends */
        static_init_idmap;
 
-       if ((dom_list = lp_idmap_domains()) != NULL) {
-               if (lp_idmap_backend()) {
-                       DEBUG(0, ("WARNING: idmap backend and idmap domains are mutually excusive!\n"));
-                       DEBUGADD(0, ("        idmap backend option will be IGNORED!\n"));
-               }
-               
-       } else if (lp_idmap_backend()) {
+       dom_list = lp_idmap_domains();
+       
+       if ( dom_list && lp_idmap_backend() ) {
+               DEBUG(0, ("WARNING: idmap backend and idmap domains are "
+                         "mutually excusive!\n"));
+               DEBUGADD(0,("idmap backend option will be IGNORED!\n"));
+       } else if ( lp_idmap_backend() ) {
                const char **compat_list = lp_idmap_backend();
-               const char *p;
+               char *p = NULL;
+               const char *q = NULL;           
 
-               DEBUG(0, ("WARNING: idmap backend is deprecated!\n"));
                compat = 1;
 
+               if ( (compat_backend = talloc_strdup( idmap_ctx, *compat_list )) == NULL ) {
+                       ret = NT_STATUS_NO_MEMORY;
+                       goto done;                      
+               }
+               
                /* strip any leading idmap_ prefix of */
                if (strncmp(*compat_list, "idmap_", 6) == 0 ) {
-                       p = *compat_list += 6;
-                       DEBUG(0, ("WARNING: idmap backend uses obsolete and deprecated 'idmap_' prefix.\n"));
-                       DEBUGADD(0, ("        Please replace 'idmap_%s' by '%s' in %s\n", p, p, dyn_CONFIGFILE));
-                       compat_backend = p;
+                       q = *compat_list += 6;
+                       DEBUG(0, ("WARNING: idmap backend uses obsolete and "
+                                 "deprecated 'idmap_' prefix.\n"
+                                 "Please replace 'idmap_%s' by '%s' in %s\n", 
+                                 q, q, dyn_CONFIGFILE));
+                       compat_backend = talloc_strdup( idmap_ctx, q);
                } else {
-                       compat_backend = *compat_list;
+                       compat_backend = talloc_strdup( idmap_ctx, *compat_list);
                }
                        
+               /* separate the backend and module arguements */
                if ((p = strchr(compat_backend, ':')) != NULL) {
+                       *p = '\0';                      
                        compat_params = p + 1;
                }
        }
@@ -296,6 +336,15 @@ NTSTATUS idmap_init(void)
                const char *parm_backend;
                char *config_option;
 
+               /* ignore BUILTIN and local MACHINE domains */
+               if ( strequal(dom_list[i], "BUILTIN") 
+                    || strequal(dom_list[i], get_global_sam_name() ) ) 
+               {
+                       DEBUG(0,("idmap_init: Ignoring invalid domain %s\n", 
+                                dom_list[i]));
+                       continue;
+               }
+
                if (strequal(dom_list[i], lp_workgroup())) {
                        pri_dom_is_in_list = True;
                }
@@ -313,19 +362,13 @@ NTSTATUS idmap_init(void)
                /* default or specific ? */
 
                dom->default_domain = lp_parm_bool(-1, config_option, "default", False);
+
                if (dom->default_domain ||
                    strequal(dom_list[i], idmap_default_domain[0])) {
-                       /* the default domain is a cacth all domain
-                        * so no specific domain sid is provided */
-                       dom->sid = NULL;
+
                        /* make sure this is set even when we match idmap_default_domain[0] */
                        dom->default_domain = True;
 
-                       if (lp_parm_const_string(-1, config_option, "domain sid", NULL)) {
-                               DEBUG(1, ("WARNING: Can't force a /domain sid/ on the DEFAULT domain, Ignoring!"));
-                       }
-
-                       /* only one default domain is permitted */
                        if (default_already_defined) {
                                DEBUG(1, ("ERROR: Multiple domains defined as default!\n"));
                                ret = NT_STATUS_INVALID_PARAMETER;
@@ -334,38 +377,16 @@ NTSTATUS idmap_init(void)
 
                        default_already_defined = True;
 
-               } else {
-                       const char *sid;
+               } 
 
-                       sid = lp_parm_const_string(-1, config_option, "domain sid", NULL);
-                       if (sid) {
-                               dom->sid = string_sid_talloc(dom, sid);
-                       } else {
-                               struct winbindd_domain *wdom = find_domain_from_name(dom->name);
-                               if (wdom) {
-                                       dom->sid = sid_dup_talloc(dom, &wdom->sid);
-                                       IDMAP_CHECK_ALLOC(dom->sid);
-                               }
-                       }
-
-                       if ( ! dom->sid) {
-                               DEBUG(1, ("ERROR: Could not find DOMAIN SID for domain %s\n", dom->name));
-                               DEBUGADD(1, ("      Consider to set explicitly the /domain sid/ option\n"));
-                               ret = NT_STATUS_NO_SUCH_DOMAIN;
-                               goto done;
-                       }
-               }
-
-               /* is this a readonly domain ? */
                dom->readonly = lp_parm_bool(-1, config_option, "readonly", False);
 
                /* find associated backend (default: tdb) */
                if (compat) {
                        parm_backend = talloc_strdup(idmap_ctx, compat_backend);
                } else {
-                       parm_backend =
-                               talloc_strdup(idmap_ctx,
-                                       lp_parm_const_string(-1, config_option, "backend", "tdb"));
+                       parm_backend = talloc_strdup(idmap_ctx,
+                                                    lp_parm_const_string(-1, config_option, "backend", "tdb"));
                }
                IDMAP_CHECK_ALLOC(parm_backend);
 
@@ -386,6 +407,7 @@ NTSTATUS idmap_init(void)
 
                /* check the set_mapping function exists otherwise mark the module as readonly */
                if ( ! dom->methods->set_mapping) {
+                       DEBUG(5, ("Forcing to readonly, as ithis module can't store arbitrary mappings.\n"));
                        dom->readonly = True;
                }
 
@@ -412,8 +434,8 @@ NTSTATUS idmap_init(void)
                        def_dom_num = i;
                }
 
-               DEBUG(10, ("Domain %s - Sid %s - Backend %s - %sdefault - %sreadonly\n",
-                               dom->name, sid_string_static(dom->sid), parm_backend,
+               DEBUG(10, ("Domain %s - Backend %s - %sdefault - %sreadonly\n",
+                               dom->name, parm_backend,
                                dom->default_domain?"":"not ", dom->readonly?"":"not "));
 
                talloc_free(config_option);
@@ -426,13 +448,6 @@ NTSTATUS idmap_init(void)
        if ((lp_server_role() == ROLE_DOMAIN_MEMBER) &&
            ( ! pri_dom_is_in_list) &&
            lp_winbind_trusted_domains_only()) {
-               DOM_SID our_sid;
-
-               if (!secrets_fetch_domain_sid(lp_workgroup(), &our_sid)) {
-                       DEBUG(0, ("Could not fetch our SID - did we join?\n"));
-                       ret = NT_STATUS_UNSUCCESSFUL;
-                       goto done;
-               }
 
                dom = talloc_zero(idmap_ctx, struct idmap_domain);
                IDMAP_CHECK_ALLOC(dom);
@@ -443,9 +458,6 @@ NTSTATUS idmap_init(void)
                dom->default_domain = False;
                dom->readonly = True;
 
-               dom->sid = sid_dup_talloc(dom, &our_sid);
-               IDMAP_CHECK_ALLOC(dom->sid);
-
                /* get the backend methods for passdb */
                dom->methods = get_methods(backends, "nss");
 
@@ -475,8 +487,7 @@ NTSTATUS idmap_init(void)
                }
                idmap_domains[num_domains] = dom;
 
-               DEBUG(10, ("Domain %s - Sid %s - Backend nss - not default - readonly\n",
-                               dom->name, sid_string_static(dom->sid)));
+               DEBUG(10, ("Domain %s - Backend nss - not default - readonly\n", dom->name ));
 
                num_domains++;
        }
@@ -491,9 +502,6 @@ NTSTATUS idmap_init(void)
        dom->default_domain = False;
        dom->readonly = True;
 
-       dom->sid = sid_dup_talloc(dom, get_global_sam_sid());
-       IDMAP_CHECK_ALLOC(dom->sid);
-
        /* get the backend methods for passdb */
        dom->methods = get_methods(backends, "passdb");
 
@@ -526,15 +534,14 @@ NTSTATUS idmap_init(void)
        /* needed to handle special BUILTIN and wellknown SIDs cases */
        pdb_dom_num = num_domains;
 
-       DEBUG(10, ("Domain %s - Sid %s - Backend passdb - not default - readonly\n",
-                       dom->name, sid_string_static(dom->sid)));
-       DEBUGADD(10, ("        (special: includes handling BUILTIN and Wellknown SIDs as well)\n"));
+       DEBUG(10, ("Domain %s - Backend passdb - not default - readonly\n", dom->name));
 
        num_domains++;
        /**** finished adding idmap_passdb backend ****/
 
        /* sort domains so that the default is the last one */
-       if (def_dom_num != num_domains-1) { /* default is not last, move it */
+       /* don't sort if no default domain defined */
+       if (def_dom_num != -1 && def_dom_num != num_domains-1) { /* default is not last, move it */
                struct idmap_domain *tmp;
 
                if (pdb_dom_num > def_dom_num) {
@@ -554,11 +561,11 @@ NTSTATUS idmap_init(void)
        }
 
 
-       /***************************
-        * initialize alloc module
-        */
-       DEBUG(1, ("Initializing idmap alloc module\n"));
+       /* Initialize alloc module */
+
+       DEBUG(3, ("Initializing idmap alloc module\n"));
 
+       alloc_backend = NULL;
        if (compat) {
                alloc_backend = talloc_strdup(idmap_ctx, compat_backend);
        } else {
@@ -566,37 +573,51 @@ NTSTATUS idmap_init(void)
                
                if (ab && (ab[0] != '\0')) {
                        alloc_backend = talloc_strdup(idmap_ctx, lp_idmap_alloc_backend());
-               } else {
-                       alloc_backend = talloc_strdup(idmap_ctx, "tdb");
                }
        }
-       IDMAP_CHECK_ALLOC(alloc_backend);
 
-       alloc_methods = get_alloc_methods(alloc_backends, alloc_backend);
-       if ( ! alloc_methods) {
-               ret = smb_probe_module("idmap", alloc_backend);
-               if (NT_STATUS_IS_OK(ret)) {
-                       alloc_methods = get_alloc_methods(alloc_backends, alloc_backend);
-               }
-       }
-       if ( ! alloc_methods) {
-               DEBUG(0, ("ERROR: Could not get methods for alloc backend %s\n", alloc_backend));
-               ret = NT_STATUS_UNSUCCESSFUL;
-               goto done;
-       }
+       if ( alloc_backend ) {
 
-       ret = alloc_methods->init(compat_params);
-       if ( ! NT_STATUS_IS_OK(ret)) {
-               DEBUG(0, ("ERROR: Initialization failed for alloc backend %s\n", alloc_backend));
-               ret = NT_STATUS_UNSUCCESSFUL;
-               goto done;
+               alloc_methods = get_alloc_methods(alloc_backends, alloc_backend);
+               if ( ! alloc_methods) {
+                       ret = smb_probe_module("idmap", alloc_backend);
+                       if (NT_STATUS_IS_OK(ret)) {
+                               alloc_methods = get_alloc_methods(alloc_backends, alloc_backend);
+                       }
+               }
+               if ( alloc_methods) {
+                       ret = alloc_methods->init(compat_params);
+                       if ( ! NT_STATUS_IS_OK(ret)) {
+                               DEBUG(0, ("idmap_init: Initialization failed for alloc "
+                                         "backend %s\n", alloc_backend));
+                               ret = NT_STATUS_UNSUCCESSFUL;
+                               goto done;
+               }
+               } else {
+                       DEBUG(2, ("idmap_init: Unable to get methods for alloc backend %s\n", 
+                                 alloc_backend));
+                       /* certain compat backends are just readonly */
+                       if ( compat )
+                               ret = NT_STATUS_OK;
+                       else
+                               ret = NT_STATUS_UNSUCCESSFUL;
+               }
        }
-
-       return NT_STATUS_OK;
+       
+       /* cleanpu temporary strings */
+       TALLOC_FREE( compat_backend );
+       
+       backend_init_status = NT_STATUS_OK;
+       
+       return ret;
 
 done:
        DEBUG(0, ("Aborting IDMAP Initialization ...\n"));
        idmap_close();
+
+       /* save the init status for later checks */
+       backend_init_status = ret;
+       
        return ret;
 }
 
@@ -612,6 +633,9 @@ NTSTATUS idmap_allocate_uid(struct unixid *id)
                return ret;
        }
 
+       if ( !alloc_methods )
+               return NT_STATUS_NOT_SUPPORTED; 
+
        id->type = ID_TYPE_UID;
        return alloc_methods->allocate_id(id);
 }
@@ -624,6 +648,9 @@ NTSTATUS idmap_allocate_gid(struct unixid *id)
                return ret;
        }
 
+       if ( !alloc_methods )
+               return NT_STATUS_NOT_SUPPORTED; 
+
        id->type = ID_TYPE_GID;
        return alloc_methods->allocate_id(id);
 }
@@ -636,6 +663,9 @@ NTSTATUS idmap_set_uid_hwm(struct unixid *id)
                return ret;
        }
 
+       if ( !alloc_methods )
+               return NT_STATUS_NOT_SUPPORTED; 
+
        id->type = ID_TYPE_UID;
        return alloc_methods->set_id_hwm(id);
 }
@@ -648,10 +678,75 @@ NTSTATUS idmap_set_gid_hwm(struct unixid *id)
                return ret;
        }
 
+       if ( !alloc_methods )
+               return NT_STATUS_NOT_SUPPORTED; 
+
        id->type = ID_TYPE_GID;
        return alloc_methods->set_id_hwm(id);
 }
 
+/******************************************************************************
+ Lookup an idmap_domain give a full user or group SID
+ ******************************************************************************/
+
+static struct idmap_domain* find_idmap_domain_from_sid( DOM_SID *account_sid )
+{
+       DOM_SID domain_sid;
+       uint32 rid;
+       struct winbindd_domain *domain = NULL;
+       int i;
+       
+       /* 1. Handle BUILTIN or Special SIDs and prevent them from
+          falling into the default domain space (if we have a
+          configured passdb backend. */
+
+       if ( (pdb_dom_num != -1) && 
+            (sid_check_is_in_builtin(account_sid) ||
+             sid_check_is_in_wellknown_domain(account_sid) ||
+             sid_check_is_in_unix_groups(account_sid) ||
+             sid_check_is_in_unix_users(account_sid)) ) 
+       {
+               return idmap_domains[pdb_dom_num];
+       }
+
+       /* 2. Lookup the winbindd_domain from the account_sid */
+
+       sid_copy( &domain_sid, account_sid );
+       sid_split_rid( &domain_sid, &rid );     
+       domain = find_domain_from_sid_noinit( &domain_sid );    
+
+       for (i = 0; domain && i < num_domains; i++) {
+               if ( strequal( idmap_domains[i]->name, domain->name ) ) {
+                       return idmap_domains[i];
+               }
+       }
+
+       /* 3. Fall back to the default domain */
+
+       if ( def_dom_num != -1 ) {
+               return idmap_domains[def_dom_num];
+       }
+
+       return NULL;
+}
+
+/******************************************************************************
+ Lookup an index given an idmap_domain pointer
+ ******************************************************************************/
+
+static uint32 find_idmap_domain_index( struct idmap_domain *id_domain)
+{
+       int i;
+       
+       for (i = 0; i < num_domains; i++) {
+               if ( idmap_domains[i] == id_domain )
+                       return i;               
+       }
+
+       return -1;      
+}
+
+
 /*********************************************************
  Check if creating a mapping is permitted for the domain
 *********************************************************/
@@ -659,7 +754,6 @@ NTSTATUS idmap_set_gid_hwm(struct unixid *id)
 static NTSTATUS idmap_can_map(const struct id_map *map, struct idmap_domain **ret_dom)
 {
        struct idmap_domain *dom;
-       int i;
 
        /* Check we do not create mappings for our own local domain, or BUILTIN or special SIDs */
        if ((sid_compare_domain(map->sid, get_global_sam_sid()) == 0) ||
@@ -679,23 +773,15 @@ static NTSTATUS idmap_can_map(const struct id_map *map, struct idmap_domain **re
                }
        }
 
-       for (i = 0, dom = NULL; i < num_domains; i++) {
-               if ((idmap_domains[i]->default_domain) || /* ok set it into the default domain */
-                   (sid_compare_domain(idmap_domains[i]->sid, map->sid) == 0)) { /* ok found a specific domain */
-                       dom = idmap_domains[i];
-                       break;
-               }
-       }
-
-       if (! dom) {
+       if ( (dom = find_idmap_domain_from_sid( map->sid )) == NULL ) {
                /* huh, couldn't find a suitable domain, let's just leave it unmapped */
-               DEBUG(10, ("Could not find imdap backend for SID %s", sid_string_static(map->sid)));
+               DEBUG(10, ("Could not find idmap backend for SID %s", sid_string_static(map->sid)));
                return NT_STATUS_NO_SUCH_DOMAIN;
        }
 
        if (dom->readonly) {
                /* ouch the domain is read only, let's just leave it unmapped */
-               DEBUG(10, ("imdap backend for SID %s is READONLY!\n", sid_string_static(map->sid)));
+               DEBUG(10, ("idmap backend for SID %s is READONLY!\n", sid_string_static(map->sid)));
                return NT_STATUS_UNSUCCESSFUL;
        }
 
@@ -707,16 +793,23 @@ static NTSTATUS idmap_new_mapping(TALLOC_CTX *ctx, struct id_map *map)
 {
        NTSTATUS ret;
        struct idmap_domain *dom;
-       char *domname, *name;
+       const char *domname, *name;
        enum lsa_SidType sid_type;
+       BOOL wbret;
 
        ret = idmap_can_map(map, &dom);
        if ( ! NT_STATUS_IS_OK(ret)) {
                return NT_STATUS_NONE_MAPPED;
        }
        
+       /* by default calls to winbindd are disabled
+          the following call will not recurse so this is safe */
+       winbind_on();
+       wbret = winbind_lookup_sid(ctx, map->sid, &domname, &name, &sid_type);
+       winbind_off();
+
        /* check if this is a valid SID and then map it */
-       if (winbindd_lookup_name_by_sid(ctx, map->sid, &domname, &name, &sid_type)) {
+       if (wbret) {
                switch (sid_type) {
                case SID_NAME_USER:
                        ret = idmap_allocate_uid(&map->xid);
@@ -743,7 +836,7 @@ static NTSTATUS idmap_new_mapping(TALLOC_CTX *ctx, struct id_map *map)
                }
 
                /* ok, got a new id, let's set a mapping */
-               map->mapped = True;
+               map->status = ID_MAPPED;
 
                DEBUG(10, ("Setting mapping: %s <-> %s %lu\n",
                           sid_string_static(map->sid),
@@ -783,7 +876,7 @@ static NTSTATUS idmap_backends_set_mapping(const struct id_map *map)
                return ret;
        }
 
-       DEBUG(10, ("set_mapping for domain %s(%s)\n", dom->name, sid_string_static(dom->sid)));
+       DEBUG(10,("set_mapping for domain %s\n", dom->name ));  
 
        return dom->methods->set_mapping(dom, map);
 }
@@ -791,6 +884,7 @@ static NTSTATUS idmap_backends_set_mapping(const struct id_map *map)
 static NTSTATUS idmap_backends_unixids_to_sids(struct id_map **ids)
 {
        struct idmap_domain *dom;
+       struct id_map **unmapped;
        struct id_map **_ids;
        TALLOC_CTX *ctx;
        NTSTATUS ret;
@@ -814,25 +908,25 @@ static NTSTATUS idmap_backends_unixids_to_sids(struct id_map **ids)
 
        _ids = ids;
 
-       /* make sure all maps are marked as false */
+       /* make sure all maps are marked as in UNKNOWN status */
        for (i = 0; _ids[i]; i++) {
-               _ids[i]->mapped = False;
+               _ids[i]->status = ID_UNKNOWN;
        }
 
+       unmapped = NULL;
        for (n = num_domains-1; n >= 0; n--) { /* cycle backwards */
-               struct id_map **unmapped = NULL;
 
                dom = idmap_domains[n];
 
-               DEBUG(10, ("Query sids from domain %s(%s)\n", dom->name, sid_string_static(dom->sid)));
+               DEBUG(10, ("Query sids from domain %s\n", dom->name));
                
                ret = dom->methods->unixids_to_sids(dom, _ids);
                IDMAP_CHECK_RET(ret);
 
-               TALLOC_FREE(unmapped);
+               unmapped = NULL;
 
                for (i = 0, u = 0; _ids[i]; i++) {
-                       if (_ids[i]->mapped == False) {
+                       if (_ids[i]->status == ID_UNKNOWN || _ids[i]->status == ID_UNMAPPED) {
                                unmapped = talloc_realloc(ctx, unmapped, struct id_map *, u + 2);
                                IDMAP_CHECK_ALLOC(unmapped);
                                unmapped[u] = _ids[i];
@@ -842,27 +936,28 @@ static NTSTATUS idmap_backends_unixids_to_sids(struct id_map **ids)
                if (unmapped) {
                        /* terminate the unmapped list */
                        unmapped[u] = NULL;
-               } else { /* no more unmapped entries, get out */
+               } else { /* no more entries, get out */
                        break;
                }
 
                _ids = unmapped;
+               
        }
 
-       if (!_ids) {
+       if (unmapped) {
                /* there are still unmapped ids, map them to the unix users/groups domains */
-               for (i = 0; _ids[i]; i++) {
-                       switch (_ids[i]->xid.type) {
+               for (i = 0; unmapped[i]; i++) {
+                       switch (unmapped[i]->xid.type) {
                        case ID_TYPE_UID:
-                               uid_to_unix_users_sid((uid_t)_ids[i]->xid.id, _ids[i]->sid);
-                               _ids[i]->mapped = True;
+                               uid_to_unix_users_sid((uid_t)unmapped[i]->xid.id, unmapped[i]->sid);
+                               unmapped[i]->status = ID_MAPPED;
                                break;
                        case ID_TYPE_GID:
-                               gid_to_unix_groups_sid((gid_t)_ids[i]->xid.id, _ids[i]->sid);
-                               _ids[i]->mapped = True;
+                               gid_to_unix_groups_sid((gid_t)unmapped[i]->xid.id, unmapped[i]->sid);
+                               unmapped[i]->status = ID_MAPPED;
                                break;
                        default: /* what?! */
-                               _ids[i]->mapped = False;
+                               unmapped[i]->status = ID_UNKNOWN;
                                break;
                        }
                }
@@ -883,13 +978,7 @@ static NTSTATUS idmap_backends_sids_to_unixids(struct id_map **ids)
        NTSTATUS ret;
        int i, *counters;
 
-       if (!ids || !*ids) {
-               DEBUG(1, ("Invalid list of maps\n"));
-               return NT_STATUS_INVALID_PARAMETER;
-       }
-
-       ctx = talloc_named_const(NULL, 0, "idmap_backends_sids_to_unixids ctx");
-       if ( ! ctx) {
+       if ( (ctx = talloc_named_const(NULL, 0, "be_sids_to_ids")) == NULL ) {
                DEBUG(1, ("failed to allocate talloc context, OOM?\n"));
                return NT_STATUS_NO_MEMORY;
        }
@@ -897,66 +986,47 @@ static NTSTATUS idmap_backends_sids_to_unixids(struct id_map **ids)
        DEBUG(10, ("Query backends to map sids->ids\n"));
 
        /* split list per domain */
+
        dom_ids = talloc_zero_array(ctx, struct id_map **, num_domains);
        IDMAP_CHECK_ALLOC(dom_ids);
        counters = talloc_zero_array(ctx, int, num_domains);
 
+       /* partition the requests by domain */
+
        for (i = 0; ids[i]; i++) {
-               int dom_num;
+               uint32 idx;             
 
-               /* make sure they are unmapped by default */
-               ids[i]->mapped = False;
+               /* make sure they are unknown to start off */
+               ids[i]->status = ID_UNKNOWN;
 
-               for (dom_num = 0, dom = NULL; dom_num < num_domains; dom_num++) {
-                       if (idmap_domains[dom_num]->default_domain) {
-                               /* we got to the default domain */
-                               dom = idmap_domains[dom_num];
-                               break;
-                       }
-                       if (sid_compare_domain(idmap_domains[dom_num]->sid, ids[i]->sid) == 0) {
-                               dom = idmap_domains[dom_num];
-                               break;
-                       }
-               }
-               if (( ! dom) || dom->default_domain) {
-                       /* handle BUILTIN or Special SIDs
-                        * and prevent them from falling into the default domain space */
-                       if ((sid_check_is_in_builtin(ids[i]->sid) ||
-                           sid_check_is_in_wellknown_domain(ids[i]->sid))) {
-
-                               if (pdb_dom_num != -1) {
-                                       dom = idmap_domains[pdb_dom_num];
-                                       dom_num = pdb_dom_num;
-                               } else {
-                                       dom = NULL;
-                               }
-                       }
-               }
-               if ( ! dom) {
-                       /* no dom move on */
+               if ( (dom = find_idmap_domain_from_sid( ids[i]->sid )) == NULL ) {
+                       /* no vailable idmap_domain.  Move on */
                        continue;
                }
 
-               DEBUG(10, ("SID %s is being handled by %s(%d)\n",
-                       sid_string_static(ids[i]->sid),
-                       dom?dom->name:"none",
-                       dom_num));
+               DEBUG(10,("SID %s is being handled by %s\n", 
+                         sid_string_static(ids[i]->sid),  
+                         dom ? dom->name : "none" ));
 
-               dom_ids[dom_num] = talloc_realloc(ctx, dom_ids[dom_num], struct id_map *, counters[dom_num] + 2);
-               IDMAP_CHECK_ALLOC(dom_ids[dom_num]);
+               idx = find_idmap_domain_index( dom );
+               SMB_ASSERT( idx != -1 );
+               
+               dom_ids[idx] = talloc_realloc(ctx, dom_ids[idx], 
+                                             struct id_map *, counters[idx] + 2);
+               IDMAP_CHECK_ALLOC(dom_ids[idx]);
 
-               dom_ids[dom_num][counters[dom_num]] = ids[i];
-               counters[dom_num]++;
-               dom_ids[dom_num][counters[dom_num]] = NULL;
+               dom_ids[idx][counters[idx]] = ids[i];
+               counters[idx]++;
+               dom_ids[idx][counters[idx]] = NULL;
        }
 
-       /* ok all the ids have been dispatched in the right queues
-        * let's cycle through the filled ones */
+       /* All the ids have been dispatched in the right queues.
+          Let's cycle through the filled ones */
 
        for (i = 0; i < num_domains; i++) {
-               if (dom_ids[i]) { /* ok, we have ids in this one */
+               if (dom_ids[i]) {
                        dom = idmap_domains[i];
-                       DEBUG(10, ("Query ids from domain %s(%s)\n", dom->name, sid_string_static(dom->sid)));
+                       DEBUG(10, ("Query ids from domain %s\n", dom->name));
                        ret = dom->methods->sids_to_unixids(dom, dom_ids[i]);
                        IDMAP_CHECK_RET(ret);
                }
@@ -966,17 +1036,18 @@ static NTSTATUS idmap_backends_sids_to_unixids(struct id_map **ids)
        /* let's see if we have any unmapped SID left and act accordingly */
 
        for (i = 0; ids[i]; i++) {
-               if ( ! ids[i]->mapped) { /* ok this is an unmapped one, see if we can map it */
+               if (ids[i]->status == ID_UNKNOWN || ids[i]->status == ID_UNMAPPED) {
+                       /* ok this is an unmapped one, see if we can map it */
                        ret = idmap_new_mapping(ctx, ids[i]);
                        if (NT_STATUS_IS_OK(ret)) {
                                /* successfully mapped */
-                               ids[i]->mapped = True;
+                               ids[i]->status = ID_MAPPED;
                        } else if (NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
                                /* could not map it */
-                               ids[i]->mapped = False;
-                       } else{
+                               ids[i]->status = ID_UNMAPPED;
+                       } else {
                                /* Something very bad happened down there */
-                               goto done;
+                               ids[i]->status = ID_UNKNOWN;
                        }
                }
        }
@@ -1029,8 +1100,6 @@ NTSTATUS idmap_unixids_to_sids(struct id_map **ids)
 
                ret = idmap_cache_map_id(idmap_cache, ids[i]);
 
-               /* TODO: handle NT_STATUS_SYNCHRONIZATION_REQUIRED for disconnected mode */
-
                if ( ! NT_STATUS_IS_OK(ret)) {
 
                        if ( ! bids) {
@@ -1066,14 +1135,27 @@ NTSTATUS idmap_unixids_to_sids(struct id_map **ids)
 
        /* let's see if there is any id mapping to be retieved from the backends */
        if (bi) {
+               /* Only do query if we are online */
+               if ( lp_winbind_offline_logon() &&
+                    get_global_winbindd_state_offline() )
+               {
+                       ret = NT_STATUS_FILE_IS_OFFLINE;
+                       goto done;
+               }
+
                ret = idmap_backends_unixids_to_sids(bids);
                IDMAP_CHECK_RET(ret);
 
                /* update the cache */
                for (i = 0; i < bi; i++) {
-                       if (bids[i]->mapped) {
+                       if (bids[i]->status == ID_MAPPED) {
                                ret = idmap_cache_set(idmap_cache, bids[i]);
-                       } else {
+                       } else if (bids[i]->status == ID_UNKNOWN) {
+                               /* return an expired entry in the cache or an unknown */
+                               /* this handles a previous NT_STATUS_SYNCHRONIZATION_REQUIRED
+                                * for disconnected mode */
+                               idmap_cache_map_id(idmap_cache, ids[i]);
+                       } else { /* unmapped */
                                ret = idmap_cache_set_negative_id(idmap_cache, bids[i]);
                        }
                        IDMAP_CHECK_RET(ret);
@@ -1123,12 +1205,11 @@ NTSTATUS idmap_sids_to_unixids(struct id_map **ids)
 
                ret = idmap_cache_map_sid(idmap_cache, ids[i]);
 
-               /* TODO: handle NT_STATUS_SYNCHRONIZATION_REQUIRED for disconnected mode */
-
                if ( ! NT_STATUS_IS_OK(ret)) {
 
                        if ( ! bids) {
-                               /* alloc space for ids to be resolved by backends (realloc ten by ten) */
+                               /* alloc space for ids to be resolved
+                                  by backends (realloc ten by ten) */
                                bids = talloc_array(ctx, struct id_map *, 10);
                                if ( ! bids) {
                                        DEBUG(1, ("Out of memory!\n"));
@@ -1160,13 +1241,26 @@ NTSTATUS idmap_sids_to_unixids(struct id_map **ids)
 
        /* let's see if there is any id mapping to be retieved from the backends */
        if (bids) {
+               /* Only do query if we are online */
+               if ( lp_winbind_offline_logon() &&
+                    get_global_winbindd_state_offline() )
+               {
+                       ret = NT_STATUS_FILE_IS_OFFLINE;
+                       goto done;
+               }
+               
                ret = idmap_backends_sids_to_unixids(bids);
                IDMAP_CHECK_RET(ret);
 
                /* update the cache */
                for (i = 0; bids[i]; i++) {
-                       if (bids[i]->mapped) {
+                       if (bids[i]->status == ID_MAPPED) {
                                ret = idmap_cache_set(idmap_cache, bids[i]);
+                       } else if (bids[i]->status == ID_UNKNOWN) {
+                               /* return an expired entry in the cache or an unknown */
+                               /* this handles a previous NT_STATUS_SYNCHRONIZATION_REQUIRED
+                                * for disconnected mode */
+                               idmap_cache_map_id(idmap_cache, ids[i]);
                        } else {
                                ret = idmap_cache_set_negative_sid(idmap_cache, bids[i]);
                        }
@@ -1190,7 +1284,7 @@ NTSTATUS idmap_set_mapping(const struct id_map *id)
        }
 
        /* sanity checks */
-       if ((id->sid == NULL) || (! id->mapped)) {
+       if ((id->sid == NULL) || (id->status != ID_MAPPED)) {
                DEBUG(1, ("NULL SID or unmapped entry\n"));
                return NT_STATUS_INVALID_PARAMETER;
        }
@@ -1239,16 +1333,18 @@ void idmap_dump_maps(char *logfile)
                return;
        }
 
-       allid.type = ID_TYPE_UID;
-       allid.id = 0;
-       alloc_methods->get_id_hwm(&allid);
-       fprintf(dump, "USER HWM %lu\n", (unsigned long)allid.id);
-
-       allid.type = ID_TYPE_GID;
-       allid.id = 0;
-       alloc_methods->get_id_hwm(&allid);
-       fprintf(dump, "GROUP HWM %lu\n", (unsigned long)allid.id);
-
+       if ( alloc_methods ) {          
+               allid.type = ID_TYPE_UID;
+               allid.id = 0;
+               alloc_methods->get_id_hwm(&allid);
+               fprintf(dump, "USER HWM %lu\n", (unsigned long)allid.id);
+               
+               allid.type = ID_TYPE_GID;
+               allid.id = 0;
+               alloc_methods->get_id_hwm(&allid);
+               fprintf(dump, "GROUP HWM %lu\n", (unsigned long)allid.id);
+       }
+       
        maps = talloc(idmap_ctx, struct id_map);
        num_maps = 0;
 
@@ -1277,8 +1373,8 @@ void idmap_dump_maps(char *logfile)
        fclose(dump);
 }
 
-const char *idmap_fecth_secret(const char *backend, bool alloc,
-                               const char *domain, const char *identity)
+char *idmap_fetch_secret(const char *backend, bool alloc,
+                              const char *domain, const char *identity)
 {
        char *tmp, *ret;
        int r;
@@ -1289,11 +1385,13 @@ const char *idmap_fecth_secret(const char *backend, bool alloc,
                r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);
        }
 
-       if (r < 0) return NULL;
+       if (r < 0) 
+               return NULL;
 
        strupper_m(tmp); /* make sure the key is case insensitive */
        ret = secrets_fetch_generic(tmp, identity);
 
-       free(tmp);
+       SAFE_FREE( tmp );       
+
        return ret;
 }