summaryrefslogtreecommitdiff
path: root/source3/winbindd/idmap_autorid_tdb.c
blob: 7d3275e78df5f04f5e8b21bc09a554b4f953f772 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
/*
 *  idmap_autorid_tdb: This file contains common code used by
 *  idmap_autorid and net idmap autorid utilities. The common
 *  code provides functions for performing various operations
 *  on autorid.tdb
 *
 *  Copyright (C) Christian Ambach, 2010-2012
 *  Copyright (C) Atul Kulkarni, 2013
 *  Copyright (C) Michael Adam, 2012-2013
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "idmap_autorid_tdb.h"
#include "../libcli/security/dom_sid.h"

/**
 * Build the database keystring for getting a range
 * belonging to a domain sid and a range index.
 */
static void idmap_autorid_build_keystr(const char *domsid,
				       uint32_t domain_range_index,
				       fstring keystr)
{
	if (domain_range_index > 0) {
		fstr_sprintf(keystr, "%s#%"PRIu32,
			     domsid, domain_range_index);
	} else {
		fstrcpy(keystr, domsid);
	}
}

static char *idmap_autorid_build_keystr_talloc(TALLOC_CTX *mem_ctx,
					      const char *domsid,
					      uint32_t domain_range_index)
{
	char *keystr;

	if (domain_range_index > 0) {
		keystr = talloc_asprintf(mem_ctx, "%s#%"PRIu32, domsid,
					 domain_range_index);
	} else {
		keystr = talloc_strdup(mem_ctx, domsid);
	}

	return keystr;
}


static bool idmap_autorid_validate_sid(const char *sid)
{
	struct dom_sid ignore;
	if (sid == NULL) {
		return false;
	}

	if (strcmp(sid, ALLOC_RANGE) == 0) {
		return true;
	}

	return dom_sid_parse(sid, &ignore);
}

struct idmap_autorid_addrange_ctx {
	struct autorid_range_config *range;
	bool acquire;
};

