s3:utils: let smbstatus report anonymous signing/encryption explicitly
[samba.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 "idmap_autorid_tdb.h"
77 #include "winbindd.h"
78 #include "idmap.h"
79 #include "idmap_rw.h"
80 #include "../libcli/security/dom_sid.h"
81 #include "libsmb/samlogon_cache.h"
82 #include "passdb/machine_sid.h"
83 #include "lib/util/string_wrappers.h"
84
85 #undef DBGC_CLASS
86 #define DBGC_CLASS DBGC_IDMAP
87
88 #define IDMAP_AUTORID_ALLOC_RESERVED 500
89
90 /* handle to the tdb storing domain <-> range assignments */
91 static struct db_context *autorid_db;
92
93 static bool ignore_builtin = false;
94
95 static NTSTATUS idmap_autorid_get_alloc_range(struct idmap_domain *dom,
96                                         struct autorid_range_config *range)
97 {
98         NTSTATUS status;
99
100         ZERO_STRUCT(*range);
101
102         fstrcpy(range->domsid, ALLOC_RANGE);
103
104         status = idmap_autorid_get_domainrange(autorid_db,
105                                                range,
106                                                dom->read_only);
107
108         return status;
109 }
110
111 static NTSTATUS idmap_autorid_allocate_id(struct idmap_domain *dom,
112                                           struct unixid *xid) {
113
114         NTSTATUS ret;
115         struct autorid_range_config range;
116
117         if (dom->read_only) {
118                 DEBUG(3, ("Backend is read-only, refusing "
119                           "new allocation request\n"));
120                 return NT_STATUS_UNSUCCESSFUL;
121         }
122
123         /* fetch the range for the allocation pool */
124
125         ret = idmap_autorid_get_alloc_range(dom, &range);
126         if (!NT_STATUS_IS_OK(ret)) {
127                 DEBUG(3, ("Could not determine range for allocation pool, "
128                           "check previous messages for reason\n"));
129                 return ret;
130         }
131
132         ret = idmap_tdb_common_get_new_id(dom, xid);
133
134         if (!NT_STATUS_IS_OK(ret)) {
135                 DEBUG(1, ("Fatal error while allocating new ID!\n"));
136                 return ret;
137         }
138
139         xid->id = xid->id + range.low_id;
140
141         DEBUG(10, ("Returned new %s %d from allocation range\n",
142                    (xid->type==ID_TYPE_UID)?"uid":"gid", xid->id));
143
144         return ret;
145 }
146
147 /*
148  * map a xid to SID using the idmap_tdb like pool
149  */
150 static NTSTATUS idmap_autorid_id_to_sid_alloc(struct idmap_domain *dom,
151                                               struct id_map *map)
152 {
153         NTSTATUS ret;
154
155         /* look out for the mapping */
156         ret = idmap_tdb_common_unixid_to_sid(dom, map);
157
158         if (NT_STATUS_IS_OK(ret)) {
159                 map->status = ID_MAPPED;
160                 return ret;
161         }
162
163         map->status = ID_UNKNOWN;
164
165         DEBUG(10, ("no ID->SID mapping for %d could be found\n", map->xid.id));
166
167         return ret;
168 }
169
170 static NTSTATUS idmap_autorid_id_to_sid(struct autorid_global_config *cfg,
171                                         struct idmap_domain *dom,
172                                         struct id_map *map)
173 {
174         uint32_t range_number;
175         uint32_t domain_range_index;
176         uint32_t normalized_id;
177         uint32_t reduced_rid;
178         uint32_t rid;
179         TDB_DATA data = tdb_null;
180         char *keystr;
181         struct dom_sid domsid;
182         NTSTATUS status;
183         bool ok;
184         const char *q = NULL;
185
186         /* can this be one of our ids? */
187         if (map->xid.id < cfg->minvalue) {
188                 DEBUG(10, ("id %d is lower than minimum value, "
189                            "ignoring mapping request\n", map->xid.id));
190                 map->status = ID_UNKNOWN;
191                 return NT_STATUS_OK;
192         }
193
194         if (map->xid.id > (cfg->minvalue + cfg->rangesize * cfg->maxranges)) {
195                 DEBUG(10, ("id %d is outside of maximum id value, "
196                            "ignoring mapping request\n", map->xid.id));
197                 map->status = ID_UNKNOWN;
198                 return NT_STATUS_OK;
199         }
200
201         /* determine the range of this uid */
202
203         normalized_id = map->xid.id - cfg->minvalue;
204         range_number = normalized_id / cfg->rangesize;
205
206         keystr = talloc_asprintf(talloc_tos(), "%u", range_number);
207         if (!keystr) {
208                 return NT_STATUS_NO_MEMORY;
209         }
210
211         status = dbwrap_fetch_bystring(autorid_db, talloc_tos(), keystr, &data);
212         TALLOC_FREE(keystr);
213
214         if (!NT_STATUS_IS_OK(status)) {
215                 DEBUG(4, ("id %d belongs to range %d which does not have "
216                           "domain mapping, ignoring mapping request\n",
217                           map->xid.id, range_number));
218                 TALLOC_FREE(data.dptr);
219                 map->status = ID_UNKNOWN;
220                 return NT_STATUS_OK;
221         }
222
223         if ((data.dsize == 0) || (data.dptr[data.dsize-1] != '\0')) {
224                 DBG_WARNING("Invalid range %"PRIu32"\n", range_number);
225                 TALLOC_FREE(data.dptr);
226                 map->status = ID_UNKNOWN;
227                 return NT_STATUS_OK;
228         }
229
230         if (strncmp((const char *)data.dptr,
231                     ALLOC_RANGE,
232                     strlen(ALLOC_RANGE)) == 0) {
233                 /*
234                  * this is from the alloc range, check if there is a mapping
235                  */
236                 DEBUG(5, ("id %d belongs to allocation range, "
237                           "checking for mapping\n",
238                           map->xid.id));
239                 TALLOC_FREE(data.dptr);
240                 return idmap_autorid_id_to_sid_alloc(dom, map);
241         }
242
243         ok = dom_sid_parse_endp((const char *)data.dptr, &domsid, &q);
244         if (!ok) {
245                 TALLOC_FREE(data.dptr);
246                 map->status = ID_UNKNOWN;
247                 return NT_STATUS_OK;
248         }
249
250         /*
251          * Allow for sid#range_index, just sid is range index 0
252          */
253
254         switch (*q) {
255             case '\0':
256                     domain_range_index = 0;
257                     break;
258             case '#':
259                     if (sscanf(q+1, "%"SCNu32, &domain_range_index) == 1) {
260                             break;
261                     }
262                     /* If we end up here, something weird is in the record. */
263
264                     FALL_THROUGH;
265             default:
266                     DBG_DEBUG("SID/domain range: %s\n",
267                               (const char *)data.dptr);
268                     TALLOC_FREE(data.dptr);
269                     map->status = ID_UNKNOWN;
270                     return NT_STATUS_OK;
271         }
272
273         TALLOC_FREE(data.dptr);
274
275         reduced_rid = normalized_id % cfg->rangesize;
276         rid = reduced_rid + domain_range_index * cfg->rangesize;
277
278         sid_compose(map->sid, &domsid, rid);
279
280         /* We **really** should have some way of validating
281            the SID exists and is the correct type here.  But
282            that is a deficiency in the idmap_rid design. */
283
284         map->status = ID_MAPPED;
285         map->xid.type = ID_TYPE_BOTH;
286
287         return NT_STATUS_OK;
288 }
289
290 /**********************************
291  Single sid to id lookup function.
292 **********************************/
293
294 static NTSTATUS idmap_autorid_sid_to_id_rid(
295                                         uint32_t rangesize,
296                                         uint32_t low_id,
297                                         struct id_map *map)
298 {
299         uint32_t rid;
300         uint32_t reduced_rid;
301
302         sid_peek_rid(map->sid, &rid);
303
304         reduced_rid = rid % rangesize;
305
306         map->xid.id = reduced_rid + low_id;
307         map->xid.type = ID_TYPE_BOTH;
308         map->status = ID_MAPPED;
309
310         return NT_STATUS_OK;
311 }
312
313 /**********************************
314  lookup a set of unix ids.
315 **********************************/
316
317 static NTSTATUS idmap_autorid_unixids_to_sids(struct idmap_domain *dom,
318                                               struct id_map **ids)
319 {
320         struct idmap_tdb_common_context *commoncfg;
321         struct autorid_global_config *globalcfg;
322         NTSTATUS ret;
323         int i;
324         int num_tomap = 0;
325         int num_mapped = 0;
326
327         /* initialize the status to avoid surprise */
328         for (i = 0; ids[i]; i++) {
329                 ids[i]->status = ID_UNKNOWN;
330                 num_tomap++;
331         }
332
333         commoncfg =
334             talloc_get_type_abort(dom->private_data,
335                                   struct idmap_tdb_common_context);
336
337         globalcfg = talloc_get_type(commoncfg->private_data,
338                                     struct autorid_global_config);
339
340         for (i = 0; ids[i]; i++) {
341
342                 ret = idmap_autorid_id_to_sid(globalcfg, dom, ids[i]);
343
344                 if ((!NT_STATUS_IS_OK(ret)) &&
345                     (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
346                         /* some fatal error occurred, log it */
347                         DBG_NOTICE("Unexpected error resolving an ID "
348                                    "(%d): %s\n", ids[i]->xid.id,
349                                    nt_errstr(ret));
350                         goto failure;
351                 }
352
353                 if (NT_STATUS_IS_OK(ret) && ids[i]->status == ID_MAPPED) {
354                         num_mapped++;
355                 }
356
357         }
358
359         if (num_tomap == num_mapped) {
360                 return NT_STATUS_OK;
361         }
362         if (num_mapped == 0) {
363                 return NT_STATUS_NONE_MAPPED;
364         }
365
366         return STATUS_SOME_UNMAPPED;
367
368
369       failure:
370         return ret;
371 }
372
373 static bool idmap_autorid_sid_is_special(struct dom_sid *sid)
374 {
375         bool match;
376
377         match = sid_check_is_in_wellknown_domain(sid);
378         if (match) {
379                 return true;
380         }
381
382         return false;
383 }
384
385 static NTSTATUS idmap_autorid_sid_to_id_special(struct idmap_domain *dom,
386                                                 struct id_map *map)
387 {
388         struct idmap_tdb_common_context *common =
389                 talloc_get_type_abort(dom->private_data,
390                                       struct idmap_tdb_common_context);
391         uint32_t count;
392         struct autorid_range_config range;
393         NTSTATUS status;
394         uint32_t free_id;
395
396         status = idmap_autorid_get_alloc_range(dom, &range);
397         if (!NT_STATUS_IS_OK(status)) {
398                 return status;
399         }
400
401         /* Take the next free ID, counting from the top */
402         free_id = 0;
403         for (count = 0; count < IDMAP_AUTORID_ALLOC_RESERVED; count++) {
404                 struct id_map test_map;
405                 struct dom_sid sid;
406
407                 test_map.sid = &sid;
408                 test_map.xid.type = map->xid.type;
409                 test_map.xid.id = range.high_id - count;
410                 test_map.status = ID_UNKNOWN;
411
412                 status = idmap_tdb_common_unixid_to_sid(dom, &test_map);
413                 if (NT_STATUS_EQUAL(NT_STATUS_NONE_MAPPED, status)) {
414                         free_id = test_map.xid.id;
415                         break;
416                 }
417
418                 if (!NT_STATUS_IS_OK(status)) {
419                         /* error - get out */
420                         return status;
421                 }
422
423                 /* mapping exists - try next ID */
424         }
425
426         if (free_id == 0) {
427                 return NT_STATUS_NONE_MAPPED;
428         }
429
430         map->status = ID_MAPPED;
431         map->xid.id = free_id;
432
433         status = common->rw_ops->set_mapping(dom, map);
434         if (!NT_STATUS_IS_OK(status)) {
435                 DEBUG(2, ("Error storing new mapping: %s\n",
436                           nt_errstr(status)));
437                 return status;
438         }
439
440         return NT_STATUS_OK;
441 }
442
443 struct idmap_autorid_sid_to_id_alloc_ctx {
444         struct idmap_domain *dom;
445         struct id_map *map;
446 };
447
448 static NTSTATUS idmap_autorid_sid_to_id_alloc_action(
449                                 struct db_context *db,
450                                 void *private_data)
451 {
452         struct idmap_autorid_sid_to_id_alloc_ctx *ctx;
453
454         ctx = (struct idmap_autorid_sid_to_id_alloc_ctx *)private_data;
455
456         if (idmap_autorid_sid_is_special(ctx->map->sid)) {
457                 struct dom_sid_buf buf;
458                 NTSTATUS ret;
459
460                 ret = idmap_autorid_sid_to_id_special(ctx->dom, ctx->map);
461                 if (NT_STATUS_IS_OK(ret)) {
462                         return NT_STATUS_OK;
463                 }
464                 if (!NT_STATUS_EQUAL(NT_STATUS_NONE_MAPPED, ret)) {
465                         return ret;
466                 }
467
468                 DEBUG(10, ("Special sid %s not mapped. falling back to "
469                            "regular allocation\n",
470                            dom_sid_str_buf(ctx->map->sid, &buf)));
471         }
472
473         return idmap_tdb_common_new_mapping(ctx->dom, ctx->map);
474 }
475
476 /*
477  * map a SID to xid using the idmap_tdb like pool
478  */
479 static NTSTATUS idmap_autorid_sid_to_id_alloc(
480                                         struct idmap_tdb_common_context *ctx,
481                                         struct idmap_domain *dom,
482                                         struct id_map *map)
483 {
484         NTSTATUS ret;
485         struct idmap_autorid_sid_to_id_alloc_ctx alloc_ctx;
486         struct dom_sid_buf buf;
487
488         map->status = ID_UNKNOWN;
489
490         /* see if we already have a mapping */
491         ret = idmap_tdb_common_sid_to_unixid(dom, map);
492
493         if (NT_STATUS_IS_OK(ret)) {
494                 map->status = ID_MAPPED;
495                 return ret;
496         }
497
498         /* bad things happened */
499         if (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED)) {
500                 DEBUG(1, ("Looking up SID->ID mapping for %s failed: %s\n",
501                           dom_sid_str_buf(map->sid, &buf),
502                           nt_errstr(ret)));
503                 return ret;
504         }
505
506         if (dom->read_only) {
507                 DEBUG(3, ("Not allocating new mapping for %s, because backend "
508                           "is read-only\n",
509                           dom_sid_str_buf(map->sid, &buf)));
510                 map->status = ID_UNMAPPED;
511                 return NT_STATUS_NONE_MAPPED;
512         }
513
514         DEBUG(10, ("Creating new mapping in pool for %s\n",
515                    dom_sid_str_buf(map->sid, &buf)));
516
517         alloc_ctx.dom = dom;
518         alloc_ctx.map = map;
519
520         ret = dbwrap_trans_do(ctx->db, idmap_autorid_sid_to_id_alloc_action,
521                               &alloc_ctx);
522         if (!NT_STATUS_IS_OK(ret)) {
523                 DEBUG(1, ("Failed to create a new mapping in alloc range: %s\n",
524                           nt_errstr(ret)));
525                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
526         }
527
528         map->status = ID_MAPPED;
529         return NT_STATUS_OK;
530 }
531
532 static bool idmap_autorid_domsid_is_for_alloc(struct dom_sid *sid)
533 {
534         bool match;
535
536         match = sid_check_is_wellknown_domain(sid, NULL);
537         if (match) {
538                 return true;
539         }
540
541         return false;
542 }
543
544 static NTSTATUS idmap_autorid_sid_to_id(struct idmap_tdb_common_context *common,
545                                         struct idmap_domain *dom,
546                                         struct id_map *map)
547 {
548         struct autorid_global_config *global =
549                 talloc_get_type_abort(common->private_data,
550                                       struct autorid_global_config);
551         struct autorid_range_config range;
552         uint32_t rid;
553         struct dom_sid domainsid;
554         struct dom_sid_buf buf;
555         NTSTATUS ret;
556
557         ZERO_STRUCT(range);
558         map->status = ID_UNKNOWN;
559
560         DEBUG(10, ("Trying to map %s\n", dom_sid_str_buf(map->sid, &buf)));
561
562         sid_copy(&domainsid, map->sid);
563         if (!sid_split_rid(&domainsid, &rid)) {
564                 DEBUG(4, ("Could not determine domain SID from %s, "
565                           "ignoring mapping request\n",
566                           dom_sid_str_buf(map->sid, &buf)));
567                 map->status = ID_UNMAPPED;
568                 return NT_STATUS_NONE_MAPPED;
569         }
570
571         if (idmap_autorid_domsid_is_for_alloc(&domainsid)) {
572                 DEBUG(10, ("SID %s is for ALLOC range.\n",
573                            dom_sid_str_buf(map->sid, &buf)));
574
575                 return idmap_autorid_sid_to_id_alloc(common, dom, map);
576         }
577
578         if (dom_sid_equal(&domainsid, &global_sid_Builtin) && ignore_builtin) {
579                 DEBUG(10, ("Ignoring request for BUILTIN domain\n"));
580                 map->status = ID_UNMAPPED;
581                 return NT_STATUS_NONE_MAPPED;
582         }
583
584         sid_to_fstring(range.domsid, &domainsid);
585
586         range.domain_range_index = rid / (global->rangesize);
587
588         ret = idmap_autorid_getrange(autorid_db, range.domsid,
589                                      range.domain_range_index,
590                                      &range.rangenum, &range.low_id);
591         if (NT_STATUS_IS_OK(ret)) {
592                 return idmap_autorid_sid_to_id_rid(
593                         global->rangesize, range.low_id, map);
594         }
595
596         if (dom->read_only) {
597                 DBG_DEBUG("read-only is enabled, did not allocate "
598                           "new range for domain %s\n", range.domsid);
599                 map->status = ID_UNMAPPED;
600                 return NT_STATUS_NONE_MAPPED;
601         }
602
603         /*
604          * Check if we should allocate a domain range. We need to
605          * protect against unknown domains to not fill our ranges
606          * needlessly.
607          */
608
609         if (sid_check_is_builtin(&domainsid) ||
610             sid_check_is_our_sam(&domainsid)) {
611                 goto allocate;
612         }
613
614         {
615                 struct winbindd_domain *domain;
616
617                 /*
618                  * Deterministic check for domain members: We can be
619                  * sure that the domain we are member of is worth to
620                  * add a mapping for.
621                  */
622
623                 domain = find_our_domain();
624                 if ((domain != NULL) &&
625                     dom_sid_equal(&domain->sid, &domainsid)) {
626                         goto allocate;
627                 }
628         }
629
630         /*
631          * If we have already allocated range index 0, this domain is
632          * worth allocating for in higher ranges.
633          */
634         if (range.domain_range_index != 0) {
635                 uint32_t zero_rangenum, zero_low_id;
636
637                 ret = idmap_autorid_getrange(autorid_db, range.domsid, 0,
638                                              &zero_rangenum, &zero_low_id);
639                 if (NT_STATUS_IS_OK(ret)) {
640                         goto allocate;
641                 }
642         }
643
644         /*
645          * If the caller already did a lookup sid and made sure the
646          * domain sid is valid, we can allocate a new range.
647          *
648          * Currently the winbindd parent already does a lookup sids
649          * first, but hopefully changes in future. If the
650          * caller knows the domain sid, ID_TYPE_BOTH should be
651          * passed instead of ID_TYPE_NOT_SPECIFIED.
652          */
653         if (map->xid.type != ID_TYPE_NOT_SPECIFIED) {
654                 goto allocate;
655         }
656
657         /*
658          * Check of last resort: A domain is valid if a user from that
659          * domain has recently logged in. The samlogon_cache these
660          * days also stores the domain sid.
661          *
662          * We used to check the list of trusted domains we received
663          * from "our" dc, but this is not reliable enough.
664          */
665         if (netsamlogon_cache_have(&domainsid)) {
666                 goto allocate;
667         }
668
669         /*
670          * Nobody knows this domain, so refuse to allocate a fresh
671          * range.
672          */
673
674         DBG_NOTICE("Allocating range for domain %s required type_hint\n", range.domsid);
675         map->status = ID_REQUIRE_TYPE;
676         return NT_STATUS_SOME_NOT_MAPPED;
677
678 allocate:
679         ret = idmap_autorid_acquire_range(autorid_db, &range);
680         if (!NT_STATUS_IS_OK(ret)) {
681                 DBG_NOTICE("Could not determine range for domain: %s, "
682                            "check previous messages for reason\n",
683                            nt_errstr(ret));
684                 return ret;
685         }
686
687         return idmap_autorid_sid_to_id_rid(global->rangesize, range.low_id,
688                                            map);
689 }
690
691 /**********************************
692  lookup a set of sids.
693 **********************************/
694
695 static NTSTATUS idmap_autorid_sids_to_unixids(struct idmap_domain *dom,
696                                               struct id_map **ids)
697 {
698         struct idmap_tdb_common_context *commoncfg;
699         NTSTATUS ret;
700         size_t i;
701         size_t num_tomap = 0;
702         size_t num_mapped = 0;
703         size_t num_required = 0;
704
705         /* initialize the status to avoid surprise */
706         for (i = 0; ids[i]; i++) {
707                 ids[i]->status = ID_UNKNOWN;
708                 num_tomap++;
709         }
710
711         commoncfg =
712             talloc_get_type_abort(dom->private_data,
713                                   struct idmap_tdb_common_context);
714
715         for (i = 0; ids[i]; i++) {
716                 ret = idmap_autorid_sid_to_id(commoncfg, dom, ids[i]);
717                 if (NT_STATUS_EQUAL(ret, NT_STATUS_SOME_NOT_MAPPED) &&
718                     ids[i]->status == ID_REQUIRE_TYPE)
719                 {
720                         num_required++;
721                         continue;
722                 }
723                 if ((!NT_STATUS_IS_OK(ret)) &&
724                     (!NT_STATUS_EQUAL(ret, NT_STATUS_NONE_MAPPED))) {
725                         struct dom_sid_buf buf;
726                         /* some fatal error occurred, log it */
727                         DEBUG(3, ("Unexpected error resolving a SID (%s)\n",
728                                   dom_sid_str_buf(ids[i]->sid, &buf)));
729                         return ret;
730                 }
731
732                 if (NT_STATUS_IS_OK(ret) && ids[i]->status == ID_MAPPED) {
733                         num_mapped++;
734                 }
735         }
736
737         if (num_tomap == num_mapped) {
738                 return NT_STATUS_OK;
739         } else if (num_required > 0) {
740                 return STATUS_SOME_UNMAPPED;
741         } else if (num_mapped == 0) {
742                 return NT_STATUS_NONE_MAPPED;
743         }
744
745         return STATUS_SOME_UNMAPPED;
746 }
747
748 static NTSTATUS idmap_autorid_preallocate_wellknown(struct idmap_domain *dom)
749 {
750         const char *groups[] = { "S-1-1-0", "S-1-2-0", "S-1-2-1",
751                 "S-1-3-0", "S-1-3-1", "S-1-3-2", "S-1-3-3", "S-1-3-4",
752                 "S-1-5-1", "S-1-5-2", "S-1-5-3", "S-1-5-4", "S-1-5-6",
753                 "S-1-5-7", "S-1-5-8", "S-1-5-9", "S-1-5-10", "S-1-5-11",
754                 "S-1-5-12", "S-1-5-13", "S-1-5-14", "S-1-5-15",
755                 "S-1-5-17", "S-1-5-18", "S-1-5-19", "S-1-5-20"
756         };
757
758         struct id_map **maps;
759         int i, num;
760         NTSTATUS status;
761
762         if (dom->read_only) {
763                 return NT_STATUS_OK;
764         }
765
766         num = ARRAY_SIZE(groups);
767
768         maps = talloc_array(talloc_tos(), struct id_map*, num+1);
769         if (!maps) {
770                 return NT_STATUS_NO_MEMORY;
771         }
772
773         for (i = 0; i < num; i++) {
774                 maps[i] = talloc(maps, struct id_map);
775                 if (maps[i] == NULL) {
776                         talloc_free(maps);
777                         return NT_STATUS_NO_MEMORY;
778                 }
779                 maps[i]->xid.type = ID_TYPE_GID;
780                 maps[i]->sid = dom_sid_parse_talloc(maps, groups[i]);
781         }
782
783         maps[num] = NULL;
784
785         status = idmap_autorid_sids_to_unixids(dom, maps);
786
787         DEBUG(10,("Preallocation run finished with status %s\n",
788                   nt_errstr(status)));
789
790         talloc_free(maps);
791
792         return NT_STATUS_IS_OK(status)?NT_STATUS_OK:NT_STATUS_UNSUCCESSFUL;
793 }
794
795 static NTSTATUS idmap_autorid_initialize_action(struct db_context *db,
796                                                 void *private_data)
797 {
798         struct idmap_domain *dom;
799         struct idmap_tdb_common_context *common;
800         struct autorid_global_config *config;
801         NTSTATUS status;
802
803         dom = (struct idmap_domain *)private_data;
804         common = (struct idmap_tdb_common_context *)dom->private_data;
805         config = (struct autorid_global_config *)common->private_data;
806
807         status = idmap_autorid_init_hwms(db);
808         if (!NT_STATUS_IS_OK(status)) {
809                 return status;
810         }
811
812         status = idmap_autorid_saveconfig(db, config);
813         if (!NT_STATUS_IS_OK(status)) {
814                 DEBUG(1, ("Failed to store configuration data!\n"));
815                 return status;
816         }
817
818         status = idmap_autorid_preallocate_wellknown(dom);
819         if (!NT_STATUS_IS_OK(status)) {
820                 DEBUG(1, ("Failed to preallocate wellknown sids: %s\n",
821                           nt_errstr(status)));
822                 return status;
823         }
824
825         return NT_STATUS_OK;
826 }
827
828 static NTSTATUS idmap_autorid_initialize(struct idmap_domain *dom)
829 {
830         struct idmap_tdb_common_context *commonconfig;
831         struct autorid_global_config *config;
832         NTSTATUS status;
833         char *db_path;
834
835         if (!strequal(dom->name, "*")) {
836                 DEBUG(0, ("idmap_autorid_initialize: Error: autorid configured "
837                           "for domain '%s'. But autorid can only be used for "
838                           "the default idmap configuration.\n", dom->name));
839                 return NT_STATUS_INVALID_PARAMETER;
840         }
841
842         commonconfig = talloc_zero(dom, struct idmap_tdb_common_context);
843         if (!commonconfig) {
844                 DEBUG(0, ("Out of memory!\n"));
845                 return NT_STATUS_NO_MEMORY;
846         }
847         dom->private_data = commonconfig;
848
849         commonconfig->rw_ops = talloc_zero(commonconfig, struct idmap_rw_ops);
850         if (commonconfig->rw_ops == NULL) {
851                 DEBUG(0, ("Out of memory!\n"));
852                 return NT_STATUS_NO_MEMORY;
853         }
854
855         config = talloc_zero(commonconfig, struct autorid_global_config);
856         if (!config) {
857                 DEBUG(0, ("Out of memory!\n"));
858                 return NT_STATUS_NO_MEMORY;
859         }
860         commonconfig->private_data = config;
861
862         config->minvalue = dom->low_id;
863         config->rangesize = idmap_config_int("*", "rangesize", 100000);
864
865         config->maxranges = (dom->high_id - dom->low_id + 1) /
866             config->rangesize;
867
868         if (config->maxranges < 2) {
869                 DBG_WARNING("Allowed idmap range is not a least double the "
870                             "size of the rangesize. Please increase idmap "
871                             "range.\n");
872                 status = NT_STATUS_INVALID_PARAMETER;
873                 goto error;
874         }
875
876         /* check if the high-low limit is a multiple of the rangesize */
877         if ((dom->high_id - dom->low_id + 1) % config->rangesize != 0) {
878                 DEBUG(5, ("High uid-low uid difference of %d "
879                           "is not a multiple of the rangesize %d, "
880                           "limiting ranges to lower boundary number of %d\n",
881                           (dom->high_id - dom->low_id + 1), config->rangesize,
882                           config->maxranges));
883         }
884
885         DEBUG(5, ("%d domain ranges with a size of %d are available\n",
886                   config->maxranges, config->rangesize));
887
888         ignore_builtin = idmap_config_bool("*", "ignore builtin", false);
889
890         /* fill the TDB common configuration */
891
892         commonconfig->max_id = config->rangesize - 1
893                              - IDMAP_AUTORID_ALLOC_RESERVED;
894         commonconfig->hwmkey_uid = ALLOC_HWM_UID;
895         commonconfig->hwmkey_gid = ALLOC_HWM_GID;
896         commonconfig->rw_ops->get_new_id = idmap_autorid_allocate_id;
897         commonconfig->rw_ops->set_mapping = idmap_tdb_common_set_mapping;
898
899         db_path = state_path(talloc_tos(), "autorid.tdb");
900         if (db_path == NULL) {
901                 status = NT_STATUS_NO_MEMORY;
902                 goto error;
903         }
904
905         status = idmap_autorid_db_open(db_path,
906                                        NULL, /* TALLOC_CTX */
907                                        &autorid_db);
908         TALLOC_FREE(db_path);
909         if (!NT_STATUS_IS_OK(status)) {
910                 goto error;
911         }
912
913         commonconfig->db = autorid_db;
914
915         status = dbwrap_trans_do(autorid_db,
916                                  idmap_autorid_initialize_action,
917                                  dom);
918         if (!NT_STATUS_IS_OK(status)) {
919                 DEBUG(1, ("Failed to init the idmap database: %s\n",
920                           nt_errstr(status)));
921                 goto error;
922         }
923
924         goto done;
925
926 error:
927         talloc_free(config);
928
929 done:
930         return status;
931 }
932
933 static const struct idmap_methods autorid_methods = {
934         .init = idmap_autorid_initialize,
935         .unixids_to_sids = idmap_autorid_unixids_to_sids,
936         .sids_to_unixids = idmap_autorid_sids_to_unixids,
937         .allocate_id     = idmap_autorid_allocate_id
938 };
939
940 static_decl_idmap;
941 NTSTATUS idmap_autorid_init(TALLOC_CTX *ctx)
942 {
943         return smb_register_idmap(SMB_IDMAP_INTERFACE_VERSION,
944                                   "autorid", &autorid_methods);
945 }