autorid: explicitly return NTSTATUS_OK in idmap_autorid_sid_to_id_alloc().
[obnox/samba/samba-obnox.git] / source3 / winbindd / idmap_autorid.c
index 5e3dacf624053d5a608b598407bb9e4e55316a19..0bdc96dd477a90c64bc93549d3493fdec0af9a0f 100644 (file)
@@ -5,7 +5,7 @@
  *  based on the idmap_rid module, but this module defines the ranges
  *  for the domains by automatically allocating a range for each domain
  *
- *  Copyright (C) Christian Ambach, 2010-2011
+ *  Copyright (C) Christian Ambach, 2010-2012
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
  *
  */
 
-#include "includes.h"
-#include "system/filesys.h"
+/*
+ * This module allocates ranges for domains to be used in a
+ * algorithmic mode like idmap_rid. Multiple ranges are supported
+ * for a single domain: If a rid exceeds the range size, a matching
+ * range is allocated to hold the rid's id.
+ *
+ * Here are the formulas applied:
+ *
+ *
+ * For a sid of the form domain_sid-rid, we have
+ *
+ *   rid = reduced_rid + domain_range_index * range_size
+ *
+ * with
+ *   reduced_rid := rid % range_size
+ *   domain_range_index := rid / range_size
+ *
+ * And reduced_rid fits into a range.
+ *
+ * In the database, we associate a range_number to
+ * the pair domain_sid,domain_range_index.
+ *
+ * Now the unix id for the given sid calculates as:
+ *
+ *   id = reduced_rid + range_low_id
+ *
+ * with
+ *
+ *   range_low_id = low_id + range_number * range_size
+ *
+ *
+ * The inverse calculation goes like this:
+ *
+ * Given a unix id, let
+ *
+ *   normalized_id := id - low_id
+ *   reduced_rid := normalized_id % range_size
+ *   range_number = normalized_id / range_size
+ *
+ * Then we have
+ *
+ *   id = reduced_rid + low_id + range_number * range_size
+ *
+ * From the database, get the domain_sid,domain_range_index pair
+ * belonging to the range_number (if there is already one).
+ *
+ * Then the rid for the unix id calculates as:
+ *
+ *   rid = reduced_rid + domain_range_index * range_size
+ */
+
+#include "idmap_autorid_tdb.h"
 #include "winbindd.h"
-#include "dbwrap.h"
 #include "idmap.h"
+#include "idmap_rw.h"
 #include "../libcli/security/dom_sid.h"
 
 #undef DBGC_CLASS
 #define DBGC_CLASS DBGC_IDMAP
 
-#define HWM "NEXT RANGE"
-#define CONFIGKEY "CONFIG"
-
-struct autorid_global_config {
-       uint32_t minvalue;
-       uint32_t rangesize;
-       uint32_t maxranges;
-};
-
-struct autorid_domain_config {
-       struct dom_sid sid;
-       uint32_t domainnum;
-       struct autorid_global_config *globalcfg;
-};
-
 /* handle to the tdb storing domain <-> range assignments */
 static struct db_context *autorid_db;
 