static NTSTATUS idmap_autorid_addrange_action(struct db_context *db,
					      void *private_data)
{
	struct idmap_autorid_addrange_ctx *ctx;
	uint32_t requested_rangenum, stored_rangenum;
	struct autorid_range_config *range;
	bool acquire;
	NTSTATUS ret;
	uint32_t hwm;
	char *numstr;
	struct autorid_global_config *globalcfg;
	fstring keystr;
	uint32_t increment;
	TALLOC_CTX *mem_ctx = NULL;

	ctx = (struct idmap_autorid_addrange_ctx *)private_data;
	range = ctx->range;
	acquire = ctx->acquire;
	requested_rangenum = range->rangenum;

	if (db == NULL) {
		DEBUG(3, ("Invalid database argument: NULL"));
		return NT_STATUS_INVALID_PARAMETER;
	}

	if (range == NULL) {
		DEBUG(3, ("Invalid range argument: NULL"));
		return NT_STATUS_INVALID_PARAMETER;
	}

	DEBUG(10, ("Adding new range for domain %s "
		   "(domain_range_index=%"PRIu32")\n",
		   range->domsid, range->domain_range_index));

	if (!idmap_autorid_validate_sid(range->domsid)) {
		DEBUG(3, ("Invalid SID: %s\n", range->domsid));
		return NT_STATUS_INVALID_PARAMETER;
	}

	idmap_autorid_build_keystr(range->domsid, range->domain_range_index,
				   keystr);

	ret = dbwrap_fetch_uint32_bystring(db, keystr, &stored_rangenum);

	if (NT_STATUS_IS_OK(ret)) {
		/* entry is already present*/
		if (acquire) {
			DEBUG(10, ("domain range already allocated - "
				   "Not adding!\n"));
			return NT_STATUS_OK;
		}

		if (stored_rangenum != requested_rangenum) {
			DEBUG(1, ("Error: requested rangenumber (%u) differs "
				  "from stored one (%u).\n",
				  requested_rangenum, stored_rangenum));
			return NT_STATUS_UNSUCCESSFUL;
		}

		DEBUG(10, ("Note: stored range agrees with requested "
			   "one - ok\n"));
		return NT_STATUS_OK;
	}

	/* fetch the current HWM */
	ret = dbwrap_fetch_uint32_bystring(db, HWM, &hwm);
	if (!NT_STATUS_IS_OK(ret)) {
		DEBUG(1, ("Fatal error while fetching current "
			  "HWM value: %s\n", nt_errstr(ret)));
		return NT_STATUS_INTERNAL_ERROR;
	}

	mem_ctx = talloc_stackframe();

	ret = idmap_autorid_loadconfig(db, mem_ctx, &globalcfg);
	if (!NT_STATUS_IS_OK(ret)) {
		DEBUG(1, ("Fatal error while fetching configuration: %s\n",
			  nt_errstr(ret)));
		goto error;
	}

	if (acquire) {
		/*
		 * automatically acquire the next range
		 */
		requested_rangenum = hwm;
	}

	if (requested_rangenum >= globalcfg->maxranges) {
		DEBUG(1, ("Not enough ranges available: New range %u must be "
			  "smaller than configured maximum number of ranges "
			  "(%u).\n",
			  requested_rangenum, globalcfg->maxranges));
		ret = NT_STATUS_NO_MEMORY;
		goto error;
	}

	if (requested_rangenum < hwm) {
		/*
		 * Set a specified range below the HWM:
		 * We need to check that it is not yet taken.
		 */

		numstr = talloc_asprintf(mem_ctx, "%u", requested_rangenum);
		if (!numstr) {
			ret = NT_STATUS_NO_MEMORY;
			goto error;
		}

		if (dbwrap_exists(db, string_term_tdb_data(numstr))) {
			DEBUG(1, ("Requested range already in use.\n"));
			ret = NT_STATUS_INVALID_PARAMETER;
			goto error;
		}

		TALLOC_FREE(numstr);
	} else {
		/*
		 * requested or automatic range >= HWM:
		 * increment the HWM.
		 */

		/* HWM always contains current max range + 1 */
		increment = requested_rangenum + 1 - hwm;

		/* increase the HWM */
		ret = dbwrap_change_uint32_atomic_bystring(db, HWM, &hwm,
							   increment);
		if (!NT_STATUS_IS_OK(ret)) {
			DEBUG(1, ("Fatal error while incrementing the HWM "
				  "value in the database: %s\n",
				  nt_errstr(ret)));
			goto error;
		}
	}

	/*
	 * store away the new mapping in both directions
	 */

	ret = dbwrap_store_uint32_bystring(db, keystr, requested_rangenum);
	if (!NT_STATUS_IS_OK(ret)) {
		DEBUG(1, ("Fatal error while storing new "
			  "domain->range assignment: %s\n", nt_errstr(ret)));
		goto error;
	}

	numstr = talloc_asprintf(mem_ctx, "%u", requested_rangenum);
	if (!numstr) {
		ret = NT_STATUS_NO_MEMORY;
		goto error;
	}

	ret = dbwrap_store_bystring(db, numstr,
			string_term_tdb_data(keystr), TDB_INSERT);

	if (!NT_STATUS_IS_OK(ret)) {
		DEBUG(1, ("Fatal error while storing new "
			  "domain->range assignment: %s\n", nt_errstr(ret)));
		goto error;
	}
	DEBUG(5, ("Acquired new range #%d for domain %s "
		  "(domain_range_index=%"PRIu32")\n", requested_rangenum, keystr,
		  range->domain_range_index));

	range->rangenum = requested_rangenum;

	range->low_id = globalcfg->minvalue
		      + range->rangenum * globalcfg->rangesize;

	ret = NT_STATUS_OK;

error:
	talloc_free(mem_ctx);
	return ret;
}

static NTSTATUS idmap_autorid_addrange(struct db_context *db,
				       struct autorid_range_config *range,
				       bool acquire)
{
	NTSTATUS status;
	struct idmap_autorid_addrange_ctx ctx;

	ctx.acquire = acquire;
	ctx.range = range;

	status = dbwrap_trans_do(db, idmap_autorid_addrange_action, &ctx);
	return status;
}

NTSTATUS idmap_autorid_setrange(struct db_context *db,
				const char *domsid,
				uint32_t domain_range_index,
				uint32_t rangenum)
{
	NTSTATUS status;
	struct autorid_range_config range;

	ZERO_STRUCT(range);
	fstrcpy(range.domsid, domsid);
	range.domain_range_index = domain_range_index;
	range.rangenum = rangenum;

	status = idmap_autorid_addrange(db, &range, false);
	return status;
}

