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