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