static NTSTATUS idmap_autorid_acquire_range(struct db_context *db,
					    struct autorid_range_config *range)
{
	return idmap_autorid_addrange(db, range, true);
}

static NTSTATUS idmap_autorid_getrange_int(struct db_context *db,
					   struct autorid_range_config *range)
{
	NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
	struct autorid_global_config *globalcfg = NULL;
	fstring keystr;

	if (db == NULL || range == NULL) {
		DEBUG(3, ("Invalid arguments received\n"));
		goto done;
	}

	idmap_autorid_build_keystr(range->domsid, range->domain_range_index,
				   keystr);

	DEBUG(10, ("reading domain range for key %s\n", keystr));
	status = dbwrap_fetch_uint32_bystring(db, keystr, &(range->rangenum));
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Failed to read database for key '%s': %s\n",
			  keystr, nt_errstr(status)));
		goto done;
	}

	status = idmap_autorid_loadconfig(db, talloc_tos(), &globalcfg);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Failed to read global configuration"));
		goto done;
	}
	range->low_id = globalcfg->minvalue
		      + range->rangenum * globalcfg->rangesize;

	TALLOC_FREE(globalcfg);
done:
	return status;
}

NTSTATUS idmap_autorid_getrange(struct db_context *db,
				const char *domsid,
				uint32_t domain_range_index,
				uint32_t *rangenum,
				uint32_t *low_id)
{
	NTSTATUS status;
	struct autorid_range_config range;

	if (rangenum == NULL) {
		return NT_STATUS_INVALID_PARAMETER;
	}

	ZERO_STRUCT(range);
	fstrcpy(range.domsid, domsid);
	range.domain_range_index = domain_range_index;

	status = idmap_autorid_getrange_int(db, &range);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	*rangenum = range.rangenum;

	if (low_id != NULL) {
		*low_id = range.low_id;
	}

	return NT_STATUS_OK;
}

NTSTATUS idmap_autorid_get_domainrange(struct db_context *db,
				       struct autorid_range_config *range,
				       bool read_only)
{
	NTSTATUS ret;

	ret = idmap_autorid_getrange_int(db, range);
	if (!NT_STATUS_IS_OK(ret)) {
		if (read_only) {
			return NT_STATUS_NOT_FOUND;
		}

		ret = idmap_autorid_acquire_range(db, range);
	}

	DEBUG(10, ("Using range #%d for domain %s "
		   "(domain_range_index=%"PRIu32", low_id=%"PRIu32")\n",
		   range->rangenum, range->domsid, range->domain_range_index,
		   range->low_id));

	return ret;
}

/* initialize the given HWM to 0 if it does not exist yet */
NTSTATUS idmap_autorid_init_hwm(struct db_context *db, const char *hwm)
{
	NTSTATUS status;
	uint32_t hwmval;

	status = dbwrap_fetch_uint32_bystring(db, hwm, &hwmval);
	if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND))  {
		status = dbwrap_trans_store_int32_bystring(db, hwm, 0);
		if (!NT_STATUS_IS_OK(status)) {
			DEBUG(0,
			      ("Unable to initialise HWM (%s) in autorid "
			       "database: %s\n", hwm, nt_errstr(status)));
			return NT_STATUS_INTERNAL_DB_ERROR;
		}
	} else if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0, ("unable to fetch HWM (%s) from autorid "
			  "database: %s\n", hwm,  nt_errstr(status)));
		return status;
	}

	return NT_STATUS_OK;
}

/*
 * Delete a domain#index <-> range mapping from the database.
 * The mapping is specified by the sid and index.
 * If force == true, invalid mapping records are deleted as far
 * as possible, otherwise they are left untouched.
 */

struct idmap_autorid_delete_range_by_sid_ctx {
	const char *domsid;
	uint32_t domain_range_index;
	bool force;
};

