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