autorid: in idmap_autorid_saveconfig, add a debug msg when loading gives error
[sfrench/samba-autobuild/.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 initialize the database which stores the ranges for the domains
704  */
705 NTSTATUS idmap_autorid_db_init(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         /* Initialize high water mark for the currently used range to 0 */
726
727         status = idmap_autorid_init_hwm(*db, HWM);
728         NT_STATUS_NOT_OK_RETURN(status);
729
730         status = idmap_autorid_init_hwm(*db, ALLOC_HWM_UID);
731         NT_STATUS_NOT_OK_RETURN(status);
732
733         status = idmap_autorid_init_hwm(*db, ALLOC_HWM_GID);
734
735         return status;
736 }
737
738 struct idmap_autorid_fetch_config_state {
739         TALLOC_CTX *mem_ctx;
740         char *configstr;
741 };
742
743 static void idmap_autorid_config_parser(TDB_DATA key, TDB_DATA value,
744                                         void *private_data)
745 {
746         struct idmap_autorid_fetch_config_state *state;
747
748         state = (struct idmap_autorid_fetch_config_state *)private_data;
749
750         /*
751          * strndup because we have non-nullterminated strings in the db
752          */
753         state->configstr = talloc_strndup(
754                 state->mem_ctx, (const char *)value.dptr, value.dsize);
755 }
756
757 NTSTATUS idmap_autorid_getconfigstr(struct db_context *db, TALLOC_CTX *mem_ctx,
758                                     char **result)
759 {
760         TDB_DATA key;
761         NTSTATUS status;
762         struct idmap_autorid_fetch_config_state state;
763
764         if (result == NULL) {
765                 return NT_STATUS_INVALID_PARAMETER;
766         }
767
768         key = string_term_tdb_data(CONFIGKEY);
769
770         state.mem_ctx = mem_ctx;
771         state.configstr = NULL;
772
773         status = dbwrap_parse_record(db, key, idmap_autorid_config_parser,
774                                      &state);
775         if (!NT_STATUS_IS_OK(status)) {
776                 DEBUG(1, ("Error while retrieving config: %s\n",
777                           nt_errstr(status)));
778                 return status;
779         }
780
781         if (state.configstr == NULL) {
782                 DEBUG(1, ("Error while retrieving config\n"));
783                 return NT_STATUS_NO_MEMORY;
784         }
785
786         DEBUG(5, ("found CONFIG: %s\n", state.configstr));
787
788         *result = state.configstr;
789         return NT_STATUS_OK;
790 }
791
792 bool idmap_autorid_parse_configstr(const char *configstr,
793                                    struct autorid_global_config *cfg)
794 {
795         unsigned long minvalue, rangesize, maxranges;
796
797         if (sscanf(configstr,
798                    "minvalue:%lu rangesize:%lu maxranges:%lu",
799                    &minvalue, &rangesize, &maxranges) != 3) {
800                 DEBUG(1,
801                       ("Found invalid configuration data. "
802                        "Creating new config\n"));
803                 return false;
804         }
805
806         cfg->minvalue = minvalue;
807         cfg->rangesize = rangesize;
808         cfg->maxranges = maxranges;
809
810         return true;
811 }
812
813 NTSTATUS idmap_autorid_loadconfig(struct db_context *db,
814                                   TALLOC_CTX *mem_ctx,
815                                   struct autorid_global_config **result)
816 {
817         struct autorid_global_config *cfg;
818         NTSTATUS status;
819         bool ok;
820         char *configstr = NULL;
821
822         if (result == NULL) {
823                 return NT_STATUS_INVALID_PARAMETER;
824         }
825
826         status = idmap_autorid_getconfigstr(db, mem_ctx, &configstr);
827         if (!NT_STATUS_IS_OK(status)) {
828                 return status;
829         }
830
831         cfg = talloc_zero(mem_ctx, struct autorid_global_config);
832         if (cfg == NULL) {
833                 return NT_STATUS_NO_MEMORY;
834         }
835
836         ok = idmap_autorid_parse_configstr(configstr, cfg);
837         if (!ok) {
838                 talloc_free(cfg);
839                 return NT_STATUS_INVALID_PARAMETER;
840         }
841
842         DEBUG(10, ("Loaded previously stored configuration "
843                    "minvalue:%d rangesize:%d\n",
844                    cfg->minvalue, cfg->rangesize));
845
846         *result = cfg;
847
848         return NT_STATUS_OK;
849 }
850
851 NTSTATUS idmap_autorid_saveconfig(struct db_context *db,
852                                   struct autorid_global_config *cfg)
853 {
854
855         struct autorid_global_config *storedconfig = NULL;
856         NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
857         TDB_DATA data;
858         char *cfgstr;
859         uint32_t hwm;
860         TALLOC_CTX *frame = talloc_stackframe();
861
862         DEBUG(10, ("New configuration provided for storing is "
863                    "minvalue:%d rangesize:%d maxranges:%d\n",
864                    cfg->minvalue, cfg->rangesize, cfg->maxranges));
865
866         if (cfg->rangesize < 2000) {
867                 DEBUG(1, ("autorid rangesize must be at least 2000\n"));
868                 goto done;
869         }
870
871         if (cfg->maxranges == 0) {
872                 DEBUG(1, ("An autorid maxranges value of 0 is invalid. "
873                           "Must have at least one range available.\n"));
874                 goto done;
875         }
876
877         status = idmap_autorid_loadconfig(db, frame, &storedconfig);
878         if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
879                 DEBUG(5, ("No configuration found. Storing initial "
880                           "configuration.\n"));
881         } else if (!NT_STATUS_IS_OK(status)) {
882                 DEBUG(1, ("Error loading configuration: %s\n",
883                           nt_errstr(status)));
884                 goto done;
885         }
886
887         /* did the minimum value or rangesize change? */
888         if (storedconfig &&
889             ((storedconfig->minvalue != cfg->minvalue) ||
890              (storedconfig->rangesize != cfg->rangesize)))
891         {
892                 DEBUG(1, ("New configuration values for rangesize or "
893                           "minimum uid value conflict with previously "
894                           "used values! Not storing new config.\n"));
895                 status = NT_STATUS_INVALID_PARAMETER;
896                 goto done;
897         }
898
899         status = dbwrap_fetch_uint32_bystring(db, HWM, &hwm);
900         if (!NT_STATUS_IS_OK(status)) {
901                 DEBUG(1, ("Fatal error while fetching current "
902                           "HWM value: %s\n", nt_errstr(status)));
903                 status = NT_STATUS_INTERNAL_ERROR;
904                 goto done;
905         }
906
907         /*
908          * has the highest uid value been reduced to setting that is not
909          * sufficient any more for already existing ranges?
910          */
911         if (hwm > cfg->maxranges) {
912                 DEBUG(1, ("New upper uid limit is too low to cover "
913                           "existing mappings! Not storing new config.\n"));
914                 status = NT_STATUS_INVALID_PARAMETER;
915                 goto done;
916         }
917
918         cfgstr =
919             talloc_asprintf(frame,
920                             "minvalue:%u rangesize:%u maxranges:%u",
921                             cfg->minvalue, cfg->rangesize, cfg->maxranges);
922
923         if (cfgstr == NULL) {
924                 status = NT_STATUS_NO_MEMORY;
925                 goto done;
926         }
927
928         data = string_tdb_data(cfgstr);
929
930         status = dbwrap_trans_store_bystring(db, CONFIGKEY, data, TDB_REPLACE);
931
932 done:
933         TALLOC_FREE(frame);
934         return status;
935 }
936
937 NTSTATUS idmap_autorid_saveconfigstr(struct db_context *db,
938                                      const char *configstr)
939 {
940         bool ok;
941         NTSTATUS status;
942         struct autorid_global_config cfg;
943
944         ok = idmap_autorid_parse_configstr(configstr, &cfg);
945         if (!ok) {
946                 return NT_STATUS_INVALID_PARAMETER;
947         }
948
949         status = idmap_autorid_saveconfig(db, &cfg);
950         return status;
951 }
952
953
954 /*
955  * iteration: Work on all range mappings for a given domain
956  */
957
958 struct domain_range_visitor_ctx {
959         const char *domsid;
960         NTSTATUS (*fn)(struct db_context *db,
961                        const char *domsid,
962                        uint32_t index,
963                        uint32_t rangenum,
964                        void *private_data);
965         void *private_data;
966         int count; /* number of records worked on */
967 };
968
969 static int idmap_autorid_visit_domain_range(struct db_record *rec,
970                                             void *private_data)
971 {
972         struct domain_range_visitor_ctx *vi;
973         char *domsid;
974         char *sep;
975         uint32_t range_index = 0;
976         uint32_t rangenum = 0;
977         TDB_DATA key, value;
978         NTSTATUS status;
979         int ret = 0;
980         struct db_context *db;
981
982         vi = talloc_get_type_abort(private_data,
983                                    struct domain_range_visitor_ctx);
984
985         key = dbwrap_record_get_key(rec);
986
987         /*
988          * split string "<sid>[#<index>]" into sid string and index number
989          */
990
991         domsid = (char *)key.dptr;
992
993         DEBUG(10, ("idmap_autorid_visit_domain_range: visiting key '%s'\n",
994                    domsid));
995
996         sep = strrchr(domsid, '#');
997         if (sep != NULL) {
998                 char *index_str;
999                 *sep = '\0';
1000                 index_str = sep+1;
1001                 if (sscanf(index_str, "%"SCNu32, &range_index) != 1) {
1002                         DEBUG(10, ("Found separator '#' but '%s' is not a "
1003                                    "valid range index. Skipping record\n",
1004                                    index_str));
1005                         goto done;
1006                 }
1007         }
1008
1009         if (!idmap_autorid_validate_sid(domsid)) {
1010                 DEBUG(10, ("String '%s' is not a valid sid. "
1011                            "Skipping record.\n", domsid));
1012                 goto done;
1013         }
1014
1015         if ((vi->domsid != NULL) && (strcmp(domsid, vi->domsid) != 0)) {
1016                 DEBUG(10, ("key sid '%s' does not match requested sid '%s'.\n",
1017                            domsid, vi->domsid));
1018                 goto done;
1019         }
1020
1021         value = dbwrap_record_get_value(rec);
1022
1023         if (value.dsize != sizeof(uint32_t)) {
1024                 /* it might be a mapping of a well known sid */
1025                 DEBUG(10, ("value size %u != sizeof(uint32_t) for sid '%s', "
1026                            "skipping.\n", (unsigned)value.dsize, vi->domsid));
1027                 goto done;
1028         }
1029
1030         rangenum = IVAL(value.dptr, 0);
1031
1032         db = dbwrap_record_get_db(rec);
1033
1034         status = vi->fn(db, domsid, range_index, rangenum, vi->private_data);
1035         if (!NT_STATUS_IS_OK(status)) {
1036                 ret = -1;
1037                 goto done;
1038         }
1039
1040         vi->count++;
1041         ret = 0;
1042
1043 done:
1044         return ret;
1045 }
1046
1047 static NTSTATUS idmap_autorid_iterate_domain_ranges_int(struct db_context *db,
1048                                 const char *domsid,
1049                                 NTSTATUS (*fn)(struct db_context *db,
1050                                                const char *domsid,
1051                                                uint32_t index,
1052                                                uint32_t rangnum,
1053                                                void *private_data),
1054                                 void *private_data,
1055                                 int *count,
1056                                 NTSTATUS (*traverse)(struct db_context *db,
1057                                           int (*f)(struct db_record *, void *),
1058                                           void *private_data,
1059                                           int *count))
1060 {
1061         NTSTATUS status;
1062         struct domain_range_visitor_ctx *vi;
1063         TALLOC_CTX *frame = talloc_stackframe();
1064
1065         if (domsid == NULL) {
1066                 DEBUG(10, ("No sid provided, operating on all ranges\n"));
1067         }
1068
1069         if (fn == NULL) {
1070                 DEBUG(1, ("Error: missing visitor callback\n"));
1071                 status = NT_STATUS_INVALID_PARAMETER;
1072                 goto done;
1073         }
1074
1075         vi = talloc_zero(frame, struct domain_range_visitor_ctx);
1076         if (vi == NULL) {
1077                 status = NT_STATUS_NO_MEMORY;
1078                 goto done;
1079         }
1080
1081         vi->domsid = domsid;
1082         vi->fn = fn;
1083         vi->private_data = private_data;
1084
1085         status = traverse(db, idmap_autorid_visit_domain_range, vi, NULL);
1086         if (!NT_STATUS_IS_OK(status)) {
1087                 goto done;
1088         }
1089
1090         if (count != NULL) {
1091                 *count = vi->count;
1092         }
1093
1094 done:
1095         talloc_free(frame);
1096         return status;
1097 }
1098
1099 NTSTATUS idmap_autorid_iterate_domain_ranges(struct db_context *db,
1100                                         const char *domsid,
1101                                         NTSTATUS (*fn)(struct db_context *db,
1102                                                        const char *domsid,
1103                                                        uint32_t index,
1104                                                        uint32_t rangenum,
1105                                                        void *private_data),
1106                                         void *private_data,
1107                                         int *count)
1108 {
1109         NTSTATUS status;
1110
1111         status = idmap_autorid_iterate_domain_ranges_int(db,
1112                                                          domsid,
1113                                                          fn,
1114                                                          private_data,
1115                                                          count,
1116                                                          dbwrap_traverse);
1117
1118         return status;
1119 }
1120
1121
1122 NTSTATUS idmap_autorid_iterate_domain_ranges_read(struct db_context *db,
1123                                         const char *domsid,
1124                                         NTSTATUS (*fn)(struct db_context *db,
1125                                                        const char *domsid,
1126                                                        uint32_t index,
1127                                                        uint32_t rangenum,
1128                                                        void *count),
1129                                         void *private_data,
1130                                         int *count)
1131 {
1132         NTSTATUS status;
1133
1134         status = idmap_autorid_iterate_domain_ranges_int(db,
1135                                                          domsid,
1136                                                          fn,
1137                                                          private_data,
1138                                                          count,
1139                                                          dbwrap_traverse_read);
1140
1141         return status;
1142 }
1143
1144
1145 /*
1146  * Delete all ranges configured for a given domain
1147  */
1148
1149 struct delete_domain_ranges_visitor_ctx {
1150         bool force;
1151 };
1152
1153 static NTSTATUS idmap_autorid_delete_domain_ranges_visitor(
1154                                                 struct db_context *db,
1155                                                 const char *domsid,
1156                                                 uint32_t domain_range_index,
1157                                                 uint32_t rangenum,
1158                                                 void *private_data)
1159 {
1160         struct delete_domain_ranges_visitor_ctx *ctx;
1161         NTSTATUS status;
1162
1163         ctx = (struct delete_domain_ranges_visitor_ctx *)private_data;
1164
1165         status = idmap_autorid_delete_range_by_sid(
1166                                 db, domsid, domain_range_index, ctx->force);
1167         return status;
1168 }
1169
1170 struct idmap_autorid_delete_domain_ranges_ctx {
1171         const char *domsid;
1172         bool force;
1173         int count; /* output: count records operated on */
1174 };
1175
1176 static NTSTATUS idmap_autorid_delete_domain_ranges_action(struct db_context *db,
1177                                                           void *private_data)
1178 {
1179         struct idmap_autorid_delete_domain_ranges_ctx *ctx;
1180         struct delete_domain_ranges_visitor_ctx visitor_ctx;
1181         int count;
1182         NTSTATUS status;
1183
1184         ctx = (struct idmap_autorid_delete_domain_ranges_ctx *)private_data;
1185
1186         ZERO_STRUCT(visitor_ctx);
1187         visitor_ctx.force = ctx->force;
1188
1189         status = idmap_autorid_iterate_domain_ranges(db,
1190                                 ctx->domsid,
1191                                 idmap_autorid_delete_domain_ranges_visitor,
1192                                 &visitor_ctx,
1193                                 &count);
1194         if (!NT_STATUS_IS_OK(status)) {
1195                 return status;
1196         }
1197
1198         ctx->count = count;
1199
1200         return NT_STATUS_OK;
1201 }
1202
1203 NTSTATUS idmap_autorid_delete_domain_ranges(struct db_context *db,
1204                                             const char *domsid,
1205                                             bool force,
1206                                             int *count)
1207 {
1208         NTSTATUS status;
1209         struct idmap_autorid_delete_domain_ranges_ctx ctx;
1210
1211         ZERO_STRUCT(ctx);
1212         ctx.domsid = domsid;
1213         ctx.force = force;
1214
1215         status = dbwrap_trans_do(db, idmap_autorid_delete_domain_ranges_action,
1216                                  &ctx);
1217         if (!NT_STATUS_IS_OK(status)) {
1218                 return status;
1219         }
1220
1221         *count = ctx.count;
1222
1223         return NT_STATUS_OK;
1224 }