static NTSTATUS idmap_autorid_delete_range_by_sid_action(struct db_context *db,
							 void *private_data)
{
	struct idmap_autorid_delete_range_by_sid_ctx *ctx =
		(struct idmap_autorid_delete_range_by_sid_ctx *)private_data;
	const char *domsid;
	uint32_t domain_range_index;
	uint32_t rangenum;
	char *keystr;
	char *range_keystr;
	TDB_DATA data;
	NTSTATUS status;
	TALLOC_CTX *frame = talloc_stackframe();
	bool is_valid_range_mapping = true;
	bool force;

	domsid = ctx->domsid;
	domain_range_index = ctx->domain_range_index;
	force = ctx->force;

	keystr = idmap_autorid_build_keystr_talloc(frame, domsid,
						   domain_range_index);
	if (keystr == NULL) {
		status = NT_STATUS_NO_MEMORY;
		goto done;
	}

	status = dbwrap_fetch_uint32_bystring(db, keystr, &rangenum);
	if (!NT_STATUS_IS_OK(status)) {
		goto done;
	}

	range_keystr = talloc_asprintf(frame, "%"PRIu32, rangenum);
	if (range_keystr == NULL) {
		status = NT_STATUS_NO_MEMORY;
		goto done;
	}

	status = dbwrap_fetch_bystring(db, frame, range_keystr, &data);
	if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		DEBUG(1, ("Incomplete mapping %s -> %s: no backward mapping\n",
			  keystr, range_keystr));
		is_valid_range_mapping = false;
	} else if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Error fetching reverse mapping for %s -> %s:  %s\n",
			  keystr, range_keystr, nt_errstr(status)));
		goto done;
	} else if (strncmp((const char *)data.dptr, keystr, strlen(keystr))
		   != 0)
	{
		DEBUG(1, ("Invalid mapping: %s -> %s -> %s\n",
			  keystr, range_keystr, (const char *)data.dptr));
		is_valid_range_mapping = false;
	}

	if (!is_valid_range_mapping && !force) {
		DEBUG(10, ("Not deleting invalid mapping, since not in force "
			   "mode.\n"));
		status = NT_STATUS_FILE_INVALID;
		goto done;
	}

	status = dbwrap_delete_bystring(db, keystr);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Deletion of '%s' failed: %s\n",
			  keystr, nt_errstr(status)));
		goto done;
	}

	if (!is_valid_range_mapping) {
		goto done;
	}

	status = dbwrap_delete_bystring(db, range_keystr);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Deletion of '%s' failed: %s\n",
			  range_keystr, nt_errstr(status)));
		goto done;
	}

	DEBUG(10, ("Deleted range mapping %s <--> %s\n", keystr,
		   range_keystr));

done:
	TALLOC_FREE(frame);
	return status;
}

NTSTATUS idmap_autorid_delete_range_by_sid(struct db_context *db,
					   const char *domsid,
					   uint32_t domain_range_index,
					   bool force)
{
	NTSTATUS status;
	struct idmap_autorid_delete_range_by_sid_ctx ctx;

	ctx.domain_range_index = domain_range_index;
	ctx.domsid = domsid;
	ctx.force = force;

	status = dbwrap_trans_do(db, idmap_autorid_delete_range_by_sid_action,
				 &ctx);
	return status;
}

/*
 * Delete a domain#index <-> range mapping from the database.
 * The mapping is specified by the range number.
 * If force == true, invalid mapping records are deleted as far
 * as possible, otherwise they are left untouched.
 */
struct idmap_autorid_delete_range_by_num_ctx {
	uint32_t rangenum;
	bool force;
};

