21e15089e9e3d319b409ed6c922f0269681641a6
[obnox/samba/samba-obnox.git] / source3 / winbindd / idmap_autorid_tdb.c
1 /*
2  *  idmap_autorid_tdb: This file contains common code used by
3  *  idmap_autorid and net idmap autorid utilities. The common
4  *  code provides functions for performing various operations
5  *  on autorid.tdb
6  *
7  *  Copyright (C) Christian Ambach, 2010-2012
8  *  Copyright (C) Atul Kulkarni, 2013
9  *  Copyright (C) Michael Adam, 2012-2013
10  *
11  *  This program is free software; you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License as published by
13  *  the Free Software Foundation; either version 3 of the License, or
14  *  (at your option) any later version.
15  *
16  *  This program is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *  GNU General Public License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
23  *
24  */
25
26 #include "idmap_autorid_tdb.h"
27 #include "../libcli/security/dom_sid.h"
28
29 /**
30  * Build the database keystring for getting a range
31  * belonging to a domain sid and a range index.
32  */
33 static void idmap_autorid_build_keystr(const char *domsid,
34                                        uint32_t domain_range_index,
35                                        fstring keystr)
36 {
37         if (domain_range_index > 0) {
38                 fstr_sprintf(keystr, "%s#%"PRIu32,
39                              domsid, domain_range_index);
40         } else {
41                 fstrcpy(keystr, domsid);
42         }
43 }
44
45 static char *idmap_autorid_build_keystr_talloc(TALLOC_CTX *mem_ctx,
46                                               const char *domsid,
47                                               uint32_t domain_range_index)
48 {
49         char *keystr;
50
51         if (domain_range_index > 0) {
52                 keystr = talloc_asprintf(mem_ctx, "%s#%"PRIu32, domsid,
53                                          domain_range_index);
54         } else {
55                 keystr = talloc_strdup(mem_ctx, domsid);
56         }
57
58         return keystr;
59 }
60
61
62 static bool idmap_autorid_validate_sid(const char *sid)
63 {
64         struct dom_sid ignore;
65         if (sid == NULL) {
66                 return false;
67         }
68
69         if (strcmp(sid, ALLOC_RANGE) == 0) {
70                 return true;
71         }
72
73         return dom_sid_parse(sid, &ignore);
74 }
75
76 struct idmap_autorid_addrange_ctx {
77         struct autorid_range_config *range;
78         bool acquire;
79 };
80
81 static NTSTATUS idmap_autorid_addrange_action(struct db_context *db,
82                                               void *private_data)
83 {
84         struct idmap_autorid_addrange_ctx *ctx;
85         uint32_t requested_rangenum, stored_rangenum;
86         struct autorid_range_config *range;
87         bool acquire;
88         NTSTATUS ret;
89         uint32_t hwm;
90         char *numstr;
91         struct autorid_global_config *globalcfg;
92         fstring keystr;
93         uint32_t increment;
94         TALLOC_CTX *mem_ctx = NULL;
95
96         ctx = (struct idmap_autorid_addrange_ctx *)private_data;
97         range = ctx->range;
98         acquire = ctx->acquire;
99         requested_rangenum = range->rangenum;
100
101         if (db == NULL) {
102                 DEBUG(3, ("Invalid database argument: NULL"));
103                 return NT_STATUS_INVALID_PARAMETER;
104         }
105
106         if (range == NULL) {
107                 DEBUG(3, ("Invalid range argument: NULL"));
108                 return NT_STATUS_INVALID_PARAMETER;
109         }
110
111         DEBUG(10, ("Adding new range for domain %s "
112                    "(domain_range_index=%"PRIu32")\n",
113                    range->domsid, range->domain_range_index));
114
115         if (!idmap_autorid_validate_sid(range->domsid)) {
116                 DEBUG(3, ("Invalid SID: %s\n", range->domsid));
117                 return NT_STATUS_INVALID_PARAMETER;
118         }
119
120         idmap_autorid_build_keystr(range->domsid, range->domain_range_index,
121                                    keystr);
122
123         ret = dbwrap_fetch_uint32_bystring(db, keystr, &stored_rangenum);
124
125         if (NT_STATUS_IS_OK(ret)) {
126                 /* entry is already present*/
127                 if (acquire) {
128                         DEBUG(10, ("domain range already allocated - "
129                                    "Not adding!\n"));
130                         return NT_STATUS_OK;
131                 }
132
133                 if (stored_rangenum != requested_rangenum) {
134                         DEBUG(1, ("Error: requested rangenumber (%u) differs "
135                                   "from stored one (%u).\n",
136                                   requested_rangenum, stored_rangenum));
137                         return NT_STATUS_UNSUCCESSFUL;
138                 }
139
140                 DEBUG(10, ("Note: stored range agrees with requested "
141                            "one - ok\n"));
142                 return NT_STATUS_OK;
143         }
144
145         /* fetch the current HWM */
146         ret = dbwrap_fetch_uint32_bystring(db, HWM, &hwm);
147         if (!NT_STATUS_IS_OK(ret)) {
148                 DEBUG(1, ("Fatal error while fetching current "
149                           "HWM value: %s\n", nt_errstr(ret)));
150                 return NT_STATUS_INTERNAL_ERROR;
151         }
152
153         mem_ctx = talloc_stackframe();
154
155         ret = idmap_autorid_loadconfig(db, mem_ctx, &globalcfg);
156         if (!NT_STATUS_IS_OK(ret)) {
157                 DEBUG(1, ("Fatal error while fetching configuration: %s\n",
158                           nt_errstr(ret)));
159                 goto error;
160         }
161
162         if (acquire) {
163                 /*
164                  * automatically acquire the next range
165                  */
166                 requested_rangenum = hwm;
167         }
168
169         if (requested_rangenum >= globalcfg->maxranges) {
170                 DEBUG(1, ("Not enough ranges available: New range %u must be "
171                           "smaller than configured maximum number of ranges "
172                           "(%u).\n",
173                           requested_rangenum, globalcfg->maxranges));
174                 ret = NT_STATUS_NO_MEMORY;
175                 goto error;
176         }
177
178         /*
179          * Check that it is not yet taken.
180          * If the range is requested and < HWM, we need
181          * to check anyways, and otherwise, we also better
182          * check in order to prevent further corruption
183          * in case the db has been externally modified.
184          */
185
186         numstr = talloc_asprintf(mem_ctx, "%u", requested_rangenum);
187         if (!numstr) {
188                 DEBUG(1, ("Talloc failed!\n"));
189                 ret = NT_STATUS_NO_MEMORY;
190                 goto error;
191         }
192
193         if (dbwrap_exists(db, string_term_tdb_data(numstr))) {
194                 DEBUG(1, ("Requested range '%s' is already in use.\n", numstr));
195
196                 if (requested_rangenum < hwm) {
197                         ret = NT_STATUS_INVALID_PARAMETER;
198                 } else {
199                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
200                 }
201
202                 goto error;
203         }
204
205         if (requested_rangenum >= hwm) {
206                 /*
207                  * requested or automatic range >= HWM:
208                  * increment the HWM.
209                  */
210
211                 /* HWM always contains current max range + 1 */
212                 increment = requested_rangenum + 1 - hwm;
213
214                 /* increase the HWM */
215                 ret = dbwrap_change_uint32_atomic_bystring(db, HWM, &hwm,
216                                                            increment);
217                 if (!NT_STATUS_IS_OK(ret)) {
218                         DEBUG(1, ("Fatal error while incrementing the HWM "
219                                   "value in the database: %s\n",
220                                   nt_errstr(ret)));
221                         goto error;
222                 }
223         }
224
225         /*
226          * store away the new mapping in both directions
227          */
228
229         ret = dbwrap_store_uint32_bystring(db, keystr, requested_rangenum);
230         if (!NT_STATUS_IS_OK(ret)) {
231                 DEBUG(1, ("Fatal error while storing new "
232                           "domain->range assignment: %s\n", nt_errstr(ret)));
233                 goto error;
234         }
235
236         numstr = talloc_asprintf(mem_ctx, "%u", requested_rangenum);
237         if (!numstr) {
238                 ret = NT_STATUS_NO_MEMORY;
239                 goto error;
240         }
241
242         ret = dbwrap_store_bystring(db, numstr,
243                         string_term_tdb_data(keystr), TDB_INSERT);
244
245         if (!NT_STATUS_IS_OK(ret)) {
246                 DEBUG(1, ("Fatal error while storing new "
247                           "domain->range assignment: %s\n", nt_errstr(ret)));
248                 goto error;
249         }
250
251         DEBUG(5, ("%s new range #%d for domain %s "
252                   "(domain_range_index=%"PRIu32")\n",
253                   (acquire?"Acquired":"Stored"),
254                   requested_rangenum, keystr,
255                   range->domain_range_index));
256
257         range->rangenum = requested_rangenum;
258
259         range->low_id = globalcfg->minvalue
260                       + range->rangenum * globalcfg->rangesize;
261
262         ret = NT_STATUS_OK;
263
264 error:
265         talloc_free(mem_ctx);
266         return ret;
267 }
268
269 static NTSTATUS idmap_autorid_addrange(struct db_context *db,
270                                        struct autorid_range_config *range,
271                                        bool acquire)
272 {
273         NTSTATUS status;
274         struct idmap_autorid_addrange_ctx ctx;
275
276         ctx.acquire = acquire;
277         ctx.range = range;
278
279         status = dbwrap_trans_do(db, idmap_autorid_addrange_action, &ctx);
280         return status;
281 }
282
283 NTSTATUS idmap_autorid_setrange(struct db_context *db,
284                                 const char *domsid,
285                                 uint32_t domain_range_index,
286                                 uint32_t rangenum)
287 {
288         NTSTATUS status;
289         struct autorid_range_config range;
290
291         ZERO_STRUCT(range);
292         fstrcpy(range.domsid, domsid);
293         range.domain_range_index = domain_range_index;
294         range.rangenum = rangenum;
295
296         status = idmap_autorid_addrange(db, &range, false);
297         return status;
298 }
299
300 static NTSTATUS idmap_autorid_acquire_range(struct db_context *db,
301                                             struct autorid_range_config *range)
302 {
303         return idmap_autorid_addrange(db, range, true);
304 }
305
306 static NTSTATUS idmap_autorid_getrange_int(struct db_context *db,
307                                            struct autorid_range_config *range)
308 {
309         NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
310         struct autorid_global_config *globalcfg = NULL;
311         fstring keystr;
312
313         if (db == NULL || range == NULL) {
314                 DEBUG(3, ("Invalid arguments received\n"));
315                 goto done;
316         }
317
318         if (!idmap_autorid_validate_sid(range->domsid)) {
319                 DEBUG(3, ("Invalid SID: '%s'\n", range->domsid));
320                 status = NT_STATUS_INVALID_PARAMETER;
321                 goto done;
322         }
323
324         idmap_autorid_build_keystr(range->domsid, range->domain_range_index,
325                                    keystr);
326
327         DEBUG(10, ("reading domain range for key %s\n", keystr));
328         status = dbwrap_fetch_uint32_bystring(db, keystr, &(range->rangenum));
329         if (!NT_STATUS_IS_OK(status)) {
330                 DEBUG(1, ("Failed to read database for key '%s': %s\n",
331                           keystr, nt_errstr(status)));
332                 goto done;
333         }
334
335         status = idmap_autorid_loadconfig(db, talloc_tos(), &globalcfg);
336         if (!NT_STATUS_IS_OK(status)) {
337                 DEBUG(1, ("Failed to read global configuration"));
338                 goto done;
339         }
340         range->low_id = globalcfg->minvalue
341                       + range->rangenum * globalcfg->rangesize;
342
343         TALLOC_FREE(globalcfg);
344 done:
345         return status;
346 }
347
348 NTSTATUS idmap_autorid_getrange(struct db_context *db,
349                                 const char *domsid,
350                                 uint32_t domain_range_index,
351                                 uint32_t *rangenum,
352                                 uint32_t *low_id)
353 {
354         NTSTATUS status;
355         struct autorid_range_config range;
356
357         if (rangenum == NULL) {
358                 return NT_STATUS_INVALID_PARAMETER;
359         }
360
361         ZERO_STRUCT(range);
362         fstrcpy(range.domsid, domsid);
363         range.domain_range_index = domain_range_index;
364
365         status = idmap_autorid_getrange_int(db, &range);
366         if (!NT_STATUS_IS_OK(status)) {
367                 return status;
368         }
369
370         *rangenum = range.rangenum;
371
372         if (low_id != NULL) {
373                 *low_id = range.low_id;
374         }
375
376         return NT_STATUS_OK;
377 }
378
379 NTSTATUS idmap_autorid_get_domainrange(struct db_context *db,
380                                        struct autorid_range_config *range,
381                                        bool read_only)
382 {
383         NTSTATUS ret;
384
385         ret = idmap_autorid_getrange_int(db, range);
386         if (!NT_STATUS_IS_OK(ret)) {
387                 if (read_only) {
388                         return NT_STATUS_NOT_FOUND;
389                 }
390
391                 ret = idmap_autorid_acquire_range(db, range);
392         }
393
394         DEBUG(10, ("Using range #%d for domain %s "
395                    "(domain_range_index=%"PRIu32", low_id=%"PRIu32")\n",
396                    range->rangenum, range->domsid, range->domain_range_index,
397                    range->low_id));
398
399         return ret;
400 }
401
402 /* initialize the given HWM to 0 if it does not exist yet */
403 static NTSTATUS idmap_autorid_init_hwm_action(struct db_context *db,
404                                               void *private_data)
405 {
406         NTSTATUS status;
407         uint32_t hwmval;
408         const char *hwm;
409
410         hwm = (char *)private_data;
411
412         status = dbwrap_fetch_uint32_bystring(db, hwm, &hwmval);
413         if (NT_STATUS_IS_OK(status)) {
414                 DEBUG(1, ("HWM (%s) already initialized in autorid database "
415                           "(value %"PRIu32").\n", hwm, hwmval));
416                 return NT_STATUS_OK;
417         }
418         if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
419                 DEBUG(0, ("Error fetching HWM (%s) from autorid "
420                           "database: %s\n", hwm, nt_errstr(status)));
421                 return status;
422         }
423
424         status = dbwrap_trans_store_uint32_bystring(db, hwm, 0);
425         if (!NT_STATUS_IS_OK(status)) {
426                 DEBUG(0, ("Error storing HWM (%s) in autorid database: %s\n",
427                           hwm, nt_errstr(status)));
428                 return status;
429         }
430
431         return NT_STATUS_OK;
432 }
433
434 NTSTATUS idmap_autorid_init_hwm(struct db_context *db, const char *hwm)
435 {
436         NTSTATUS status;
437         uint32_t hwmval;
438
439         status = dbwrap_fetch_uint32_bystring(db, hwm, &hwmval);
440         if (NT_STATUS_IS_OK(status)) {
441                 DEBUG(1, ("HWM (%s) already initialized in autorid database "
442                           "(value %"PRIu32").\n", hwm, hwmval));
443                 return NT_STATUS_OK;
444         }
445         if (!NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
446                 DEBUG(0, ("unable to fetch HWM (%s) from autorid "
447                           "database: %s\n", hwm,  nt_errstr(status)));
448                 return status;
449         }
450
451         status = dbwrap_trans_do(db, idmap_autorid_init_hwm_action,
452                                  (void *)hwm);
453         if (!NT_STATUS_IS_OK(status)) {
454                 DEBUG(0, ("Error initializing HWM (%s) in autorid database: "
455                           "%s\n", hwm, nt_errstr(status)));
456                 return NT_STATUS_INTERNAL_DB_ERROR;
457         }
458
459         DEBUG(1, ("Initialized HWM (%s) in autorid database.\n", hwm));
460
461         return NT_STATUS_OK;
462 }
463
464 /*
465  * Delete a domain#index <-> range mapping from the database.
466  * The mapping is specified by the sid and index.
467  * If force == true, invalid mapping records are deleted as far
468  * as possible, otherwise they are left untouched.
469  */
470
471 struct idmap_autorid_delete_range_by_sid_ctx {
472         const char *domsid;
473         uint32_t domain_range_index;
474         bool force;
475 };
476
477 static NTSTATUS idmap_autorid_delete_range_by_sid_action(struct db_context *db,
478                                                          void *private_data)
479 {
480         struct idmap_autorid_delete_range_by_sid_ctx *ctx =
481                 (struct idmap_autorid_delete_range_by_sid_ctx *)private_data;
482         const char *domsid;
483         uint32_t domain_range_index;
484         uint32_t rangenum;
485         char *keystr;
486         char *range_keystr;
487         TDB_DATA data;
488         NTSTATUS status;
489         TALLOC_CTX *frame = talloc_stackframe();
490         bool is_valid_range_mapping = true;
491         bool force;
492
493         domsid = ctx->domsid;
494         domain_range_index = ctx->domain_range_index;
495         force = ctx->force;
496
497         keystr = idmap_autorid_build_keystr_talloc(frame, domsid,
498                                                    domain_range_index);
499         if (keystr == NULL) {
500                 status = NT_STATUS_NO_MEMORY;
501                 goto done;
502         }
503
504         status = dbwrap_fetch_uint32_bystring(db, keystr, &rangenum);
505         if (!NT_STATUS_IS_OK(status)) {
506                 goto done;
507         }
508
509         range_keystr = talloc_asprintf(frame, "%"PRIu32, rangenum);
510         if (range_keystr == NULL) {
511                 status = NT_STATUS_NO_MEMORY;
512                 goto done;
513         }
514
515         status = dbwrap_fetch_bystring(db, frame, range_keystr, &data);
516         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
517                 DEBUG(1, ("Incomplete mapping %s -> %s: no backward mapping\n",
518                           keystr, range_keystr));
519                 is_valid_range_mapping = false;
520         } else if (!NT_STATUS_IS_OK(status)) {
521                 DEBUG(1, ("Error fetching reverse mapping for %s -> %s:  %s\n",
522                           keystr, range_keystr, nt_errstr(status)));
523                 goto done;
524         } else if (strncmp((const char *)data.dptr, keystr, strlen(keystr))
525                    != 0)
526         {
527                 DEBUG(1, ("Invalid mapping: %s -> %s -> %s\n",
528                           keystr, range_keystr, (const char *)data.dptr));
529                 is_valid_range_mapping = false;
530         }
531
532         if (!is_valid_range_mapping && !force) {
533                 DEBUG(10, ("Not deleting invalid mapping, since not in force "
534                            "mode.\n"));
535                 status = NT_STATUS_FILE_INVALID;
536                 goto done;
537         }
538
539         status = dbwrap_delete_bystring(db, keystr);
540         if (!NT_STATUS_IS_OK(status)) {
541                 DEBUG(1, ("Deletion of '%s' failed: %s\n",
542                           keystr, nt_errstr(status)));
543                 goto done;
544         }
545
546         if (!is_valid_range_mapping) {
547                 goto done;
548         }
549
550         status = dbwrap_delete_bystring(db, range_keystr);
551         if (!NT_STATUS_IS_OK(status)) {
552                 DEBUG(1, ("Deletion of '%s' failed: %s\n",
553                           range_keystr, nt_errstr(status)));
554                 goto done;
555         }
556
557         DEBUG(10, ("Deleted range mapping %s <--> %s\n", keystr,
558                    range_keystr));
559
560 done:
561         TALLOC_FREE(frame);
562         return status;
563 }
564
565 NTSTATUS idmap_autorid_delete_range_by_sid(struct db_context *db,
566                                            const char *domsid,
567                                            uint32_t domain_range_index,
568                                            bool force)
569 {
570         NTSTATUS status;
571         struct idmap_autorid_delete_range_by_sid_ctx ctx;
572
573         ctx.domain_range_index = domain_range_index;
574         ctx.domsid = domsid;
575         ctx.force = force;
576
577         status = dbwrap_trans_do(db, idmap_autorid_delete_range_by_sid_action,
578                                  &ctx);
579         return status;
580 }
581
582 /*
583  * Delete a domain#index <-> range mapping from the database.
584  * The mapping is specified by the range number.
585  * If force == true, invalid mapping records are deleted as far
586  * as possible, otherwise they are left untouched.
587  */
588 struct idmap_autorid_delete_range_by_num_ctx {
589         uint32_t rangenum;
590         bool force;
591 };
592
593 static NTSTATUS idmap_autorid_delete_range_by_num_action(struct db_context *db,
594                                                            void *private_data)
595 {
596         struct idmap_autorid_delete_range_by_num_ctx *ctx =
597                 (struct idmap_autorid_delete_range_by_num_ctx *)private_data;
598         uint32_t rangenum;
599         char *keystr;
600         char *range_keystr;
601         TDB_DATA val;
602         NTSTATUS status;
603         TALLOC_CTX *frame = talloc_stackframe();
604         bool is_valid_range_mapping = true;
605         bool force;
606
607         rangenum = ctx->rangenum;
608         force = ctx->force;
609
610         range_keystr = talloc_asprintf(frame, "%"PRIu32, rangenum);
611         if (range_keystr == NULL) {
612                 status = NT_STATUS_NO_MEMORY;
613                 goto done;
614         }
615
616         ZERO_STRUCT(val);
617
618         status = dbwrap_fetch_bystring(db, frame, range_keystr, &val);
619         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
620                 DEBUG(10, ("Did not find range '%s' in database.\n",
621                            range_keystr));
622                 goto done;
623         } else if (!NT_STATUS_IS_OK(status)) {
624                 DEBUG(5, ("Error fetching rang key: %s\n", nt_errstr(status)));
625                 goto done;
626         }
627
628         if (val.dptr == NULL) {
629                 DEBUG(1, ("Invalid mapping: %s -> empty value\n",
630                           range_keystr));
631                 is_valid_range_mapping = false;
632         } else {
633                 uint32_t reverse_rangenum = 0;
634
635                 keystr = (char *)val.dptr;
636
637                 status = dbwrap_fetch_uint32_bystring(db, keystr,
638                                                       &reverse_rangenum);
639                 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
640                         DEBUG(1, ("Incomplete mapping %s -> %s: "
641                                   "no backward mapping\n",
642                                   range_keystr, keystr));
643                         is_valid_range_mapping = false;
644                 } else if (!NT_STATUS_IS_OK(status)) {
645                         DEBUG(1, ("Error fetching reverse mapping for "
646                                   "%s -> %s: %s\n",
647                                   range_keystr, keystr, nt_errstr(status)));
648                         goto done;
649                 } else if (rangenum != reverse_rangenum) {
650                         is_valid_range_mapping = false;
651                 }
652         }
653
654         if (!is_valid_range_mapping && !force) {
655                 DEBUG(10, ("Not deleting invalid mapping, since not in force "
656                            "mode.\n"));
657                 status = NT_STATUS_FILE_INVALID;
658                 goto done;
659         }
660
661         status = dbwrap_delete_bystring(db, range_keystr);
662         if (!NT_STATUS_IS_OK(status)) {
663                 DEBUG(1, ("Deletion of '%s' failed: %s\n",
664                           range_keystr, nt_errstr(status)));
665                 goto done;
666         }
667
668         if (!is_valid_range_mapping) {
669                 goto done;
670         }
671
672         status = dbwrap_delete_bystring(db, keystr);
673         if (!NT_STATUS_IS_OK(status)) {
674                 DEBUG(1, ("Deletion of '%s' failed: %s\n",
675                           keystr, nt_errstr(status)));
676                 goto done;
677         }
678
679         DEBUG(10, ("Deleted range mapping %s <--> %s\n", range_keystr,
680                    keystr));
681
682 done:
683         talloc_free(frame);
684         return status;
685 }
686
687 NTSTATUS idmap_autorid_delete_range_by_num(struct db_context *db,
688                                            uint32_t rangenum,
689                                            bool force)
690 {
691         NTSTATUS status;
692         struct idmap_autorid_delete_range_by_num_ctx ctx;
693
694         ctx.rangenum = rangenum;
695         ctx.force = force;
696
697         status = dbwrap_trans_do(db, idmap_autorid_delete_range_by_num_action,
698                                  &ctx);
699         return status;
700 }
701
702 /**
703  * Open and possibly create the database.
704  */
705 NTSTATUS idmap_autorid_db_open(const char *path,
706                                TALLOC_CTX *mem_ctx,
707                                struct db_context **db)
708 {
709         NTSTATUS status;
710
711         if (*db != NULL) {
712                 /* its already open */
713                 return NT_STATUS_OK;
714         }
715
716         /* Open idmap repository */
717         *db = db_open(mem_ctx, path, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0644,
718                       DBWRAP_LOCK_ORDER_1, DBWRAP_FLAG_NONE);
719
720         if (*db == NULL) {
721                 DEBUG(0, ("Unable to open idmap_autorid database '%s'\n", path));
722                 return NT_STATUS_UNSUCCESSFUL;
723         }
724
725         return status;
726 }
727
728 /**
729  * Initialize the high watermark records in the database.
730  */
731 NTSTATUS idmap_autorid_init_hwms(struct db_context *db)
732 {
733         NTSTATUS status;
734
735         status = idmap_autorid_init_hwm(db, HWM);
736         if (!NT_STATUS_IS_OK(status)) {
737                 return status;
738         }
739
740         status = idmap_autorid_init_hwm(db, ALLOC_HWM_UID);
741         if (!NT_STATUS_IS_OK(status)) {
742                 return status;
743         }
744
745         status = idmap_autorid_init_hwm(db, ALLOC_HWM_GID);
746
747         return status;
748 }
749
750 NTSTATUS idmap_autorid_db_init(const char *path,
751                                TALLOC_CTX *mem_ctx,
752                                struct db_context **db)
753 {
754         NTSTATUS status;
755
756         status = idmap_autorid_db_open(path, mem_ctx, db);
757         if (!NT_STATUS_IS_OK(status)) {
758                 return status;
759         }
760
761         status = idmap_autorid_init_hwms(*db);
762         return status;
763 }
764
765
766
767 struct idmap_autorid_fetch_config_state {
768         TALLOC_CTX *mem_ctx;
769         char *configstr;
770 };
771
772 static void idmap_autorid_config_parser(TDB_DATA key, TDB_DATA value,
773                                         void *private_data)
774 {
775         struct idmap_autorid_fetch_config_state *state;
776
777         state = (struct idmap_autorid_fetch_config_state *)private_data;
778
779         /*
780          * strndup because we have non-nullterminated strings in the db
781          */
782         state->configstr = talloc_strndup(
783                 state->mem_ctx, (const char *)value.dptr, value.dsize);
784 }
785
786 NTSTATUS idmap_autorid_getconfigstr(struct db_context *db, TALLOC_CTX *mem_ctx,
787                                     char **result)
788 {
789         TDB_DATA key;
790         NTSTATUS status;
791         struct idmap_autorid_fetch_config_state state;
792
793         if (result == NULL) {
794                 return NT_STATUS_INVALID_PARAMETER;
795         }
796
797         key = string_term_tdb_data(CONFIGKEY);
798
799         state.mem_ctx = mem_ctx;
800         state.configstr = NULL;
801
802         status = dbwrap_parse_record(db, key, idmap_autorid_config_parser,
803                                      &state);
804         if (!NT_STATUS_IS_OK(status)) {
805                 DEBUG(1, ("Error while retrieving config: %s\n",
806                           nt_errstr(status)));
807                 return status;
808         }
809
810         if (state.configstr == NULL) {
811                 DEBUG(1, ("Error while retrieving config\n"));
812                 return NT_STATUS_NO_MEMORY;
813         }
814
815         DEBUG(5, ("found CONFIG: %s\n", state.configstr));
816
817         *result = state.configstr;
818         return NT_STATUS_OK;
819 }
820
821 bool idmap_autorid_parse_configstr(const char *configstr,
822                                    struct autorid_global_config *cfg)
823 {
824         unsigned long minvalue, rangesize, maxranges;
825
826         if (sscanf(configstr,
827                    "minvalue:%lu rangesize:%lu maxranges:%lu",
828                    &minvalue, &rangesize, &maxranges) != 3) {
829                 DEBUG(1,
830                       ("Found invalid configuration data. "
831                        "Creating new config\n"));
832                 return false;
833         }
834
835         cfg->minvalue = minvalue;
836         cfg->rangesize = rangesize;
837         cfg->maxranges = maxranges;
838
839         return true;
840 }
841
842 NTSTATUS idmap_autorid_loadconfig(struct db_context *db,
843                                   TALLOC_CTX *mem_ctx,
844                                   struct autorid_global_config **result)
845 {
846         struct autorid_global_config *cfg;
847         NTSTATUS status;
848         bool ok;
849         char *configstr = NULL;
850
851         if (result == NULL) {
852                 return NT_STATUS_INVALID_PARAMETER;
853         }
854
855         status = idmap_autorid_getconfigstr(db, mem_ctx, &configstr);
856         if (!NT_STATUS_IS_OK(status)) {
857                 return status;
858         }
859
860         cfg = talloc_zero(mem_ctx, struct autorid_global_config);
861         if (cfg == NULL) {
862                 return NT_STATUS_NO_MEMORY;
863         }
864
865         ok = idmap_autorid_parse_configstr(configstr, cfg);
866         if (!ok) {
867                 talloc_free(cfg);
868                 return NT_STATUS_INVALID_PARAMETER;
869         }
870
871         DEBUG(10, ("Loaded previously stored configuration "
872                    "minvalue:%d rangesize:%d\n",
873                    cfg->minvalue, cfg->rangesize));
874
875         *result = cfg;
876
877         return NT_STATUS_OK;
878 }
879
880 NTSTATUS idmap_autorid_saveconfig(struct db_context *db,
881                                   struct autorid_global_config *cfg)
882 {
883
884         struct autorid_global_config *storedconfig = NULL;
885         NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
886         TDB_DATA data;
887         char *cfgstr;
888         uint32_t hwm;
889         TALLOC_CTX *frame = talloc_stackframe();
890
891         DEBUG(10, ("New configuration provided for storing is "
892                    "minvalue:%d rangesize:%d maxranges:%d\n",
893                    cfg->minvalue, cfg->rangesize, cfg->maxranges));
894
895         if (cfg->rangesize < 2000) {
896                 DEBUG(1, ("autorid rangesize must be at least 2000\n"));
897                 goto done;
898         }
899
900         if (cfg->maxranges == 0) {
901                 DEBUG(1, ("An autorid maxranges value of 0 is invalid. "
902                           "Must have at least one range available.\n"));
903                 goto done;
904         }
905
906         status = idmap_autorid_loadconfig(db, frame, &storedconfig);
907         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
908                 DEBUG(5, ("No configuration found. Storing initial "
909                           "configuration.\n"));
910         } else if (!NT_STATUS_IS_OK(status)) {
911                 DEBUG(1, ("Error loading configuration: %s\n",
912                           nt_errstr(status)));
913                 goto done;
914         }
915
916         /* did the minimum value or rangesize change? */
917         if (storedconfig &&
918             ((storedconfig->minvalue != cfg->minvalue) ||
919              (storedconfig->rangesize != cfg->rangesize)))
920         {
921                 DEBUG(1, ("New configuration values for rangesize or "
922                           "minimum uid value conflict with previously "
923                           "used values! Not storing new config.\n"));
924                 status = NT_STATUS_INVALID_PARAMETER;
925                 goto done;
926         }
927
928         status = dbwrap_fetch_uint32_bystring(db, HWM, &hwm);
929         if (!NT_STATUS_IS_OK(status)) {
930                 DEBUG(1, ("Fatal error while fetching current "
931                           "HWM value: %s\n", nt_errstr(status)));
932                 status = NT_STATUS_INTERNAL_ERROR;
933                 goto done;
934         }
935
936         /*
937          * has the highest uid value been reduced to setting that is not
938          * sufficient any more for already existing ranges?
939          */
940         if (hwm > cfg->maxranges) {
941                 DEBUG(1, ("New upper uid limit is too low to cover "
942                           "existing mappings! Not storing new config.\n"));
943                 status = NT_STATUS_INVALID_PARAMETER;
944                 goto done;
945         }
946
947         cfgstr =
948             talloc_asprintf(frame,
949                             "minvalue:%u rangesize:%u maxranges:%u",
950                             cfg->minvalue, cfg->rangesize, cfg->maxranges);
951
952         if (cfgstr == NULL) {
953                 status = NT_STATUS_NO_MEMORY;
954                 goto done;
955         }
956
957         data = string_tdb_data(cfgstr);
958
959         status = dbwrap_trans_store_bystring(db, CONFIGKEY, data, TDB_REPLACE);
960
961 done:
962         TALLOC_FREE(frame);
963         return status;
964 }
965
966 NTSTATUS idmap_autorid_saveconfigstr(struct db_context *db,
967                                      const char *configstr)
968 {
969         bool ok;
970         NTSTATUS status;
971         struct autorid_global_config cfg;
972
973         ok = idmap_autorid_parse_configstr(configstr, &cfg);
974         if (!ok) {
975                 return NT_STATUS_INVALID_PARAMETER;
976         }
977
978         status = idmap_autorid_saveconfig(db, &cfg);
979         return status;
980 }
981
982
983 /*
984  * iteration: Work on all range mappings for a given domain
985  */
986
987 struct domain_range_visitor_ctx {
988         const char *domsid;
989         NTSTATUS (*fn)(struct db_context *db,
990                        const char *domsid,
991                        uint32_t index,
992                        uint32_t rangenum,
993                        void *private_data);
994         void *private_data;
995         int count; /* number of records worked on */
996 };
997
998 static int idmap_autorid_visit_domain_range(struct db_record *rec,
999                                             void *private_data)
1000 {
1001         struct domain_range_visitor_ctx *vi;
1002         char *domsid;
1003         char *sep;
1004         uint32_t range_index = 0;
1005         uint32_t rangenum = 0;
1006         TDB_DATA key, value;
1007         NTSTATUS status;
1008         int ret = 0;
1009         struct db_context *db;
1010
1011         vi = talloc_get_type_abort(private_data,
1012                                    struct domain_range_visitor_ctx);
1013
1014         key = dbwrap_record_get_key(rec);
1015
1016         /*
1017          * split string "<sid>[#<index>]" into sid string and index number
1018          */
1019
1020         domsid = (char *)key.dptr;
1021
1022         DEBUG(10, ("idmap_autorid_visit_domain_range: visiting key '%s'\n",
1023                    domsid));
1024
1025         sep = strrchr(domsid, '#');
1026         if (sep != NULL) {
1027                 char *index_str;
1028                 *sep = '\0';
1029                 index_str = sep+1;
1030                 if (sscanf(index_str, "%"SCNu32, &range_index) != 1) {
1031                         DEBUG(10, ("Found separator '#' but '%s' is not a "
1032                                    "valid range index. Skipping record\n",
1033                                    index_str));
1034                         goto done;
1035                 }
1036         }
1037
1038         if (!idmap_autorid_validate_sid(domsid)) {
1039                 DEBUG(10, ("String '%s' is not a valid sid. "
1040                            "Skipping record.\n", domsid));
1041                 goto done;
1042         }
1043
1044         if ((vi->domsid != NULL) && (strcmp(domsid, vi->domsid) != 0)) {
1045                 DEBUG(10, ("key sid '%s' does not match requested sid '%s'.\n",
1046                            domsid, vi->domsid));
1047                 goto done;
1048         }
1049
1050         value = dbwrap_record_get_value(rec);
1051
1052         if (value.dsize != sizeof(uint32_t)) {
1053                 /* it might be a mapping of a well known sid */
1054                 DEBUG(10, ("value size %u != sizeof(uint32_t) for sid '%s', "
1055                            "skipping.\n", (unsigned)value.dsize, vi->domsid));
1056                 goto done;
1057         }
1058
1059         rangenum = IVAL(value.dptr, 0);
1060
1061         db = dbwrap_record_get_db(rec);
1062
1063         status = vi->fn(db, domsid, range_index, rangenum, vi->private_data);
1064         if (!NT_STATUS_IS_OK(status)) {
1065                 ret = -1;
1066                 goto done;
1067         }
1068
1069         vi->count++;
1070         ret = 0;
1071
1072 done:
1073         return ret;
1074 }
1075
1076 static NTSTATUS idmap_autorid_iterate_domain_ranges_int(struct db_context *db,
1077                                 const char *domsid,
1078                                 NTSTATUS (*fn)(struct db_context *db,
1079                                                const char *domsid,
1080                                                uint32_t index,
1081                                                uint32_t rangnum,
1082                                                void *private_data),
1083                                 void *private_data,
1084                                 int *count,
1085                                 NTSTATUS (*traverse)(struct db_context *db,
1086                                           int (*f)(struct db_record *, void *),
1087                                           void *private_data,
1088                                           int *count))
1089 {
1090         NTSTATUS status;
1091         struct domain_range_visitor_ctx *vi;
1092         TALLOC_CTX *frame = talloc_stackframe();
1093
1094         if (domsid == NULL) {
1095                 DEBUG(10, ("No sid provided, operating on all ranges\n"));
1096         }
1097
1098         if (fn == NULL) {
1099                 DEBUG(1, ("Error: missing visitor callback\n"));
1100                 status = NT_STATUS_INVALID_PARAMETER;
1101                 goto done;
1102         }
1103
1104         vi = talloc_zero(frame, struct domain_range_visitor_ctx);
1105         if (vi == NULL) {
1106                 status = NT_STATUS_NO_MEMORY;
1107                 goto done;
1108         }
1109
1110         vi->domsid = domsid;
1111         vi->fn = fn;
1112         vi->private_data = private_data;
1113
1114         status = traverse(db, idmap_autorid_visit_domain_range, vi, NULL);
1115         if (!NT_STATUS_IS_OK(status)) {
1116                 goto done;
1117         }
1118
1119         if (count != NULL) {
1120                 *count = vi->count;
1121         }
1122
1123 done:
1124         talloc_free(frame);
1125         return status;
1126 }
1127
1128 NTSTATUS idmap_autorid_iterate_domain_ranges(struct db_context *db,
1129                                         const char *domsid,
1130                                         NTSTATUS (*fn)(struct db_context *db,
1131                                                        const char *domsid,
1132                                                        uint32_t index,
1133                                                        uint32_t rangenum,
1134                                                        void *private_data),
1135                                         void *private_data,
1136                                         int *count)
1137 {
1138         NTSTATUS status;
1139
1140         status = idmap_autorid_iterate_domain_ranges_int(db,
1141                                                          domsid,
1142                                                          fn,
1143                                                          private_data,
1144                                                          count,
1145                                                          dbwrap_traverse);
1146
1147         return status;
1148 }
1149
1150
1151 NTSTATUS idmap_autorid_iterate_domain_ranges_read(struct db_context *db,
1152                                         const char *domsid,
1153                                         NTSTATUS (*fn)(struct db_context *db,
1154                                                        const char *domsid,
1155                                                        uint32_t index,
1156                                                        uint32_t rangenum,
1157                                                        void *count),
1158                                         void *private_data,
1159                                         int *count)
1160 {
1161         NTSTATUS status;
1162
1163         status = idmap_autorid_iterate_domain_ranges_int(db,
1164                                                          domsid,
1165                                                          fn,
1166                                                          private_data,
1167                                                          count,
1168                                                          dbwrap_traverse_read);
1169
1170         return status;
1171 }
1172
1173
1174 /*
1175  * Delete all ranges configured for a given domain
1176  */
1177
1178 struct delete_domain_ranges_visitor_ctx {
1179         bool force;
1180 };
1181
1182 static NTSTATUS idmap_autorid_delete_domain_ranges_visitor(
1183                                                 struct db_context *db,
1184                                                 const char *domsid,
1185                                                 uint32_t domain_range_index,
1186                                                 uint32_t rangenum,
1187                                                 void *private_data)
1188 {
1189         struct delete_domain_ranges_visitor_ctx *ctx;
1190         NTSTATUS status;
1191
1192         ctx = (struct delete_domain_ranges_visitor_ctx *)private_data;
1193
1194         status = idmap_autorid_delete_range_by_sid(
1195                                 db, domsid, domain_range_index, ctx->force);
1196         return status;
1197 }
1198
1199 struct idmap_autorid_delete_domain_ranges_ctx {
1200         const char *domsid;
1201         bool force;
1202         int count; /* output: count records operated on */
1203 };
1204
1205 static NTSTATUS idmap_autorid_delete_domain_ranges_action(struct db_context *db,
1206                                                           void *private_data)
1207 {
1208         struct idmap_autorid_delete_domain_ranges_ctx *ctx;
1209         struct delete_domain_ranges_visitor_ctx visitor_ctx;
1210         int count;
1211         NTSTATUS status;
1212
1213         ctx = (struct idmap_autorid_delete_domain_ranges_ctx *)private_data;
1214
1215         ZERO_STRUCT(visitor_ctx);
1216         visitor_ctx.force = ctx->force;
1217
1218         status = idmap_autorid_iterate_domain_ranges(db,
1219                                 ctx->domsid,
1220                                 idmap_autorid_delete_domain_ranges_visitor,
1221                                 &visitor_ctx,
1222                                 &count);
1223         if (!NT_STATUS_IS_OK(status)) {
1224                 return status;
1225         }
1226
1227         ctx->count = count;
1228
1229         return NT_STATUS_OK;
1230 }
1231
1232 NTSTATUS idmap_autorid_delete_domain_ranges(struct db_context *db,
1233                                             const char *domsid,
1234                                             bool force,
1235                                             int *count)
1236 {
1237         NTSTATUS status;
1238         struct idmap_autorid_delete_domain_ranges_ctx ctx;
1239
1240         ZERO_STRUCT(ctx);
1241         ctx.domsid = domsid;
1242         ctx.force = force;
1243
1244         status = dbwrap_trans_do(db, idmap_autorid_delete_domain_ranges_action,
1245                                  &ctx);
1246         if (!NT_STATUS_IS_OK(status)) {
1247                 return status;
1248         }
1249
1250         *count = ctx.count;
1251
1252         return NT_STATUS_OK;
1253 }