s3:idmap_autorid: force mapping type to ID_TYPE_BOTH for sid->unixid mapping
[obnox/samba/samba-obnox.git] / source3 / winbindd / idmap_autorid.c
1 /*
2  *  idmap_autorid: static map between Active Directory/NT RIDs
3  *  and RFC 2307 accounts
4  *
5  *  based on the idmap_rid module, but this module defines the ranges
6  *  for the domains by automatically allocating a range for each domain
7  *
8  *  Copyright (C) Christian Ambach, 2010-2012
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 3 of the License, or
13  *  (at your option) any later version.
14  *
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #include "includes.h"
26 #include "system/filesys.h"
27 #include "winbindd.h"
28 #include "dbwrap/dbwrap.h"
29 #include "dbwrap/dbwrap_open.h"
30 #include "idmap.h"
31 #include "idmap_rw.h"
32 #include "../libcli/security/dom_sid.h"
33 #include "util_tdb.h"
34 #include "winbindd/idmap_tdb_common.h"
35
36 #undef DBGC_CLASS
37 #define DBGC_CLASS DBGC_IDMAP
38
39 #define HWM "NEXT RANGE"
40 #define ALLOC_HWM_UID "NEXT ALLOC UID"
41 #define ALLOC_HWM_GID "NEXT ALLOC GID"
42 #define ALLOC_RANGE "ALLOC"
43 #define CONFIGKEY "CONFIG"
44
45 struct autorid_global_config {
46         uint32_t minvalue;
47         uint32_t rangesize;
48         uint32_t maxranges;
49         bool ignore_builtin;
50 };
51
52 struct autorid_domain_config {
53         fstring sid;
54         uint32_t domainnum;
55         struct autorid_global_config *globalcfg;
56 };
57
58 /* handle to the tdb storing domain <-> range assignments */
59 static struct db_context *autorid_db;
60
61 static NTSTATUS idmap_autorid_get_domainrange_action(struct db_context *db,
62                                               void *private_data)
63 {
64         NTSTATUS ret;
65         uint32_t domainnum, hwm;
66         char *numstr;
67         struct autorid_domain_config *cfg;
68
69         cfg = (struct autorid_domain_config *)private_data;
70
71         ret = dbwrap_fetch_uint32_bystring(db, cfg->sid, &(cfg->domainnum));
72
73         if (NT_STATUS_IS_OK(ret)) {
74                 /* entry is already present*/
75                 return ret;
76         }
77
78         DEBUG(10, ("Acquiring new range for domain %s\n", cfg->sid));
79
80         /* fetch the current HWM */
81         ret = dbwrap_fetch_uint32_bystring(db, HWM, &hwm);
82         if (!NT_STATUS_IS_OK(ret)) {
83                 DEBUG(1, ("Fatal error while fetching current "
84                           "HWM value: %s\n", nt_errstr(ret)));
85                 ret = NT_STATUS_INTERNAL_ERROR;
86                 goto error;
87         }
88
89         /* do we have a range left? */
90         if (hwm >= cfg->globalcfg->maxranges) {
91                 DEBUG(1, ("No more domain ranges available!\n"));
92                 ret = NT_STATUS_NO_MEMORY;
93                 goto error;
94         }
95
96         /* increase the HWM */
97         ret = dbwrap_change_uint32_atomic_bystring(db, HWM, &domainnum, 1);
98         if (!NT_STATUS_IS_OK(ret)) {
99                 DEBUG(1, ("Fatal error while fetching a new "
100                           "domain range value!\n"));
101                 goto error;
102         }
103
104         /* store away the new mapping in both directions */
105         ret = dbwrap_store_uint32_bystring(db, cfg->sid, domainnum);
106         if (!NT_STATUS_IS_OK(ret)) {
107                 DEBUG(1, ("Fatal error while storing new "
108                           "domain->range assignment!\n"));
109                 goto error;
110         }
111
112         numstr = talloc_asprintf(db, "%u", domainnum);
113         if (!numstr) {
114                 ret = NT_STATUS_NO_MEMORY;
115                 goto error;
116         }
117
118         ret = dbwrap_store_bystring(db, numstr,
119                         string_term_tdb_data(cfg->sid), TDB_INSERT);
120
121         talloc_free(numstr);
122         if (!NT_STATUS_IS_OK(ret)) {
123                 DEBUG(1, ("Fatal error while storing "
124                           "new domain->range assignment!\n"));
125                 goto error;
126         }
127         DEBUG(5, ("Acquired new range #%d for domain %s\n",
128                   domainnum, cfg->sid));
129
130         cfg->domainnum = domainnum;
131
132         return NT_STATUS_OK;
133
134 error:
135         return ret;
136
137 }
138
139 static NTSTATUS idmap_autorid_get_domainrange(struct autorid_domain_config *dom,
140                                               bool read_only)
141 {
142         NTSTATUS ret;
143
144         /*
145          * try to find mapping without locking the database,
146          * if it is not found create a mapping in a transaction unless
147          * read-only mode has been set
148          */
149         ret = dbwrap_fetch_uint32_bystring(autorid_db, dom->sid,
150                                            &(dom->domainnum));
151
152         if (!NT_STATUS_IS_OK(ret)) {
153                 if (read_only) {
154                         return NT_STATUS_NOT_FOUND;
155                 }
156                 ret = dbwrap_trans_do(autorid_db,
157                               idmap_autorid_get_domainrange_action, dom);
158         }
159
160         DEBUG(10, ("Using range #%d for domain %s\n", dom->domainnum,
161                    dom->sid));
162
163         return ret;
164 }
165
166 static NTSTATUS idmap_autorid_allocate_id(struct idmap_domain *dom,
167                                           struct unixid *xid) {
168
169         NTSTATUS ret;
170         struct idmap_tdb_common_context *commoncfg;
171         struct autorid_global_config *globalcfg;
172         struct autorid_domain_config domaincfg;
173
174         commoncfg =
175             talloc_get_type_abort(dom->private_data,
176                                   struct idmap_tdb_common_context);
177
178         globalcfg = talloc_get_type(commoncfg->private_data,
179                                     struct autorid_global_config);
180
181         if (dom->read_only) {
182                 DEBUG(3, ("Backend is read-only, refusing "
183                           "new allocation request\n"));
184                 return NT_STATUS_UNSUCCESSFUL;
185         }
186
187         /* fetch the range for the allocation pool */
188
189         ZERO_STRUCT(domaincfg);
190
191         domaincfg.globalcfg = globalcfg;
192         fstrcpy(domaincfg.sid, ALLOC_RANGE);
193
194         ret = idmap_autorid_get_domainrange(&domaincfg, dom->read_only);
195
196         if (!NT_STATUS_IS_OK(ret)) {
197                 DEBUG(3, ("Could not determine range for allocation pool, "
198                           "check previous messages for reason\n"));
199                 return ret;
200         }
201
202         ret = idmap_tdb_common_get_new_id(dom, xid);
203
204         if (!NT_STATUS_IS_OK(ret)) {
205                 DEBUG(1, ("Fatal error while allocating new ID!\n"));
206                 return ret;
207         }
208
209         xid->id = globalcfg->minvalue +
210                   globalcfg->rangesize * domaincfg.domainnum +
211                   xid->id;
212
213         DEBUG(10, ("Returned new %s %d from allocation range\n",
214                    (xid->type==ID_TYPE_UID)?"uid":"gid", xid->id));
215
216         return ret;
217 }
218
219 /*
220  * map a SID to xid using the idmap_tdb like pool
221  */
222 static NTSTATUS idmap_autorid_map_id_to_sid(struct idmap_domain *dom,
223                                             struct id_map *map)
224 {
225         NTSTATUS ret;
226
227         /* look out for the mapping */
228         ret = idmap_tdb_common_unixid_to_sid(dom, map);
229
230         if (NT_STATUS_IS_OK(ret)) {
231                 map->status = ID_MAPPED;
232                 return ret;
233         }
234
235         map->status = ID_UNKNOWN;
236
237         DEBUG(10, ("no ID->SID mapping for %d could be found\n", map->xid.id));
238
239         return ret;
240 }
241
242 static NTSTATUS idmap_autorid_id_to_sid(struct autorid_global_config *cfg,
243                                         struct idmap_domain *dom,
244                                         struct id_map *map)
245 {
246         uint32_t range;
247         TDB_DATA data;
248         char *keystr;
249         struct dom_sid sid;
250         NTSTATUS status;
251
252         /* can this be one of our ids? */
253         if (map->xid.id < cfg->minvalue) {
254                 DEBUG(10, ("id %d is lower than minimum value, "
255                            "ignoring mapping request\n", map->xid.id));
256                 map->status = ID_UNKNOWN;
257                 return NT_STATUS_OK;
258         }
259
260         if (map->xid.id > (cfg->minvalue + cfg->rangesize * cfg->maxranges)) {
261                 DEBUG(10, ("id %d is outside of maximum id value, "
262                            "ignoring mapping request\n", map->xid.id));
263                 map->status = ID_UNKNOWN;
264                 return NT_STATUS_OK;
265         }
266
267         /* determine the range of this uid */
268         range = ((map->xid.id - cfg->minvalue) / cfg->rangesize);
269
270         keystr = talloc_asprintf(talloc_tos(), "%u", range);
271         if (!keystr) {
272                 return NT_STATUS_NO_MEMORY;
273         }
274
275         status = dbwrap_fetch_bystring(autorid_db, talloc_tos(), keystr, &data);
276         TALLOC_FREE(keystr);
277
278         if (!NT_STATUS_IS_OK(status)) {
279                 DEBUG(4, ("id %d belongs to range %d which does not have "
280                           "domain mapping, ignoring mapping request\n",
281                           map->xid.id, range));
282                 TALLOC_FREE(data.dptr);
283                 map->status = ID_UNKNOWN;
284                 return NT_STATUS_OK;
285         }
286
287         if (strncmp((const char *)data.dptr,
288                     ALLOC_RANGE,
289                     strlen(ALLOC_RANGE)) == 0) {
290                 /*
291                  * this is from the alloc range, check if there is a mapping
292                  */
293                 DEBUG(5, ("id %d belongs to allocation range, "
294                           "checking for mapping\n",
295                           map->xid.id));
296                 TALLOC_FREE(data.dptr);
297                 return idmap_autorid_map_id_to_sid(dom, map);
298         }
299
300         string_to_sid(&sid, (const char *)data.dptr);
301         TALLOC_FREE(data.dptr);
302
303         sid_compose(map->sid, &sid,
304                     (map->xid.id - cfg->minvalue -
305                      range * cfg->rangesize));
306
307         /* We **really** should have some way of validating
308            the SID exists and is the correct type here.  But
309            that is a deficiency in the idmap_rid design. */
310
311         map->status = ID_MAPPED;
312         map->xid.type = ID_TYPE_BOTH;
313
314         return NT_STATUS_OK;
315 }
316
317 /**********************************
318  Single sid to id lookup function.
319 **********************************/
320
321 static NTSTATUS idmap_autorid_sid_to_id(struct autorid_global_config *global,
322                                         struct autorid_domain_config *domain,
323                                         struct id_map *map)
324 {
325         uint32_t rid;
326
327         sid_peek_rid(map->sid, &rid);
328
329         /* if the rid is higher than the size of the range, we cannot map it */
330         if (rid >= global->rangesize) {
331                 map->status = ID_UNKNOWN;
332                 DEBUG(2, ("RID %d is larger then size of range (%d), "
333                           "user cannot be mapped\n", rid, global->rangesize));
334                 return NT_STATUS_UNSUCCESSFUL;
335         }
336         map->xid.id = global->minvalue +
337             (global->rangesize * domain->domainnum)+rid;
338         map->xid.type = ID_TYPE_BOTH;
339
340         /* We **really** should have some way of validating
341            the SID exists and is the correct type here.  But
342            that is a deficiency in the idmap_rid design. */
343
344         map->status = ID_MAPPED;
345
346         return NT_STATUS_OK;
347 }
348
349 /**********************************
350  lookup a set of unix ids.
351 **********************************/
352
353 static NTSTATUS idmap_autorid_unixids_to_sids(struct idmap_domain *dom,
354                                               struct id_map **ids)
355 {
356         struct idmap_tdb_common_context *commoncfg;
357         struct autorid_global_config *globalcfg;
358         NTSTATUS ret;
359         int i;
360         int num_tomap = 0;
361         int num_mapped = 0;
362
363         /* initialize the status to avoid surprise */
364         for (i = 0; ids[i]; i++) {
365                 ids[i]->status = ID_UNKNOWN;
366                 num_tomap++;
367         }
368
369         commoncfg =
370             talloc_get_type_abort(dom->private_data,
371                                   struct idmap_tdb_common_context);
372
373         globalcfg = talloc_get_type(commoncfg->private_data,
374                                     struct autorid_global_config);
375
376         for (i = 0; ids[i]; i++) {
377
378                 ret = idmap_autorid_id_to_sid(globalcfg, dom, ids[i]);
379
380                 if ((!NT_STATUS_IS_OK(ret)) &&
381                     (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
382                         /* some fatal error occurred, log it */
383                         DEBUG(3, ("Unexpected error resolving an ID "
384                                   " (%d)\n", ids[i]->xid.id));
385                         goto failure;
386                 }
387
388                 if (NT_STATUS_IS_OK(ret) && ids[i]->status == ID_MAPPED) {
389                         num_mapped++;
390                 }
391
392         }
393
394         if (num_tomap == num_mapped) {
395                 return NT_STATUS_OK;
396         } else if (num_mapped == 0) {
397                 return NT_STATUS_NONE_MAPPED;
398         }
399
400         return STATUS_SOME_UNMAPPED;
401
402
403       failure:
404         return ret;
405 }
406
407 /*
408  * map a SID to xid using the idmap_tdb like pool
409  */
410 static NTSTATUS idmap_autorid_map_sid_to_id(struct idmap_domain *dom,
411                                             struct id_map *map,
412                                             struct idmap_tdb_common_context *ctx)
413 {
414         NTSTATUS ret;
415         int res;
416
417         /* see if we already have a mapping */
418         ret = idmap_tdb_common_sid_to_unixid(dom, map);
419
420         if (NT_STATUS_IS_OK(ret)) {
421                 map->status = ID_MAPPED;
422                 return ret;
423         }
424
425         /* bad things happened */
426         if (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
427                 DEBUG(1, ("Looking up SID->ID mapping for %s failed\n",
428                           sid_string_dbg(map->sid)));
429                 return ret;
430         }
431
432         if (dom->read_only) {
433                 DEBUG(3, ("Not allocating new mapping for %s, because backend "
434                           "is read-only\n", sid_string_dbg(map->sid)));
435                 return NT_STATUS_NONE_MAPPED;
436         }
437
438         DEBUG(10, ("Creating new mapping in pool for %s\n",
439                    sid_string_dbg(map->sid)));
440
441         /* create new mapping */
442         res = dbwrap_transaction_start(ctx->db);
443         if (res != 0) {
444                 DEBUG(2, ("transaction_start failed\n"));
445                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
446         }
447
448         ret = idmap_tdb_common_new_mapping(dom, map);
449
450         map->status = (NT_STATUS_IS_OK(ret))?ID_MAPPED:ID_UNMAPPED;
451
452         if (!NT_STATUS_IS_OK(ret)) {
453                 if (dbwrap_transaction_cancel(ctx->db) != 0) {
454                         smb_panic("Cancelling transaction failed");
455                 }
456                 return ret;
457         }
458
459         res = dbwrap_transaction_commit(ctx->db);
460         if (res == 0) {
461                 return ret;
462         }
463
464         DEBUG(2, ("transaction_commit failed\n"));
465         return NT_STATUS_INTERNAL_DB_CORRUPTION;
466
467 }
468
469 /**********************************
470  lookup a set of sids.
471 **********************************/
472
473 static NTSTATUS idmap_autorid_sids_to_unixids(struct idmap_domain *dom,
474                                               struct id_map **ids)
475 {
476         struct idmap_tdb_common_context *commoncfg;
477         struct autorid_global_config *global;
478         NTSTATUS ret;
479         int i;
480         int num_tomap = 0;
481         int num_mapped = 0;
482
483         /* initialize the status to avoid surprise */
484         for (i = 0; ids[i]; i++) {
485                 ids[i]->status = ID_UNKNOWN;
486                 num_tomap++;
487         }
488
489         commoncfg =
490             talloc_get_type_abort(dom->private_data,
491                                   struct idmap_tdb_common_context);
492
493         global = talloc_get_type(commoncfg->private_data,
494                                  struct autorid_global_config);
495
496         for (i = 0; ids[i]; i++) {
497                 struct winbindd_tdc_domain *domain;
498                 struct autorid_domain_config domaincfg;
499                 uint32_t rid;
500                 struct dom_sid domainsid;
501
502                 ZERO_STRUCT(domaincfg);
503
504                 DEBUG(10, ("Trying to map %s\n", sid_string_dbg(ids[i]->sid)));
505
506                 sid_copy(&domainsid, ids[i]->sid);
507                 if (!sid_split_rid(&domainsid, &rid)) {
508                         DEBUG(4, ("Could not determine domain SID from %s, "
509                                   "ignoring mapping request\n",
510                                   sid_string_dbg(ids[i]->sid)));
511                         continue;
512                 }
513
514                 /* is this a well-known SID? */
515
516                 if (sid_check_is_wellknown_domain(&domainsid, NULL)) {
517
518                         DEBUG(10, ("SID %s is well-known, using pool\n",
519                                    sid_string_dbg(ids[i]->sid)));
520
521                         ret = idmap_autorid_map_sid_to_id(dom, ids[i],
522                                                           commoncfg);
523
524                         if (!NT_STATUS_IS_OK(ret) &&
525                             !NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
526                                 DEBUG(3, ("Unexpected error resolving "
527                                           "SID (%s)\n",
528                                           sid_string_dbg(ids[i]->sid)));
529                                 goto failure;
530                         }
531
532                         if (ids[i]->status == ID_MAPPED) {
533                                 num_mapped++;
534                         }
535
536                         continue;
537                 }
538
539                 /* BUILTIN is passdb's job */
540                 if (dom_sid_equal(&domainsid, &global_sid_Builtin) &&
541                     global->ignore_builtin) {
542                         DEBUG(10, ("Ignoring request for BUILTIN domain\n"));
543                         continue;
544                 }
545
546                 /*
547                  * Check if the domain is around
548                  */
549                 domain = wcache_tdc_fetch_domainbysid(talloc_tos(),
550                                                       &domainsid);
551                 if (domain == NULL) {
552                         DEBUG(10, ("Ignoring unknown domain sid %s\n",
553                                    sid_string_dbg(&domainsid)));
554                         continue;
555                 }
556                 TALLOC_FREE(domain);
557
558                 domaincfg.globalcfg = global;
559                 sid_to_fstring(domaincfg.sid, &domainsid);
560
561                 ret = idmap_autorid_get_domainrange(&domaincfg, dom->read_only);
562
563                 /* read-only mode and a new domain range would be required? */
564                 if (NT_STATUS_EQUAL(ret, NT_STATUS_NOT_FOUND) &&
565                     dom->read_only) {
566                         DEBUG(10, ("read-only is enabled, did not allocate "
567                                    "new range for domain %s\n",
568                                    sid_string_dbg(&domainsid)));
569                         continue;
570                 }
571
572                 if (!NT_STATUS_IS_OK(ret)) {
573                         DEBUG(3, ("Could not determine range for domain, "
574                                   "check previous messages for reason\n"));
575                         goto failure;
576                 }
577
578                 ret = idmap_autorid_sid_to_id(global, &domaincfg, ids[i]);
579
580                 if ((!NT_STATUS_IS_OK(ret)) &&
581                     (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
582                         /* some fatal error occurred, log it */
583                         DEBUG(3, ("Unexpected error resolving a SID (%s)\n",
584                                   sid_string_dbg(ids[i]->sid)));
585                         goto failure;
586                 }
587
588                 if (NT_STATUS_IS_OK(ret)) {
589                         num_mapped++;
590                 }
591         }
592
593         if (num_tomap == num_mapped) {
594                 return NT_STATUS_OK;
595         } else if (num_mapped == 0) {
596                 return NT_STATUS_NONE_MAPPED;
597         }
598
599         return STATUS_SOME_UNMAPPED;
600
601       failure:
602         return ret;
603
604 }
605
606 /* initialize the given HWM to 0 if it does not exist yet */
607 static NTSTATUS idmap_autorid_init_hwm(const char *hwm) {
608
609         NTSTATUS status;
610         uint32_t hwmval;
611
612         status = dbwrap_fetch_uint32_bystring(autorid_db, hwm, &hwmval);
613         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND))  {
614                 status = dbwrap_trans_store_int32_bystring(autorid_db, hwm, 0);
615                 if (!NT_STATUS_IS_OK(status)) {
616                         DEBUG(0,
617                               ("Unable to initialise HWM (%s) in autorid "
618                                "database: %s\n", hwm, nt_errstr(status)));
619                         return NT_STATUS_INTERNAL_DB_ERROR;
620                 }
621         } else if (!NT_STATUS_IS_OK(status)) {
622                 DEBUG(0, ("unable to fetch HWM (%s) from autorid "
623                           "database: %s\n", hwm,  nt_errstr(status)));
624                 return status;
625         }
626
627         return NT_STATUS_OK;
628 }
629
630 /*
631  * open and initialize the database which stores the ranges for the domains
632  */
633 static NTSTATUS idmap_autorid_db_init(void)
634 {
635         NTSTATUS status;
636
637         if (autorid_db) {
638                 /* its already open */
639                 return NT_STATUS_OK;
640         }
641
642         /* Open idmap repository */
643         autorid_db = db_open(NULL, state_path("autorid.tdb"), 0,
644                              TDB_DEFAULT, O_RDWR | O_CREAT, 0644,
645                              DBWRAP_LOCK_ORDER_1);
646
647         if (!autorid_db) {
648                 DEBUG(0, ("Unable to open idmap_autorid database '%s'\n",
649                           state_path("autorid.tdb")));
650                 return NT_STATUS_UNSUCCESSFUL;
651         }
652
653         /* Initialize high water mark for the currently used range to 0 */
654
655         status = idmap_autorid_init_hwm(HWM);
656         NT_STATUS_NOT_OK_RETURN(status);
657
658         status = idmap_autorid_init_hwm(ALLOC_HWM_UID);
659         NT_STATUS_NOT_OK_RETURN(status);
660
661         status = idmap_autorid_init_hwm(ALLOC_HWM_GID);
662
663         return status;
664 }
665
666 static struct autorid_global_config *idmap_autorid_loadconfig(TALLOC_CTX * ctx)
667 {
668
669         TDB_DATA data;
670         struct autorid_global_config *cfg;
671         unsigned long minvalue, rangesize, maxranges;
672         NTSTATUS status;
673
674         status = dbwrap_fetch_bystring(autorid_db, ctx, CONFIGKEY, &data);
675
676         if (!NT_STATUS_IS_OK(status)) {
677                 DEBUG(10, ("No saved config found\n"));
678                 return NULL;
679         }
680
681         cfg = talloc_zero(ctx, struct autorid_global_config);
682         if (!cfg) {
683                 return NULL;
684         }
685
686         if (sscanf((char *)data.dptr,
687                    "minvalue:%lu rangesize:%lu maxranges:%lu",
688                    &minvalue, &rangesize, &maxranges) != 3) {
689                 DEBUG(1,
690                       ("Found invalid configuration data"
691                        "creating new config\n"));
692                 return NULL;
693         }
694
695         cfg->minvalue = minvalue;
696         cfg->rangesize = rangesize;
697         cfg->maxranges = maxranges;
698
699         DEBUG(10, ("Loaded previously stored configuration "
700                    "minvalue:%d rangesize:%d\n",
701                    cfg->minvalue, cfg->rangesize));
702
703         return cfg;
704
705 }
706
707 static NTSTATUS idmap_autorid_saveconfig(struct autorid_global_config *cfg)
708 {
709
710         NTSTATUS status;
711         TDB_DATA data;
712         char *cfgstr;
713
714         cfgstr =
715             talloc_asprintf(talloc_tos(),
716                             "minvalue:%u rangesize:%u maxranges:%u",
717                             cfg->minvalue, cfg->rangesize, cfg->maxranges);
718
719         if (!cfgstr) {
720                 return NT_STATUS_NO_MEMORY;
721         }
722
723         data = string_tdb_data(cfgstr);
724
725         status = dbwrap_trans_store_bystring(autorid_db, CONFIGKEY,
726                                              data, TDB_REPLACE);
727
728         talloc_free(cfgstr);
729
730         return status;
731 }
732
733 static NTSTATUS idmap_autorid_preallocate_wellknown(struct idmap_domain *dom)
734 {
735         const char *groups[] = { "S-1-1-0", "S-1-2-0", "S-1-2-1",
736                 "S-1-3-0", "S-1-3-1", "S-1-3-2", "S-1-3-3", "S-1-3-4",
737                 "S-1-5-1", "S-1-5-2", "S-1-5-3", "S-1-5-4", "S-1-5-6",
738                 "S-1-5-7", "S-1-5-8", "S-1-5-9", "S-1-5-10", "S-1-5-11",
739                 "S-1-5-12", "S-1-5-13", "S-1-5-14", "S-1-5-15",
740                 "S-1-5-17", "S-1-5-18", "S-1-5-19", "S-1-5-20"
741         };
742
743         struct id_map **maps;
744         int i, num;
745         NTSTATUS status;
746
747         if (dom->read_only) {
748                 return NT_STATUS_OK;
749         }
750
751         num = sizeof(groups)/sizeof(char*);
752
753         maps = talloc_zero_array(talloc_tos(), struct id_map*, num+1);
754         if (!maps) {
755                 return NT_STATUS_NO_MEMORY;
756         }
757
758         for (i = 0; i < num; i++) {
759                 maps[i] = talloc(maps, struct id_map);
760                 maps[i]->xid.type = ID_TYPE_GID;
761                 maps[i]->sid = dom_sid_parse_talloc(maps, groups[i]);
762         }
763
764         maps[num] = NULL;
765
766         status = idmap_autorid_sids_to_unixids(dom, maps);
767
768         DEBUG(10,("Preallocation run finished with status %s\n",
769                   nt_errstr(status)));
770
771         talloc_free(maps);
772
773         return NT_STATUS_IS_OK(status)?NT_STATUS_OK:NT_STATUS_UNSUCCESSFUL;
774 }
775
776 static NTSTATUS idmap_autorid_initialize(struct idmap_domain *dom)
777 {
778         struct idmap_tdb_common_context *commonconfig;
779         struct autorid_global_config *config;
780         struct autorid_global_config *storedconfig = NULL;
781         NTSTATUS status;
782         uint32_t hwm;
783
784         if (!strequal(dom->name, "*")) {
785                 DEBUG(0, ("idmap_autorid_initialize: Error: autorid configured "
786                           "for domain '%s'. But autorid can only be used for "
787                           "the default idmap configuration.\n", dom->name));
788                 return NT_STATUS_INVALID_PARAMETER;
789         }
790
791         commonconfig = talloc_zero(dom, struct idmap_tdb_common_context);
792         if (!commonconfig) {
793                 DEBUG(0, ("Out of memory!\n"));
794                 return NT_STATUS_NO_MEMORY;
795         }
796
797         commonconfig->rw_ops = talloc_zero(commonconfig, struct idmap_rw_ops);
798         if (commonconfig->rw_ops == NULL) {
799                 DEBUG(0, ("Out of memory!\n"));
800                 return NT_STATUS_NO_MEMORY;
801         }
802
803         config = talloc_zero(commonconfig, struct autorid_global_config);
804         if (!config) {
805                 DEBUG(0, ("Out of memory!\n"));
806                 return NT_STATUS_NO_MEMORY;
807         }
808
809         status = idmap_autorid_db_init();
810         if (!NT_STATUS_IS_OK(status)) {
811                 goto error;
812         }
813
814         config->minvalue = dom->low_id;
815         config->rangesize = lp_parm_int(-1, "idmap config *",
816                                         "rangesize", 100000);
817
818         if (config->rangesize < 2000) {
819                 DEBUG(1, ("autorid rangesize must be at least 2000\n"));
820                 status = NT_STATUS_INVALID_PARAMETER;
821                 goto error;
822         }
823
824         config->maxranges = (dom->high_id - dom->low_id + 1) /
825             config->rangesize;
826
827         if (config->maxranges == 0) {
828                 DEBUG(1, ("allowed uid range is smaller then rangesize, "
829                           "increase uid range or decrease rangesize\n"));
830                 status = NT_STATUS_INVALID_PARAMETER;
831                 goto error;
832         }
833
834         /* check if the high-low limit is a multiple of the rangesize */
835         if ((dom->high_id - dom->low_id + 1) % config->rangesize != 0) {
836                 DEBUG(5, ("High uid-low uid difference of %d "
837                           "is not a multiple of the rangesize %d, "
838                           "limiting ranges to lower boundary number of %d\n",
839                           (dom->high_id - dom->low_id + 1), config->rangesize,
840                           config->maxranges));
841         }
842
843         DEBUG(10, ("Current configuration in config is "
844                    "minvalue:%d rangesize:%d maxranges:%d\n",
845                    config->minvalue, config->rangesize, config->maxranges));
846
847         /* read previously stored config and current HWM */
848         storedconfig = idmap_autorid_loadconfig(talloc_tos());
849
850         status = dbwrap_fetch_uint32_bystring(autorid_db, HWM, &hwm);
851         if (!NT_STATUS_IS_OK(status)) {
852                 DEBUG(1, ("Fatal error while fetching current "
853                           "HWM value: %s\n", nt_errstr(status)));
854                 status = NT_STATUS_INTERNAL_ERROR;
855                 goto error;
856         }
857
858         /* did the minimum value or rangesize change? */
859         if (storedconfig &&
860             ((storedconfig->minvalue != config->minvalue) ||
861              (storedconfig->rangesize != config->rangesize))) {
862                 DEBUG(1, ("New configuration values for rangesize or "
863                           "minimum uid value conflict with previously "
864                           "used values! Aborting initialization\n"));
865                 status = NT_STATUS_INVALID_PARAMETER;
866                 goto error;
867         }
868
869         /*
870          * has the highest uid value been reduced to setting that is not
871          * sufficient any more for already existing ranges?
872          */
873         if (hwm > config->maxranges) {
874                 DEBUG(1, ("New upper uid limit is too low to cover "
875                           "existing mappings! Aborting initialization\n"));
876                 status = NT_STATUS_INVALID_PARAMETER;
877                 goto error;
878         }
879
880         status = idmap_autorid_saveconfig(config);
881
882         if (!NT_STATUS_IS_OK(status)) {
883                 DEBUG(1, ("Failed to store configuration data!\n"));
884                 goto error;
885         }
886
887         DEBUG(5, ("%d domain ranges with a size of %d are available\n",
888                   config->maxranges, config->rangesize));
889
890         config->ignore_builtin = lp_parm_bool(-1, "idmap config *",
891                                               "ignore builtin", false);
892
893         /* fill the TDB common configuration */
894         commonconfig->private_data = config;
895
896         commonconfig->db = autorid_db;
897         commonconfig->max_id = config->rangesize -1;
898         commonconfig->hwmkey_uid = ALLOC_HWM_UID;
899         commonconfig->hwmkey_gid = ALLOC_HWM_GID;
900         commonconfig->rw_ops->get_new_id = idmap_autorid_allocate_id;
901         commonconfig->rw_ops->set_mapping = idmap_tdb_common_set_mapping;
902
903         dom->private_data = commonconfig;
904
905         /* preallocate well-known SIDs in the pool */
906         status = idmap_autorid_preallocate_wellknown(dom);
907
908         goto done;
909
910 error:
911         talloc_free(config);
912
913 done:
914         talloc_free(storedconfig);
915
916         return status;
917 }
918
919 /*
920   Close the idmap tdb instance
921 */
922 static struct idmap_methods autorid_methods = {
923         .init = idmap_autorid_initialize,
924         .unixids_to_sids = idmap_autorid_unixids_to_sids,
925         .sids_to_unixids = idmap_autorid_sids_to_unixids,
926         .allocate_id     = idmap_autorid_allocate_id
927 };
928
929 NTSTATUS samba_init_module(void)
930 {
931         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION,
932                                   "autorid", &autorid_methods);
933 }