static NTSTATUS idmap_autorid_delete_range_by_num_action(struct db_context *db,
							   void *private_data)
{
	struct idmap_autorid_delete_range_by_num_ctx *ctx =
		(struct idmap_autorid_delete_range_by_num_ctx *)private_data;
	uint32_t rangenum;
	char *keystr;
	char *range_keystr;
	TDB_DATA val;
	NTSTATUS status;
	TALLOC_CTX *frame = talloc_stackframe();
	bool is_valid_range_mapping = true;
	bool force;

	rangenum = ctx->rangenum;
	force = ctx->force;

	range_keystr = talloc_asprintf(frame, "%"PRIu32, rangenum);
	if (range_keystr == NULL) {
		status = NT_STATUS_NO_MEMORY;
		goto done;
	}

	ZERO_STRUCT(val);

	status = dbwrap_fetch_bystring(db, frame, range_keystr, &val);
	if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		DEBUG(10, ("Did not find range '%s' in database.\n",
			   range_keystr));
		goto done;
	} else if (!NT_STATUS_IS_OK(status)) {
		DEBUG(5, ("Error fetching rang key: %s\n", nt_errstr(status)));
		goto done;
	}

	if (val.dptr == NULL) {
		DEBUG(1, ("Invalid mapping: %s -> empty value\n",
			  range_keystr));
		is_valid_range_mapping = false;
	} else {
		uint32_t reverse_rangenum = 0;

		keystr = (char *)val.dptr;

		status = dbwrap_fetch_uint32_bystring(db, keystr,
						      &reverse_rangenum);
		if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
			DEBUG(1, ("Incomplete mapping %s -> %s: "
				  "no backward mapping\n",
				  range_keystr, keystr));
			is_valid_range_mapping = false;
		} else if (!NT_STATUS_IS_OK(status)) {
			DEBUG(1, ("Error fetching reverse mapping for "
				  "%s -> %s: %s\n",
				  range_keystr, keystr, nt_errstr(status)));
			goto done;
		} else if (rangenum != reverse_rangenum) {
			is_valid_range_mapping = false;
		}
	}

	if (!is_valid_range_mapping && !force) {
		DEBUG(10, ("Not deleting invalid mapping, since not in force "
			   "mode.\n"));
		status = NT_STATUS_FILE_INVALID;
		goto done;
	}

	status = dbwrap_delete_bystring(db, range_keystr);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Deletion of '%s' failed: %s\n",
			  range_keystr, nt_errstr(status)));
		goto done;
	}

	if (!is_valid_range_mapping) {
		goto done;
	}

	status = dbwrap_delete_bystring(db, keystr);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Deletion of '%s' failed: %s\n",
			  keystr, nt_errstr(status)));
		goto done;
	}

	DEBUG(10, ("Deleted range mapping %s <--> %s\n", range_keystr,
		   keystr));

done:
	talloc_free(frame);
	return status;
}

NTSTATUS idmap_autorid_delete_range_by_num(struct db_context *db,
					   uint32_t rangenum,
					   bool force)
{
	NTSTATUS status;
	struct idmap_autorid_delete_range_by_num_ctx ctx;

	ctx.rangenum = rangenum;
	ctx.force = force;

	status = dbwrap_trans_do(db, idmap_autorid_delete_range_by_num_action,
				 &ctx);
	return status;
}

/*
 * open and initialize the database which stores the ranges for the domains
 */
NTSTATUS idmap_autorid_db_init(const char *path,
			       TALLOC_CTX *mem_ctx,
			       struct db_context **db)
{
	NTSTATUS status;

	if (*db != NULL) {
		/* its already open */
		return NT_STATUS_OK;
	}

	/* Open idmap repository */
	*db = db_open(mem_ctx, path, 0, TDB_DEFAULT, O_RDWR | O_CREAT, 0644,
		      DBWRAP_LOCK_ORDER_1);

	if (*db == NULL) {
		DEBUG(0, ("Unable to open idmap_autorid database '%s'\n", path));
		return NT_STATUS_UNSUCCESSFUL;
	}

	/* Initialize high water mark for the currently used range to 0 */

	status = idmap_autorid_init_hwm(*db, HWM);
	NT_STATUS_NOT_OK_RETURN(status);

	status = idmap_autorid_init_hwm(*db, ALLOC_HWM_UID);
	NT_STATUS_NOT_OK_RETURN(status);

	status = idmap_autorid_init_hwm(*db, ALLOC_HWM_GID);

	return status;
}

struct idmap_autorid_fetch_config_state {
	TALLOC_CTX *mem_ctx;
	char *configstr;
};

static void idmap_autorid_config_parser(TDB_DATA key, TDB_DATA value,
					void *private_data)
{
	struct idmap_autorid_fetch_config_state *state;

	state = (struct idmap_autorid_fetch_config_state *)private_data;

	/*
	 * strndup because we have non-nullterminated strings in the db
	 */
	state->configstr = talloc_strndup(
		state->mem_ctx, (const char *)value.dptr, value.dsize);
}