-static NTSTATUS idmap_autorid_get_domainrange(struct db_context *db,
-                                             void *private_data)
+static bool ignore_builtin = false;
+
+static NTSTATUS idmap_autorid_get_alloc_range(struct idmap_domain *dom,
+                                       struct autorid_range_config *range)
 {
+       NTSTATUS status;
+
+       ZERO_STRUCT(*range);
+
+       fstrcpy(range->domsid, ALLOC_RANGE);
+
+       status = idmap_autorid_get_domainrange(autorid_db,
+                                              range,
+                                              dom->read_only);
+
+       return status;
+}
+
+static NTSTATUS idmap_autorid_allocate_id(struct idmap_domain *dom,
+                                         struct unixid *xid) {
+
        NTSTATUS ret;
-       uint32_t domainnum, hwm;
-       fstring sidstr;
-       char *numstr;
-       struct autorid_domain_config *cfg;
-
-       cfg = (struct autorid_domain_config *)private_data;
-       dom_sid_string_buf(&(cfg->sid), sidstr, sizeof(sidstr));
-
-       if (!dbwrap_fetch_uint32(db, sidstr, &domainnum)) {
-               DEBUG(10, ("Acquiring new range for domain %s\n", sidstr));
-
-               /* fetch the current HWM */
-               if (!dbwrap_fetch_uint32(db, HWM, &hwm)) {
-                       DEBUG(1, ("Fatal error while fetching current "
-                                 "HWM value!\n"));
-                       ret = NT_STATUS_INTERNAL_ERROR;
-                       goto error;
-               }
+       struct autorid_range_config range;
 
-               /* do we have a range left? */
-               if (hwm >= cfg->globalcfg->maxranges) {
-                       DEBUG(1, ("No more domain ranges available!\n"));
-                       ret = NT_STATUS_NO_MEMORY;
-                       goto error;
-               }
+       if (dom->read_only) {
+               DEBUG(3, ("Backend is read-only, refusing "
+                         "new allocation request\n"));
+               return NT_STATUS_UNSUCCESSFUL;
+       }
 
-               /* increase the HWM */
-               ret = dbwrap_change_uint32_atomic(db, HWM, &domainnum, 1);
-               if (!NT_STATUS_IS_OK(ret)) {
-                       DEBUG(1, ("Fatal error while fetching a new "
-                                 "domain range value!\n"));
-                       goto error;
-               }
+       /* fetch the range for the allocation pool */
 
-               /* store away the new mapping in both directions */
-               ret = dbwrap_trans_store_uint32(db, sidstr, domainnum);
-               if (!NT_STATUS_IS_OK(ret)) {
-                       DEBUG(1, ("Fatal error while storing new "
-                                 "domain->range assignment!\n"));
-                       goto error;
-               }
+       ret = idmap_autorid_get_alloc_range(dom, &range);
+       if (!NT_STATUS_IS_OK(ret)) {
+               DEBUG(3, ("Could not determine range for allocation pool, "
+                         "check previous messages for reason\n"));
+               return ret;
+       }
 
-               numstr = talloc_asprintf(db, "%u", domainnum);
-               if (!numstr) {
-                       ret = NT_STATUS_NO_MEMORY;
-                       goto error;
-               }
+       ret = idmap_tdb_common_get_new_id(dom, xid);
 
-               ret = dbwrap_trans_store_bystring(db, numstr,
-                                                 string_term_tdb_data(sidstr),
-                                                 TDB_INSERT);
-               talloc_free(numstr);
-               if (!NT_STATUS_IS_OK(ret)) {
-                       DEBUG(1, ("Fatal error while storing "
-                                 "new domain->range assignment!\n"));
-                       goto error;
-               }
-               DEBUG(5, ("Acquired new range #%d for domain %s\n",
-                         domainnum, sidstr));
+       if (!NT_STATUS_IS_OK(ret)) {
+               DEBUG(1, ("Fatal error while allocating new ID!\n"));
+               return ret;
        }
 
-       DEBUG(10, ("Using range #%d for domain %s\n", domainnum, sidstr));
-       cfg->domainnum = domainnum;
+       xid->id = xid->id + range.low_id;
 
-       return NT_STATUS_OK;
+       DEBUG(10, ("Returned new %s %d from allocation range\n",
+                  (xid->type==ID_TYPE_UID)?"uid":"gid", xid->id));
 
-      error:
        return ret;
+}
+
+/*
+ * map a SID to xid using the idmap_tdb like pool
+ */
+static NTSTATUS idmap_autorid_id_to_sid_alloc(struct idmap_domain *dom,
+                                             struct id_map *map)
+{
+       NTSTATUS ret;
+
+       /* look out for the mapping */
+       ret = idmap_tdb_common_unixid_to_sid(dom, map);
 
+       if (NT_STATUS_IS_OK(ret)) {
+               map->status = ID_MAPPED;
+               return ret;
+       }
+
+       map->status = ID_UNKNOWN;
+
+       DEBUG(10, ("no ID->SID mapping for %d could be found\n", map->xid.id));
+
+       return ret;
 }
 
 static NTSTATUS idmap_autorid_id_to_sid(struct autorid_global_config *cfg,
+                                       struct idmap_domain *dom,
                                        struct id_map *map)
 {
-       uint32_t range;
-       TDB_DATA data;
+       uint32_t range_number;
+       uint32_t domain_range_index = 0;
+       uint32_t normalized_id;
+       uint32_t reduced_rid;
+       uint32_t rid;
+       TDB_DATA data = tdb_null;
        char *keystr;
-       struct dom_sid sid;
+       struct dom_sid domsid;
+       NTSTATUS status;
+       bool ok;
+       const char *q = NULL;
 
        /* can this be one of our ids? */
        if (map->xid.id < cfg->minvalue) {
@@ -149,36 +194,66 @@ static NTSTATUS idmap_autorid_id_to_sid(struct autorid_global_config *cfg,
        }
 
        /* determine the range of this uid */
-       range = ((map->xid.id - cfg->minvalue) / cfg->rangesize);
 
-       keystr = talloc_asprintf(talloc_tos(), "%u", range);
+       normalized_id = map->xid.id - cfg->minvalue;
+       range_number = normalized_id / cfg->rangesize;
+
+       keystr = talloc_asprintf(talloc_tos(), "%u", range_number);
        if (!keystr) {
                return NT_STATUS_NO_MEMORY;
        }
 
-       data = dbwrap_fetch_bystring(autorid_db, talloc_tos(), keystr);
+       status = dbwrap_fetch_bystring(autorid_db, talloc_tos(), keystr, &data);
        TALLOC_FREE(keystr);
 
-       if (!data.dptr) {
+       if (!NT_STATUS_IS_OK(status)) {
                DEBUG(4, ("id %d belongs to range %d which does not have "
                          "domain mapping, ignoring mapping request\n",
-                         map->xid.id, range));
+                         map->xid.id, range_number));
+               TALLOC_FREE(data.dptr);
                map->status = ID_UNKNOWN;
                return NT_STATUS_OK;
        }
 
-       string_to_sid(&sid, (const char *)data.dptr);
+       if (strncmp((const char *)data.dptr,
+                   ALLOC_RANGE,
+                   strlen(ALLOC_RANGE)) == 0) {
+               /*
+                * this is from the alloc range, check if there is a mapping
+                */
+               DEBUG(5, ("id %d belongs to allocation range, "
+                         "checking for mapping\n",
+                         map->xid.id));
+               TALLOC_FREE(data.dptr);
+               return idmap_autorid_id_to_sid_alloc(dom, map);
+       }
+
+       ok = dom_sid_parse_endp((const char *)data.dptr, &domsid, &q);
        TALLOC_FREE(data.dptr);
+       if (!ok) {
+               map->status = ID_UNKNOWN;
+               return NT_STATUS_OK;
+       }
+       if ((q != NULL) && (*q != '\0'))
+               if (sscanf(q+1, "%"SCNu32, &domain_range_index) != 1) {
+                       DEBUG(10, ("Domain range index not found, "
+                                  "ignoring mapping request\n"));
+                       map->status = ID_UNKNOWN;
+                       return NT_STATUS_OK;
+               }
+
+       reduced_rid = normalized_id % cfg->rangesize;
+       rid = reduced_rid + domain_range_index * cfg->rangesize;
 
-       sid_compose(map->sid, &sid,
-                   (map->xid.id - cfg->minvalue -
-                    range * cfg->rangesize));
+       sid_compose(map->sid, &domsid, rid);
 
        /* We **really** should have some way of validating
           the SID exists and is the correct type here.  But
           that is a deficiency in the idmap_rid design. */
 
        map->status = ID_MAPPED;
+       map->xid.type = ID_TYPE_BOTH;
+
        return NT_STATUS_OK;
 }
 
@@ -186,28 +261,20 @@ static NTSTATUS idmap_autorid_id_to_sid(struct autorid_global_config *cfg,
  Single sid to id lookup function.
 **********************************/
 
-static NTSTATUS idmap_autorid_sid_to_id(struct autorid_global_config *global,
-                                       struct autorid_domain_config *domain,
+static NTSTATUS idmap_autorid_sid_to_id_rid(
+                                       struct autorid_global_config *global,
+                                       struct autorid_range_config *range,
                                        struct id_map *map)
 {
        uint32_t rid;
+       uint32_t reduced_rid;
 
        sid_peek_rid(map->sid, &rid);
 
-       /* if the rid is higher than the size of the range, we cannot map it */
-       if (rid >= global->rangesize) {
-               map->status = ID_UNKNOWN;
-               DEBUG(2, ("RID %d is larger then size of range (%d), "
-                         "user cannot be mapped\n", rid, global->rangesize));
-               return NT_STATUS_UNSUCCESSFUL;
-       }
-       map->xid.id = global->minvalue +
-           (global->rangesize * domain->domainnum)+rid;
-
-       /* We **really** should have some way of validating
-          the SID exists and is the correct type here.  But
-          that is a deficiency in the idmap_rid design. */
+       reduced_rid = rid % global->rangesize;
 
+       map->xid.id = reduced_rid + range->low_id;
+       map->xid.type = ID_TYPE_BOTH;
        map->status = ID_MAPPED;
 
        return NT_STATUS_OK;
@@ -220,21 +287,29 @@ static NTSTATUS idmap_autorid_sid_to_id(struct autorid_global_config *global,
 static NTSTATUS idmap_autorid_unixids_to_sids(struct idmap_domain *dom,
                                              struct id_map **ids)
 {
+       struct idmap_tdb_common_context *commoncfg;
        struct autorid_global_config *globalcfg;
        NTSTATUS ret;
        int i;
+       int num_tomap = 0;
+       int num_mapped = 0;
 
        /* initialize the status to avoid surprise */
        for (i = 0; ids[i]; i++) {
                ids[i]->status = ID_UNKNOWN;
+               num_tomap++;
        }
 
-       globalcfg = talloc_get_type(dom->private_data,
+       commoncfg =
+           talloc_get_type_abort(dom->private_data,
+                                 struct idmap_tdb_common_context);
+
+       globalcfg = talloc_get_type(commoncfg->private_data,
                                    struct autorid_global_config);
 
        for (i = 0; ids[i]; i++) {
 
-               ret = idmap_autorid_id_to_sid(globalcfg, ids[i]);
+               ret = idmap_autorid_id_to_sid(globalcfg, dom, ids[i]);
 
                if ((!NT_STATUS_IS_OK(ret)) &&
                    (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
@@ -243,13 +318,90 @@ static NTSTATUS idmap_autorid_unixids_to_sids(struct idmap_domain *dom,
                                  " (%d)\n", ids[i]->xid.id));
                        goto failure;
                }
+
+               if (NT_STATUS_IS_OK(ret) && ids[i]->status == ID_MAPPED) {
+                       num_mapped++;
+               }
+
        }
-       return NT_STATUS_OK;
+
+       if (num_tomap == num_mapped) {
+               return NT_STATUS_OK;
+       } else if (num_mapped == 0) {
+               return NT_STATUS_NONE_MAPPED;
+       }
+
+       return STATUS_SOME_UNMAPPED;
+
 
       failure:
        return ret;
 }
 
+/*
+ * map a SID to xid using the idmap_tdb like pool
+ */
+static NTSTATUS idmap_autorid_sid_to_id_alloc(struct idmap_domain *dom,
+                                       struct id_map *map,
+                                       struct idmap_tdb_common_context *ctx)
+{
+       NTSTATUS ret;
+       int res;
+
+       map->status = ID_UNKNOWN;
+
+       /* see if we already have a mapping */
+       ret = idmap_tdb_common_sid_to_unixid(dom, map);
+
+       if (NT_STATUS_IS_OK(ret)) {
+               map->status = ID_MAPPED;
+               return ret;
+       }
+
+       /* bad things happened */
+       if (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
+               DEBUG(1, ("Looking up SID->ID mapping for %s failed: %s\n",
+                         sid_string_dbg(map->sid), nt_errstr(ret)));
+               return ret;
+       }
+
+       if (dom->read_only) {
+               DEBUG(3, ("Not allocating new mapping for %s, because backend "
+                         "is read-only\n", sid_string_dbg(map->sid)));
+               map->status = ID_UNMAPPED;
+               return NT_STATUS_NONE_MAPPED;
+       }
+
+       DEBUG(10, ("Creating new mapping in pool for %s\n",
+                  sid_string_dbg(map->sid)));
+
+       /* create new mapping */
+       res = dbwrap_transaction_start(ctx->db);
+       if (res != 0) {
+               DEBUG(2, ("transaction_start failed\n"));
+               return NT_STATUS_INTERNAL_DB_CORRUPTION;
+       }
+
+       ret = idmap_tdb_common_new_mapping(dom, map);
+       if (!NT_STATUS_IS_OK(ret)) {
+               if (dbwrap_transaction_cancel(ctx->db) != 0) {
+                       smb_panic("Cancelling transaction failed");
+               }
+               map->status = ID_UNMAPPED;
+               return ret;
+       }
+
+       res = dbwrap_transaction_commit(ctx->db);
+       if (res == 0) {
+               map->status = ID_MAPPED;
+               return NT_STATUS_OK;
+       }
+
+       DEBUG(2, ("transaction_commit failed\n"));
+       return NT_STATUS_INTERNAL_DB_CORRUPTION;
+
+}
+
 /**********************************
  lookup a set of sids.
 **********************************/
@@ -257,50 +409,104 @@ static NTSTATUS idmap_autorid_unixids_to_sids(struct idmap_domain *dom,
 static NTSTATUS idmap_autorid_sids_to_unixids(struct idmap_domain *dom,
                                              struct id_map **ids)
 {
+       struct idmap_tdb_common_context *commoncfg;
        struct autorid_global_config *global;
        NTSTATUS ret;
        int i;
+       int num_tomap = 0;
+       int num_mapped = 0;
 
        /* initialize the status to avoid surprise */
        for (i = 0; ids[i]; i++) {
                ids[i]->status = ID_UNKNOWN;
+               num_tomap++;
        }
 
-       global = talloc_get_type(dom->private_data,
+       commoncfg =
+           talloc_get_type_abort(dom->private_data,
+                                 struct idmap_tdb_common_context);
+
+       global = talloc_get_type(commoncfg->private_data,
                                 struct autorid_global_config);
 
        for (i = 0; ids[i]; i++) {
                struct winbindd_tdc_domain *domain;
-               struct autorid_domain_config domaincfg;
+               struct autorid_range_config range;
                uint32_t rid;
+               struct dom_sid domainsid;
 
-               ZERO_STRUCT(domaincfg);
+               ZERO_STRUCT(range);
 
-               sid_copy(&domaincfg.sid, ids[i]->sid);
-               if (!sid_split_rid(&domaincfg.sid, &rid)) {
+               DEBUG(10, ("Trying to map %s\n", sid_string_dbg(ids[i]->sid)));
+
+               sid_copy(&domainsid, ids[i]->sid);
+               if (!sid_split_rid(&domainsid, &rid)) {
                        DEBUG(4, ("Could not determine domain SID from %s, "
                                  "ignoring mapping request\n",
                                  sid_string_dbg(ids[i]->sid)));
                        continue;
                }
 
+               /* is this a well-known SID? */
+
+               if (sid_check_is_wellknown_domain(&domainsid, NULL)) {
+
+                       DEBUG(10, ("SID %s is well-known, using pool\n",
+                                  sid_string_dbg(ids[i]->sid)));
+
+                       ret = idmap_autorid_sid_to_id_alloc(dom, ids[i],
+                                                           commoncfg);
+
+                       if (!NT_STATUS_IS_OK(ret) &&
+                           !NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
+                               DEBUG(3, ("Unexpected error resolving "
+                                         "SID (%s)\n",
+                                         sid_string_dbg(ids[i]->sid)));
+                               goto failure;
+                       }
+
+                       if (ids[i]->status == ID_MAPPED) {
+                               num_mapped++;
+                       }
+
+                       continue;
+               }
+
+               /* BUILTIN is passdb's job */
+               if (dom_sid_equal(&domainsid, &global_sid_Builtin) &&
+                   ignore_builtin) {
+                       DEBUG(10, ("Ignoring request for BUILTIN domain\n"));
+                       continue;
+               }
+
                /*
                 * Check if the domain is around
                 */
                domain = wcache_tdc_fetch_domainbysid(talloc_tos(),
-                                                     &domaincfg.sid);
+                                                     &domainsid);
                if (domain == NULL) {
                        DEBUG(10, ("Ignoring unknown domain sid %s\n",
-                                  sid_string_dbg(&domaincfg.sid)));
+                                  sid_string_dbg(&domainsid)));
                        continue;
                }
                TALLOC_FREE(domain);
 
-               domaincfg.globalcfg = global;
+               sid_to_fstring(range.domsid, &domainsid);
 
-               ret = dbwrap_trans_do(autorid_db,
-                                     idmap_autorid_get_domainrange,
-                                     &domaincfg);
+               /* Calculate domain_range_index for multi-range support */
+               range.domain_range_index = rid / (global->rangesize);
+
+               ret = idmap_autorid_get_domainrange(autorid_db, &range,
+                                                   dom->read_only);
+
+               /* read-only mode and a new domain range would be required? */
+               if (NT_STATUS_EQUAL(ret, NT_STATUS_NOT_FOUND) &&
+                   dom->read_only) {
+                       DEBUG(10, ("read-only is enabled, did not allocate "
+                                  "new range for domain %s\n",
+                                  sid_string_dbg(&domainsid)));
+                       continue;
+               }
 
                if (!NT_STATUS_IS_OK(ret)) {
                        DEBUG(3, ("Could not determine range for domain, "
@@ -308,7 +514,7 @@ static NTSTATUS idmap_autorid_sids_to_unixids(struct idmap_domain *dom,
                        goto failure;
                }
 
-               ret = idmap_autorid_sid_to_id(global, &domaincfg, ids[i]);
+               ret = idmap_autorid_sid_to_id_rid(global, &range, ids[i]);
 
                if ((!NT_STATUS_IS_OK(ret)) &&
                    (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
@@ -317,150 +523,148 @@ static NTSTATUS idmap_autorid_sids_to_unixids(struct idmap_domain *dom,
                                  sid_string_dbg(ids[i]->sid)));
                        goto failure;
                }
+
+               if (NT_STATUS_IS_OK(ret)) {
+                       num_mapped++;
+               }
        }
-       return NT_STATUS_OK;
+
+       if (num_tomap == num_mapped) {
+               return NT_STATUS_OK;
+       } else if (num_mapped == 0) {
+               return NT_STATUS_NONE_MAPPED;
+       }
+
+       return STATUS_SOME_UNMAPPED;
 
       failure:
        return ret;
 
 }
 
-/*
- * open and initialize the database which stores the ranges for the domains
- */
-static NTSTATUS idmap_autorid_db_init(void)
+static NTSTATUS idmap_autorid_preallocate_wellknown(struct idmap_domain *dom)
 {
-       int32_t hwm;
+       const char *groups[] = { "S-1-1-0", "S-1-2-0", "S-1-2-1",
+               "S-1-3-0", "S-1-3-1", "S-1-3-2", "S-1-3-3", "S-1-3-4",
+               "S-1-5-1", "S-1-5-2", "S-1-5-3", "S-1-5-4", "S-1-5-6",
+               "S-1-5-7", "S-1-5-8", "S-1-5-9", "S-1-5-10", "S-1-5-11",
+               "S-1-5-12", "S-1-5-13", "S-1-5-14", "S-1-5-15",
+               "S-1-5-17", "S-1-5-18", "S-1-5-19", "S-1-5-20"
+       };
+
+       struct id_map **maps;
+       int i, num;
+       NTSTATUS status;
 
-       if (autorid_db) {
-               /* its already open */
+       if (dom->read_only) {
                return NT_STATUS_OK;
        }
 
-       /* Open idmap repository */
-       autorid_db = db_open(NULL, state_path("autorid.tdb"), 0,
-                            TDB_DEFAULT, O_RDWR | O_CREAT, 0644);
+       num = ARRAY_SIZE(groups);
 
-       if (!autorid_db) {
-               DEBUG(0, ("Unable to open idmap_autorid database '%s'\n",
-                         state_path("autorid.tdb")));
-               return NT_STATUS_UNSUCCESSFUL;
+       maps = talloc_array(talloc_tos(), struct id_map*, num+1);
+       if (!maps) {
+               return NT_STATUS_NO_MEMORY;
        }
 
-       /* Initialize high water mark for the currently used range to 0 */
-       hwm = dbwrap_fetch_int32(autorid_db, HWM);
-       if ((hwm < 0)) {
-               if (!NT_STATUS_IS_OK
-                   (dbwrap_trans_store_int32(autorid_db, HWM, 0))) {
-                       DEBUG(0,
-                             ("Unable to initialise HWM in autorid "
-                              "database\n"));
-                       return NT_STATUS_INTERNAL_DB_ERROR;
+       for (i = 0; i < num; i++) {
+               maps[i] = talloc(maps, struct id_map);
+               if (maps[i] == NULL) {
+                       talloc_free(maps);
+                       return NT_STATUS_NO_MEMORY;
                }
+               maps[i]->xid.type = ID_TYPE_GID;
+               maps[i]->sid = dom_sid_parse_talloc(maps, groups[i]);
        }
 
-       return NT_STATUS_OK;
-}
-
-static struct autorid_global_config *idmap_autorid_loadconfig(TALLOC_CTX * ctx)
-{
+       maps[num] = NULL;
 
-       TDB_DATA data;
-       struct autorid_global_config *cfg;
-       unsigned long minvalue, rangesize, maxranges;
+       status = idmap_autorid_sids_to_unixids(dom, maps);
 
-       data = dbwrap_fetch_bystring(autorid_db, ctx, CONFIGKEY);
+       DEBUG(10,("Preallocation run finished with status %s\n",
+                 nt_errstr(status)));
 
-       if (!data.dptr) {
-               DEBUG(10, ("No saved config found\n"));
-               return NULL;
-       }
-
-       cfg = TALLOC_ZERO_P(ctx, struct autorid_global_config);
-       if (!cfg) {
-               return NULL;
-       }
-
-       if (sscanf((char *)data.dptr,
-                  "minvalue:%lu rangesize:%lu maxranges:%lu",
-                  &minvalue, &rangesize, &maxranges) != 3) {
-               DEBUG(1,
-                     ("Found invalid configuration data"
-                      "creating new config\n"));
-               return NULL;
-       }
-
-       cfg->minvalue = minvalue;
-       cfg->rangesize = rangesize;
-       cfg->maxranges = maxranges;
-
-       DEBUG(10, ("Loaded previously stored configuration "
-                  "minvalue:%d rangesize:%d\n",
-                  cfg->minvalue, cfg->rangesize));
-
-       return cfg;
+       talloc_free(maps);
 
+       return NT_STATUS_IS_OK(status)?NT_STATUS_OK:NT_STATUS_UNSUCCESSFUL;
 }
 
-static NTSTATUS idmap_autorid_saveconfig(struct autorid_global_config *cfg)
+static NTSTATUS idmap_autorid_initialize_action(struct db_context *db,
+                                               void *private_data)
 {
-
+       struct idmap_domain *dom;
+       struct idmap_tdb_common_context *common;
+       struct autorid_global_config *config;
        NTSTATUS status;
-       TDB_DATA data;
-       char *cfgstr;
 
-       cfgstr =
-           talloc_asprintf(talloc_tos(),
-                           "minvalue:%u rangesize:%u maxranges:%u",
-                           cfg->minvalue, cfg->rangesize, cfg->maxranges);
+       dom = (struct idmap_domain *)private_data;
+       common = (struct idmap_tdb_common_context *)dom->private_data;
+       config = (struct autorid_global_config *)common->private_data;
 
-       if (!cfgstr) {
-               return NT_STATUS_NO_MEMORY;
+       status = idmap_autorid_init_hwms(db);
+       if (!NT_STATUS_IS_OK(status)) {
+               return status;
        }
 
-       data = string_tdb_data(cfgstr);
-
-       status = dbwrap_trans_store_bystring(autorid_db, CONFIGKEY,
-                                            data, TDB_REPLACE);
+       status = idmap_autorid_saveconfig(db, config);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(1, ("Failed to store configuration data!\n"));
+               return status;
+       }
 
-       talloc_free(cfgstr);
+       status = idmap_autorid_preallocate_wellknown(dom);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(1, ("Failed to preallocate wellknown sids: %s\n",
+                         nt_errstr(status)));
+               return status;
+       }
 
-       return status;
+       return NT_STATUS_OK;
 }
 
 static NTSTATUS idmap_autorid_initialize(struct idmap_domain *dom)
 {
+       struct idmap_tdb_common_context *commonconfig;
        struct autorid_global_config *config;
-       struct autorid_global_config *storedconfig = NULL;
        NTSTATUS status;
-       uint32_t hwm;
 
-       config = TALLOC_ZERO_P(dom, struct autorid_global_config);
-       if (!config) {
+       if (!strequal(dom->name, "*")) {
+               DEBUG(0, ("idmap_autorid_initialize: Error: autorid configured "
+                         "for domain '%s'. But autorid can only be used for "
+                         "the default idmap configuration.\n", dom->name));
+               return NT_STATUS_INVALID_PARAMETER;
+       }
+
+       commonconfig = talloc_zero(dom, struct idmap_tdb_common_context);
+       if (!commonconfig) {
                DEBUG(0, ("Out of memory!\n"));
                return NT_STATUS_NO_MEMORY;
        }
+       dom->private_data = commonconfig;
 
-       status = idmap_autorid_db_init();
-       if (!NT_STATUS_IS_OK(status)) {
-               goto error;
+       commonconfig->rw_ops = talloc_zero(commonconfig, struct idmap_rw_ops);
+       if (commonconfig->rw_ops == NULL) {
+               DEBUG(0, ("Out of memory!\n"));
+               return NT_STATUS_NO_MEMORY;
        }
 
-       config->minvalue = dom->low_id;
-       config->rangesize = lp_parm_int(-1, "autorid", "rangesize", 100000);
-
-       if (config->rangesize < 2000) {
-               DEBUG(1, ("autorid rangesize must be at least 2000\n"));
-               status = NT_STATUS_INVALID_PARAMETER;
-               goto error;
+       config = talloc_zero(commonconfig, struct autorid_global_config);
+       if (!config) {
+               DEBUG(0, ("Out of memory!\n"));
+               return NT_STATUS_NO_MEMORY;
        }
+       commonconfig->private_data = config;
+
+       config->minvalue = dom->low_id;
+       config->rangesize = lp_parm_int(-1, "idmap config *",
+                                       "rangesize", 100000);
 
        config->maxranges = (dom->high_id - dom->low_id + 1) /
            config->rangesize;
 
        if (config->maxranges == 0) {
-               DEBUG(1, ("allowed uid range is smaller then rangesize, "
-                         "increase uid range or decrease rangesize\n"));
+               DEBUG(1, ("Allowed uid range is smaller than rangesize. "
+                         "Increase uid range or decrease rangesize.\n"));
                status = NT_STATUS_INVALID_PARAMETER;
                goto error;
        }
@@ -474,64 +678,44 @@ static NTSTATUS idmap_autorid_initialize(struct idmap_domain *dom)
                          config->maxranges));
        }
 
-       DEBUG(10, ("Current configuration in config is "
-                  "minvalue:%d rangesize:%d maxranges:%d\n",
-                  config->minvalue, config->rangesize, config->maxranges));
-
-       /* read previously stored config and current HWM */
-       storedconfig = idmap_autorid_loadconfig(talloc_tos());
-
-       if (!dbwrap_fetch_uint32(autorid_db, HWM, &hwm)) {
-               DEBUG(1, ("Fatal error while fetching current "
-                         "HWM value!\n"));
-               status = NT_STATUS_INTERNAL_ERROR;
-               goto error;
-       }
+       DEBUG(5, ("%d domain ranges with a size of %d are available\n",
+                 config->maxranges, config->rangesize));
 
-       /* did the minimum value or rangesize change? */
-       if (storedconfig &&
-           ((storedconfig->minvalue != config->minvalue) ||
-            (storedconfig->rangesize != config->rangesize))) {
-               DEBUG(1, ("New configuration values for rangesize or "
-                         "minimum uid value conflict with previously "
-                         "used values! Aborting initialization\n"));
-               status = NT_STATUS_INVALID_PARAMETER;
-               goto error;
-       }
+       ignore_builtin = lp_parm_bool(-1, "idmap config *",
+                                     "ignore builtin", false);
 
-       /*
-        * has the highest uid value been reduced to setting that is not
-        * sufficient any more for already existing ranges?
-        */
-       if (hwm > config->maxranges) {
-               DEBUG(1, ("New upper uid limit is too low to cover "
-                         "existing mappings! Aborting initialization\n"));
-               status = NT_STATUS_INVALID_PARAMETER;
-               goto error;
-       }
+       /* fill the TDB common configuration */
 
-       status = idmap_autorid_saveconfig(config);
+       commonconfig->max_id = config->rangesize -1;
+       commonconfig->hwmkey_uid = ALLOC_HWM_UID;
+       commonconfig->hwmkey_gid = ALLOC_HWM_GID;
+       commonconfig->rw_ops->get_new_id = idmap_autorid_allocate_id;
+       commonconfig->rw_ops->set_mapping = idmap_tdb_common_set_mapping;
 
+       status = idmap_autorid_db_open(state_path("autorid.tdb"),
+                                      NULL, /* TALLOC_CTX */
+                                      &autorid_db);
        if (!NT_STATUS_IS_OK(status)) {
-               DEBUG(1, ("Failed to store configuration data!\n"));
                goto error;
        }
 
-       DEBUG(5, ("%d domain ranges with a size of %d are available\n",
-                 config->maxranges, config->rangesize));
-
-       dom->private_data = config;
+       commonconfig->db = autorid_db;
 
+       status = dbwrap_trans_do(autorid_db,
+                                idmap_autorid_initialize_action,
+                                dom);
        if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(1, ("Failed to init the idmap database: %s\n",
+                         nt_errstr(status)));
                goto error;
        }
 
-       return NT_STATUS_OK;
+       goto done;
 
-      error:
+error:
        talloc_free(config);
-       talloc_free(storedconfig);
 
+done:
        return status;
 }
 
@@ -542,6 +726,7 @@ static struct idmap_methods autorid_methods = {
        .init = idmap_autorid_initialize,
        .unixids_to_sids = idmap_autorid_unixids_to_sids,
        .sids_to_unixids = idmap_autorid_sids_to_unixids,
+       .allocate_id     = idmap_autorid_allocate_id
 };
 
 NTSTATUS idmap_autorid_init(void)