NTSTATUS idmap_autorid_getconfigstr(struct db_context *db, TALLOC_CTX *mem_ctx,
				    char **result)
{
	TDB_DATA key;
	NTSTATUS status;
	struct idmap_autorid_fetch_config_state state;

	if (result == NULL) {
		return NT_STATUS_INVALID_PARAMETER;
	}

	key = string_term_tdb_data(CONFIGKEY);

	state.mem_ctx = mem_ctx;
	state.configstr = NULL;

	status = dbwrap_parse_record(db, key, idmap_autorid_config_parser,
				     &state);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Error while retrieving config: %s\n",
			  nt_errstr(status)));
		return status;
	}

	if (state.configstr == NULL) {
		DEBUG(1, ("Error while retrieving config\n"));
		return NT_STATUS_NO_MEMORY;
	}

	DEBUG(5, ("found CONFIG: %s\n", state.configstr));

	*result = state.configstr;
	return NT_STATUS_OK;
}

bool idmap_autorid_parse_configstr(const char *configstr,
				   struct autorid_global_config *cfg)
{
	unsigned long minvalue, rangesize, maxranges;

	if (sscanf(configstr,
		   "minvalue:%lu rangesize:%lu maxranges:%lu",
		   &minvalue, &rangesize, &maxranges) != 3) {
		DEBUG(1,
		      ("Found invalid configuration data"
		       "creating new config\n"));
		return false;
	}

	cfg->minvalue = minvalue;
	cfg->rangesize = rangesize;
	cfg->maxranges = maxranges;

	return true;
}

NTSTATUS idmap_autorid_loadconfig(struct db_context *db,
				  TALLOC_CTX *mem_ctx,
				  struct autorid_global_config **result)
{
	struct autorid_global_config *cfg;
	NTSTATUS status;
	bool ok;
	char *configstr = NULL;

	if (result == NULL) {
		return NT_STATUS_INVALID_PARAMETER;
	}

	status = idmap_autorid_getconfigstr(db, mem_ctx, &configstr);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	cfg = talloc_zero(mem_ctx, struct autorid_global_config);
	if (cfg == NULL) {
		return NT_STATUS_NO_MEMORY;
	}

	ok = idmap_autorid_parse_configstr(configstr, cfg);
	if (!ok) {
		talloc_free(cfg);
		return NT_STATUS_INVALID_PARAMETER;
	}

	DEBUG(10, ("Loaded previously stored configuration "
		   "minvalue:%d rangesize:%d\n",
		   cfg->minvalue, cfg->rangesize));

	*result = cfg;

	return NT_STATUS_OK;
}

NTSTATUS idmap_autorid_saveconfig(struct db_context *db,
				  struct autorid_global_config *cfg)
{

	struct autorid_global_config *storedconfig = NULL;
	NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
	TDB_DATA data;
	char *cfgstr;
	uint32_t hwm;
	TALLOC_CTX *frame = talloc_stackframe();

	DEBUG(10, ("New configuration provided for storing is "
		   "minvalue:%d rangesize:%d maxranges:%d\n",
		   cfg->minvalue, cfg->rangesize, cfg->maxranges));

	if (cfg->rangesize < 2000) {
		DEBUG(1, ("autorid rangesize must be at least 2000\n"));
		goto done;
	}

	if (cfg->maxranges == 0) {
		DEBUG(1, ("An autorid maxranges value of 0 is invalid. "
			  "Must have at least one range available.\n"));
		goto done;
	}

	status = idmap_autorid_loadconfig(db, frame, &storedconfig);
	if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) {
		DEBUG(5, ("No configuration found. Storing initial "
			  "configuration.\n"));
	} else if (!NT_STATUS_IS_OK(status)) {
		goto done;
	}

	/* did the minimum value or rangesize change? */
	if (storedconfig &&
	    ((storedconfig->minvalue != cfg->minvalue) ||
	     (storedconfig->rangesize != cfg->rangesize)))
	{
		DEBUG(1, ("New configuration values for rangesize or "
			  "minimum uid value conflict with previously "
			  "used values! Not storing new config.\n"));
		status = NT_STATUS_INVALID_PARAMETER;
		goto done;
	}

	status = dbwrap_fetch_uint32_bystring(db, HWM, &hwm);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("Fatal error while fetching current "
			  "HWM value: %s\n", nt_errstr(status)));
		status = NT_STATUS_INTERNAL_ERROR;
		goto done;
	}

	/*
	 * has the highest uid value been reduced to setting that is not
	 * sufficient any more for already existing ranges?
	 */
	if (hwm > cfg->maxranges) {
		DEBUG(1, ("New upper uid limit is too low to cover "
			  "existing mappings! Not storing new config.\n"));
		status = NT_STATUS_INVALID_PARAMETER;
		goto done;
	}

	cfgstr =
	    talloc_asprintf(frame,
			    "minvalue:%u rangesize:%u maxranges:%u",
			    cfg->minvalue, cfg->rangesize, cfg->maxranges);

	if (cfgstr == NULL) {
		status = NT_STATUS_NO_MEMORY;
		goto done;
	}

	data = string_tdb_data(cfgstr);

	status = dbwrap_trans_store_bystring(db, CONFIGKEY, data, TDB_REPLACE);

done:
	TALLOC_FREE(frame);
	return status;
}

NTSTATUS idmap_autorid_saveconfigstr(struct db_context *db,
				     const char *configstr)
{
	bool ok;
	NTSTATUS status;
	struct autorid_global_config cfg;

	ok = idmap_autorid_parse_configstr(configstr, &cfg);
	if (!ok) {
		return NT_STATUS_INVALID_PARAMETER;
	}

	status = idmap_autorid_saveconfig(db, &cfg);
	return status;
}


/*
 * iteration: Work on all range mappings for a given domain
 */

struct domain_range_visitor_ctx {
	const char *domsid;
	NTSTATUS (*fn)(struct db_context *db,
		       const char *domsid,
		       uint32_t index,
		       uint32_t rangenum,
		       void *private_data);
	void *private_data;
	int count; /* number of records worked on */
};

static int idmap_autorid_visit_domain_range(struct db_record *rec,
					    void *private_data)
{
	struct domain_range_visitor_ctx *vi;
	char *domsid;
	char *sep;
	uint32_t range_index = 0;
	uint32_t rangenum = 0;
	TDB_DATA key, value;
	NTSTATUS status;
	int ret = 0;
	struct db_context *db;

	vi = talloc_get_type_abort(private_data,
				   struct domain_range_visitor_ctx);

	key = dbwrap_record_get_key(rec);

	/*
	 * split string "<sid>[#<index>]" into sid string and index number
	 */

	domsid = (char *)key.dptr;

	DEBUG(10, ("idmap_autorid_visit_domain_range: visiting key '%s'\n",
		   domsid));

	sep = strrchr(domsid, '#');
	if (sep != NULL) {
		char *index_str;
		*sep = '\0';
		index_str = sep+1;
		if (sscanf(index_str, "%"SCNu32, &range_index) != 1) {
			DEBUG(10, ("Found separator '#' but '%s' is not a "
				   "valid range index. Skipping record\n",
				   index_str));
			goto done;
		}
	}

	if (!idmap_autorid_validate_sid(domsid)) {
		DEBUG(10, ("String '%s' is not a valid sid. "
			   "Skipping record.\n", domsid));
		goto done;
	}

	if ((vi->domsid != NULL) && (strcmp(domsid, vi->domsid) != 0)) {
		DEBUG(10, ("key sid '%s' does not match requested sid '%s'.\n",
			   domsid, vi->domsid));
		goto done;
	}

	value = dbwrap_record_get_value(rec);

	if (value.dsize != sizeof(uint32_t)) {
		/* it might be a mapping of a well known sid */
		DEBUG(10, ("value size %u != sizeof(uint32_t) for sid '%s', "
			   "skipping.\n", (unsigned)value.dsize, vi->domsid));
		goto done;
	}

	rangenum = IVAL(value.dptr, 0);

	db = dbwrap_record_get_db(rec);

	status = vi->fn(db, domsid, range_index, rangenum, vi->private_data);
	if (!NT_STATUS_IS_OK(status)) {
		ret = -1;
		goto done;
	}

	vi->count++;
	ret = 0;

done:
	return ret;
}

static NTSTATUS idmap_autorid_iterate_domain_ranges_int(struct db_context *db,
				const char *domsid,
				NTSTATUS (*fn)(struct db_context *db,
					       const char *domsid,
					       uint32_t index,
					       uint32_t rangnum,
					       void *private_data),
				void *private_data,
				int *count,
				NTSTATUS (*traverse)(struct db_context *db,
					  int (*f)(struct db_record *, void *),
					  void *private_data,
					  int *count))
{
	NTSTATUS status;
	struct domain_range_visitor_ctx *vi;
	TALLOC_CTX *frame = talloc_stackframe();

	if (domsid == NULL) {
		DEBUG(10, ("No sid provided, operating on all ranges\n"));
	}

	if (fn == NULL) {
		DEBUG(1, ("Error: missing visitor callback\n"));
		status = NT_STATUS_INVALID_PARAMETER;
		goto done;
	}

	vi = talloc_zero(frame, struct domain_range_visitor_ctx);
	if (vi == NULL) {
		status = NT_STATUS_NO_MEMORY;
		goto done;
	}

	vi->domsid = domsid;
	vi->fn = fn;
	vi->private_data = private_data;

	status = traverse(db, idmap_autorid_visit_domain_range, vi, NULL);
	if (!NT_STATUS_IS_OK(status)) {
		goto done;
	}

	if (count != NULL) {
		*count = vi->count;
	}

done:
	talloc_free(frame);
	return status;
}

NTSTATUS idmap_autorid_iterate_domain_ranges(struct db_context *db,
					const char *domsid,
					NTSTATUS (*fn)(struct db_context *db,
						       const char *domsid,
						       uint32_t index,
						       uint32_t rangenum,
						       void *private_data),
					void *private_data,
					int *count)
{
	NTSTATUS status;

	status = idmap_autorid_iterate_domain_ranges_int(db,
							 domsid,
							 fn,
							 private_data,
							 count,
							 dbwrap_traverse);

	return status;
}


NTSTATUS idmap_autorid_iterate_domain_ranges_read(struct db_context *db,
					const char *domsid,
					NTSTATUS (*fn)(struct db_context *db,
						       const char *domsid,
						       uint32_t index,
						       uint32_t rangenum,
						       void *count),
					void *private_data,
					int *count)
{
	NTSTATUS status;

	status = idmap_autorid_iterate_domain_ranges_int(db,
							 domsid,
							 fn,
							 private_data,
							 count,
							 dbwrap_traverse_read);

	return status;
}


/*
 * Delete all ranges configured for a given domain
 */

struct delete_domain_ranges_visitor_ctx {
	bool force;
};

static NTSTATUS idmap_autorid_delete_domain_ranges_visitor(
						struct db_context *db,
						const char *domsid,
						uint32_t domain_range_index,
						uint32_t rangenum,
						void *private_data)
{
	struct delete_domain_ranges_visitor_ctx *ctx;
	NTSTATUS status;

	ctx = (struct delete_domain_ranges_visitor_ctx *)private_data;

	status = idmap_autorid_delete_range_by_sid(
				db, domsid, domain_range_index, ctx->force);
	return status;
}

struct idmap_autorid_delete_domain_ranges_ctx {
	const char *domsid;
	bool force;
	int count; /* output: count records operated on */
};

static NTSTATUS idmap_autorid_delete_domain_ranges_action(struct db_context *db,
							  void *private_data)
{
	struct idmap_autorid_delete_domain_ranges_ctx *ctx;
	struct delete_domain_ranges_visitor_ctx visitor_ctx;
	int count;
	NTSTATUS status;

	ctx = (struct idmap_autorid_delete_domain_ranges_ctx *)private_data;

	ZERO_STRUCT(visitor_ctx);
	visitor_ctx.force = ctx->force;

	status = idmap_autorid_iterate_domain_ranges(db,
				ctx->domsid,
				idmap_autorid_delete_domain_ranges_visitor,
				&visitor_ctx,
				&count);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	ctx->count = count;

	return NT_STATUS_OK;
}

NTSTATUS idmap_autorid_delete_domain_ranges(struct db_context *db,
					    const char *domsid,
					    bool force,
					    int *count)
{
	NTSTATUS status;
	struct idmap_autorid_delete_domain_ranges_ctx ctx;

	ZERO_STRUCT(ctx);
	ctx.domsid = domsid;
	ctx.force = force;

	status = dbwrap_trans_do(db, idmap_autorid_delete_domain_ranges_action,
				 &ctx);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	*count = ctx.count;

	return NT_STATUS_OK;
}