summaryrefslogtreecommitdiffstats
path: root/source3/utils/net_idmap.c
blob: 663831227705f99fe580cb94683d63921c11cd65 (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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
/*
   Samba Unix/Linux SMB client library
   Distributed SMB/CIFS Server Management Utility
   Copyright (C) 2003 Andrew Bartlett (abartlet@samba.org)

   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 "includes.h"
#include "system/filesys.h"
#include "utils/net.h"
#include "secrets.h"
#include "idmap.h"
#include "dbwrap/dbwrap.h"
#include "dbwrap/dbwrap_open.h"
#include "../libcli/security/security.h"
#include "net_idmap_check.h"
#include "util_tdb.h"
#include "idmap_autorid_tdb.h"

#define ALLOC_CHECK(mem) do { \
	if (!mem) { \
		d_fprintf(stderr, _("Out of memory!\n")); \
		talloc_free(ctx); \
		return -1; \
	} } while(0)

enum idmap_dump_backend {
	TDB,
	AUTORID
};

struct net_idmap_ctx {
	enum idmap_dump_backend backend;
};

static int net_idmap_dump_one_autorid_entry(struct db_record *rec,
					    void *unused)
{
	TDB_DATA key;
	TDB_DATA value;

	key = dbwrap_record_get_key(rec);
	value = dbwrap_record_get_value(rec);

	if (strncmp((char *)key.dptr, "CONFIG", 6) == 0) {
		char *config = talloc_array(talloc_tos(), char, value.dsize+1);
		memcpy(config, value.dptr, value.dsize);
		config[value.dsize] = '\0';
		printf("CONFIG: %s\n", config);
		talloc_free(config);
		return 0;
	}

	if (strncmp((char *)key.dptr, "NEXT RANGE", 10) == 0) {
		printf("RANGE HWM: %"PRIu32"\n", IVAL(value.dptr, 0));
		return 0;
	}

	if (strncmp((char *)key.dptr, "NEXT ALLOC UID", 14) == 0) {
		printf("UID HWM: %"PRIu32"\n", IVAL(value.dptr, 0));
		return 0;
	}

	if (strncmp((char *)key.dptr, "NEXT ALLOC GID", 14) == 0) {
		printf("GID HWM: %"PRIu32"\n", IVAL(value.dptr, 0));
		return 0;
	}

	if (strncmp((char *)key.dptr, "UID", 3) == 0 ||
	    strncmp((char *)key.dptr, "GID", 3) == 0)
	{
		/* mapped entry from allocation pool */
		printf("%s %s\n", value.dptr, key.dptr);
		return 0;
	}

	if ((strncmp((char *)key.dptr, "S-1-5-", 6) == 0 ||
	     strncmp((char *)key.dptr, "ALLOC", 5) == 0) &&
	    value.dsize == sizeof(uint32_t))
	{
		/* this is a domain range assignment */
		uint32_t range = IVAL(value.dptr, 0);
		printf("RANGE %"PRIu32": %s\n", range, key.dptr);
		return 0;
	}

	return 0;
}

/***********************************************************
 Helper function for net_idmap_dump. Dump one entry.
 **********************************************************/
static int net_idmap_dump_one_tdb_entry(struct db_record *rec,
					void *unused)
{
	TDB_DATA key;
	TDB_DATA value;

	key = dbwrap_record_get_key(rec);
	value = dbwrap_record_get_value(rec);

	if (strcmp((char *)key.dptr, "USER HWM") == 0) {
		printf(_("USER HWM %d\n"), IVAL(value.dptr,0));
		return 0;
	}

	if (strcmp((char *)key.dptr, "GROUP HWM") == 0) {
		printf(_("GROUP HWM %d\n"), IVAL(value.dptr,0));
		return 0;
	}

	if (strncmp((char *)key.dptr, "S-", 2) != 0) {
		return 0;
	}

	printf("%s %s\n", value.dptr, key.dptr);
	return 0;
}

static const char* net_idmap_dbfile(struct net_context *c,
				    struct net_idmap_ctx *ctx)
{
	const char* dbfile = NULL;
	const char *backend = NULL;

	backend = lp_idmap_default_backend();
	if (!backend) {
		d_printf(_("Internal error: 'idmap config * : backend' is not set!\n"));
		return NULL;
	}

	if (c->opt_db != NULL) {
		dbfile = talloc_strdup(talloc_tos(), c->opt_db);
		if (dbfile == NULL) {
			d_fprintf(stderr, _("Out of memory!\n"));
		}
	} else if (strequal(backend, "tdb")) {
		dbfile = state_path("winbindd_idmap.tdb");
		if (dbfile == NULL) {
			d_fprintf(stderr, _("Out of memory!\n"));
		}
		ctx->backend = TDB;
	} else if (strequal(backend, "tdb2")) {
		dbfile = talloc_asprintf(talloc_tos(), "%s/idmap2.tdb",
					 lp_private_dir());
		if (dbfile == NULL) {
			d_fprintf(stderr, _("Out of memory!\n"));
		}
		ctx->backend = TDB;
	} else if (strequal(backend, "autorid")) {
		dbfile = state_path("autorid.tdb");
		if (dbfile == NULL) {
			d_fprintf(stderr, _("Out of memory!\n"));
		}
		ctx->backend = AUTORID;
	} else {
		char *_backend = talloc_strdup(talloc_tos(), backend);
		char* args = strchr(_backend, ':');
		if (args != NULL) {
			*args = '\0';
		}

		d_printf(_("Sorry, 'idmap backend = %s' is currently not supported\n"),
			   _backend);

		talloc_free(_backend);
	}

	return dbfile;
}

static bool net_idmap_opendb_autorid(TALLOC_CTX *mem_ctx,
				     struct net_context *c,
				     bool readonly,
				     struct db_context **db)
{
	bool ret = false;
	const char *dbfile;
	struct net_idmap_ctx ctx = { .backend = AUTORID };

	if (c == NULL) {
		goto done;
	}

	dbfile = net_idmap_dbfile(c, &ctx);
	if (dbfile == NULL) {
		goto done;
	}

	if (ctx.backend != AUTORID) {
		d_fprintf(stderr, _("Unsupported backend\n"));
		goto done;
	}

	if (readonly) {
		*db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDONLY, 0,
			     DBWRAP_LOCK_ORDER_1);
		if (*db == NULL) {
			d_fprintf(stderr,
				  _("Could not open autorid db (%s): %s\n"),
				 dbfile, strerror(errno));
			goto done;
		}
	} else {
		NTSTATUS status;
		status = idmap_autorid_db_init(dbfile, mem_ctx, db);
		if (!NT_STATUS_IS_OK(status)) {
			d_fprintf(stderr,
				_("Error calling idmap_autorid_db_init: %s\n"),
				nt_errstr(status));
			goto done;
		}
	}

	ret = true;

done:
	return ret;
}


/***********************************************************
 Dump the current idmap
 **********************************************************/
static int net_idmap_dump(struct net_context *c, int argc, const char **argv)
{
	struct db_context *db;
	TALLOC_CTX *mem_ctx;
	const char* dbfile;
	NTSTATUS status;
	int ret = -1;
	struct net_idmap_ctx ctx = { .backend = TDB };

	if ( argc > 1  || c->display_usage) {
		d_printf("%s\n%s",
			 _("Usage:"),
			 _("net idmap dump [[--db=]<inputfile>]\n"
			   "  Dump current ID mapping.\n"
			   "    inputfile\tTDB file to read mappings from.\n"));
		return c->display_usage?0:-1;
	}

	mem_ctx = talloc_stackframe();

	dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c, &ctx);
	if (dbfile == NULL) {
		goto done;
	}
	d_fprintf(stderr, _("dumping id mapping from %s\n"), dbfile);

	db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDONLY, 0,
		     DBWRAP_LOCK_ORDER_1);
	if (db == NULL) {
		d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
			  dbfile, strerror(errno));
		goto done;
	}

	if (ctx.backend == AUTORID) {
		status = dbwrap_traverse_read(db,
					      net_idmap_dump_one_autorid_entry,
					      NULL, NULL);
	} else {
		status = dbwrap_traverse_read(db,
					      net_idmap_dump_one_tdb_entry,
					      NULL, NULL);
	}
	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, _("error traversing the database\n"));
		ret = -1;
		goto done;
	}

	ret = 0;

done:
	talloc_free(mem_ctx);
	return ret;
}

/***********************************************************
 Write entries from stdin to current local idmap
 **********************************************************/

static int net_idmap_store_id_mapping(struct db_context *db,
				      enum id_type type,
				      unsigned long idval,
				      const char *sid_string)
{
	NTSTATUS status;
	char *idstr = NULL;

	switch(type) {
	case ID_TYPE_UID:
		idstr = talloc_asprintf(talloc_tos(), "UID %lu", idval);
		break;
	case ID_TYPE_GID:
		idstr = talloc_asprintf(talloc_tos(), "GID %lu", idval);
		break;
	default:
		d_fprintf(stderr, "Invalid id mapping type: %d\n", type);
		return -1;
	}

	status = dbwrap_store_bystring(db, idstr,
				       string_term_tdb_data(sid_string),
				       TDB_REPLACE);
	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, "Error storing ID -> SID: "
			 "%s\n", nt_errstr(status));
		talloc_free(idstr);
		return -1;
	}
	status = dbwrap_store_bystring(db, sid_string,
				       string_term_tdb_data(idstr),
				       TDB_REPLACE);
	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, "Error storing SID -> ID: "
			 "%s\n", nt_errstr(status));
		talloc_free(idstr);
		return -1;
	}

	return 0;
}

static int net_idmap_restore(struct net_context *c, int argc, const char **argv)
{
	TALLOC_CTX *mem_ctx;
	FILE *input = NULL;
	struct db_context *db;
	const char *dbfile = NULL;
	int ret = 0;
	struct net_idmap_ctx ctx = { .backend = TDB };

	if (c->display_usage) {
		d_printf("%s\n%s",
			 _("Usage:"),
			 _("net idmap restore [--db=<TDB>] [<inputfile>]\n"
			   "  Restore ID mappings from file\n"
			   "    TDB\tFile to store ID mappings to."
			   "    inputfile\tFile to load ID mappings from. If not "
			   "given, load data from stdin.\n"));
		return 0;
	}

	mem_ctx = talloc_stackframe();

	dbfile = net_idmap_dbfile(c, &ctx);

	if (dbfile == NULL) {
		ret = -1;
		goto done;
	}

	if (ctx.backend != TDB) {
		d_fprintf(stderr, _("Sorry, restoring of non-TDB databases is "
				    "currently not supported\n"));
		ret = -1;
		goto done;
	}

	d_fprintf(stderr, _("restoring id mapping to %s\n"), dbfile);

	if (argc == 1) {
		input = fopen(argv[0], "r");
		if (input == NULL) {
			d_fprintf(stderr, _("Could not open input file (%s): %s\n"),
				  argv[0], strerror(errno));
			ret = -1;
			goto done;
		}
	} else {
		input = stdin;
	}

	db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR|O_CREAT, 0644,
		     DBWRAP_LOCK_ORDER_1);
	if (db == NULL) {
		d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
			  dbfile, strerror(errno));
		ret = -1;
		goto done;
	}

	if (dbwrap_transaction_start(db) != 0) {
		d_fprintf(stderr, _("Failed to start transaction.\n"));
		ret = -1;
		goto done;
	}

	while (!feof(input)) {
		char line[128], sid_string[128];
		int len;
		unsigned long idval;
		NTSTATUS status;

		if (fgets(line, 127, input) == NULL)
			break;

		len = strlen(line);

		if ( (len > 0) && (line[len-1] == '\n') )
			line[len-1] = '\0';

		if (sscanf(line, "GID %lu %128s", &idval, sid_string) == 2)
		{
			ret = net_idmap_store_id_mapping(db, ID_TYPE_GID,
							 idval, sid_string);
			if (ret != 0) {
				break;
			}
		} else if (sscanf(line, "UID %lu %128s", &idval, sid_string) == 2)
		{
			ret = net_idmap_store_id_mapping(db, ID_TYPE_UID,
							 idval, sid_string);
			if (ret != 0) {
				break;
			}
		} else if (sscanf(line, "USER HWM %lu", &idval) == 1) {
			status = dbwrap_store_int32_bystring(
				db, "USER HWM", idval);
			if (!NT_STATUS_IS_OK(status)) {
				d_fprintf(stderr,
					  _("Could not store USER HWM: %s\n"),
					  nt_errstr(status));
				break;
			}
		} else if (sscanf(line, "GROUP HWM %lu", &idval) == 1) {
			status = dbwrap_store_int32_bystring(
				db, "GROUP HWM", idval);
			if (!NT_STATUS_IS_OK(status)) {
				d_fprintf(stderr,
					  _("Could not store GROUP HWM: %s\n"),
					  nt_errstr(status));
				break;
			}
		} else {
			d_fprintf(stderr, _("ignoring invalid line [%s]\n"),
				  line);
			continue;
		}
	}

	if (ret == 0) {
		if(dbwrap_transaction_commit(db) != 0) {
			d_fprintf(stderr, _("Failed to commit transaction.\n"));
			ret = -1;
		}
	} else {
		if (dbwrap_transaction_cancel(db) != 0) {
			d_fprintf(stderr, _("Failed to cancel transaction.\n"));
		}
	}

done:
	if ((input != NULL) && (input != stdin)) {
		fclose(input);
	}

	talloc_free(mem_ctx);
	return ret;
}

static
NTSTATUS dbwrap_delete_mapping(struct db_context *db, TDB_DATA key1, bool force)
{
	TALLOC_CTX *mem_ctx = talloc_stackframe();
	bool is_valid_mapping;
	NTSTATUS status = NT_STATUS_OK;
	TDB_DATA val1, val2;

	ZERO_STRUCT(val1);
	ZERO_STRUCT(val2);

	status = dbwrap_fetch(db, mem_ctx, key1, &val1);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("failed to fetch: %.*s\n", (int)key1.dsize, key1.dptr));
		goto done;
	}

	if (val1.dptr == NULL) {
		DEBUG(1, ("invalid mapping: %.*s -> empty value\n",
			  (int)key1.dsize, key1.dptr));
		status = NT_STATUS_FILE_INVALID;
		goto done;
	}

	DEBUG(2, ("mapping: %.*s -> %.*s\n",
		  (int)key1.dsize, key1.dptr, (int)val1.dsize, val1.dptr));

	status = dbwrap_fetch(db, mem_ctx, val1, &val2);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("failed to fetch: %.*s\n", (int)val1.dsize, val1.dptr));
		goto done;
	}

	is_valid_mapping = tdb_data_equal(key1, val2);

	if (!is_valid_mapping) {
		DEBUG(1, ("invalid mapping: %.*s -> %.*s -> %.*s\n",
			  (int)key1.dsize, key1.dptr,
			  (int)val1.dsize, val1.dptr,
			  (int)val2.dsize, val2.dptr));
		if ( !force ) {
			status = NT_STATUS_FILE_INVALID;
			goto done;
		}
	}

	status = dbwrap_delete(db, key1);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("failed to delete: %.*s\n", (int)key1.dsize, key1.dptr));
		goto done;
	}

	if (!is_valid_mapping) {
		goto done;
	}

	status = dbwrap_delete(db, val1);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("failed to delete: %.*s\n", (int)val1.dsize, val1.dptr));
	}

done:
	talloc_free(mem_ctx);
	return status;
}

static
NTSTATUS delete_mapping_action(struct db_context *db, void* data)
{
	return dbwrap_delete_mapping(db, *(TDB_DATA*)data, false);
}
static
NTSTATUS delete_mapping_action_force(struct db_context *db, void* data)
{
	return dbwrap_delete_mapping(db, *(TDB_DATA*)data, true);
}

/***********************************************************
 Delete a SID mapping from a winbindd_idmap.tdb
 **********************************************************/
static bool delete_args_ok(int argc, const char **argv)
{
	if (argc != 1)
		return false;
	if (strncmp(argv[0], "S-", 2) == 0)
		return true;
	if (strncmp(argv[0], "GID ", 4) == 0)
		return true;
	if (strncmp(argv[0], "UID ", 4) == 0)
		return true;
	return false;
}

static int net_idmap_delete_mapping(struct net_context *c, int argc,
				    const char **argv)
{
	int ret = -1;
	struct db_context *db;
	TALLOC_CTX *mem_ctx;
	TDB_DATA key;
	NTSTATUS status;
	const char* dbfile;
	struct net_idmap_ctx ctx = { .backend = TDB };

	if ( !delete_args_ok(argc,argv) || c->display_usage) {
		d_printf("%s\n%s",
			 _("Usage:"),
			 _("net idmap delete mapping [-f] [--db=<TDB>] <ID>\n"
			   "  Delete mapping of ID from TDB.\n"
			   "    -f\tforce\n"
			   "    TDB\tidmap database\n"
			   "    ID\tSID|GID|UID\n"));
		return c->display_usage ? 0 : -1;
	}

	mem_ctx = talloc_stackframe();

	dbfile = net_idmap_dbfile(c, &ctx);
	if (dbfile == NULL) {
		goto done;
	}
	d_fprintf(stderr, _("deleting id mapping from %s\n"), dbfile);

	db = db_open(mem_ctx, dbfile, 0, TDB_DEFAULT, O_RDWR, 0,
		     DBWRAP_LOCK_ORDER_1);
	if (db == NULL) {
		d_fprintf(stderr, _("Could not open idmap db (%s): %s\n"),
			  dbfile, strerror(errno));
		goto done;
	}

	key = string_term_tdb_data(argv[0]);

	status = dbwrap_trans_do(db, (c->opt_force
				      ? delete_mapping_action_force
				      : delete_mapping_action),  &key);

	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, _("could not delete mapping: %s\n"),
			  nt_errstr(status));
		goto done;
	}
	ret = 0;
done:
	talloc_free(mem_ctx);
	return ret;
}

static bool parse_uint32(const char *str, uint32_t *result)
{
	unsigned long val;
	char *endptr;

	val = strtoul(str, &endptr, 10);

	if (str == endptr) {
		return false;
	}
	if (*endptr != '\0') {
		return false;
	}
	if ((val == ULONG_MAX) && (errno == ERANGE)) {
		return false;
	}
	if ((val & UINT32_MAX) != val) {
		/* overflow */
		return false;
	}
	*result = val;		/* Potential crop */
	return true;
}

static void net_idmap_autorid_delete_range_usage(void)
{
	d_printf("%s\n%s",
		 _("Usage:"),
		 _("net idmap delete range [-f] [--db=<TDB>] <RANGE>|(<SID>[ <INDEX>])\n"
		   "  Delete a domain range mapping from the database.\n"
		   "    -f\tforce\n"
		   "    TDB\tidmap database\n"
		   "    RANGE\tthe range number to delete\n"
		   "    SID\t\tSID of the domain\n"
		   "    INDEX\trange index number do delete for the domain\n"));
}

static int net_idmap_autorid_delete_range(struct net_context *c, int argc,
					  const char **argv)
{
	int ret = -1;
	struct db_context *db = NULL;
	NTSTATUS status;
	uint32_t rangenum;
	uint32_t range_index;
	const char *domsid;
	TALLOC_CTX *mem_ctx = NULL;
	bool ok;
	bool force = (c->opt_force != 0);

	if (c->display_usage) {
		net_idmap_autorid_delete_range_usage();
		return 0;
	}

	if (argc < 1 || argc > 2) {
		net_idmap_autorid_delete_range_usage();
		return -1;
	}

	mem_ctx = talloc_stackframe();
	if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
		goto done;
	}

	ok = parse_uint32(argv[0], &rangenum);
	if (ok) {
		d_printf("%s: %"PRIu32"\n", _("Deleting range number"),
			 rangenum);

		status = idmap_autorid_delete_range_by_num(db, rangenum,
							   force);
		if (!NT_STATUS_IS_OK(status)) {
			d_fprintf(stderr, "%s: %s\n",
				  _("Failed to delete domain range mapping"),
				  nt_errstr(status));
		} else {
			ret = 0;
		}

		goto done;
	}

	domsid = argv[0];

	if (argc == 2) {
		ok = parse_uint32(argv[1], &range_index);
		if (!ok) {
			d_printf("%s: %s\n",
				 _("Invalid index specification"), argv[1]);
			net_idmap_autorid_delete_range_usage();
			goto done;
		}
	}

	status = idmap_autorid_delete_range_by_sid(db, domsid, range_index,
						   force);
	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, "%s: %s\n",
			  _("Failed to delete domain range mapping"),
			  nt_errstr(status));
		goto done;
	}

	ret = 0;

done:
	talloc_free(mem_ctx);
	return ret;
}

static void net_idmap_autorid_delete_ranges_usage(void)
{
	d_printf("%s\n%s",
		 _("Usage:"),
		 _("net idmap delete ranges [-f] [--db=<TDB>] <SID>)\n"
		   "  Delete all domain range mappings for a given domain.\n"
		   "    -f\tforce\n"
		   "    TDB\tidmap database\n"
		   "    SID\t\tSID of the domain\n"));
}

static int net_idmap_autorid_delete_ranges(struct net_context *c, int argc,
					   const char **argv)
{
	int ret = -1;
	struct db_context *db = NULL;
	NTSTATUS status;
	const char *domsid;
	TALLOC_CTX *mem_ctx = NULL;
	bool force = (c->opt_force != 0);
	int count = 0;

	if (c->display_usage) {
		net_idmap_autorid_delete_ranges_usage();
		return 0;
	}

	if (argc != 1) {
		net_idmap_autorid_delete_ranges_usage();
		return -1;
	}

	domsid = argv[0];

	mem_ctx = talloc_stackframe();
	if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
		goto done;
	}

	status = idmap_autorid_delete_domain_ranges(db, domsid, force, &count);
	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, "%s %s: %s\n",
			  _("Failed to delete domain range mappings for "
			    "domain"),
			  domsid,
			  nt_errstr(status));
		goto done;
	}

	d_printf(_("deleted %d domain mappings\n"), count);

	ret = 0;

done:
	talloc_free(mem_ctx);
	return ret;
}

static int net_idmap_delete(struct net_context *c, int argc, const char **argv)
{
	struct functable func[] = {
		{
			"mapping",
			net_idmap_delete_mapping,
			NET_TRANSPORT_LOCAL,
			N_("Delete ID mapping"),
			N_("net idmap delete mapping <ID>\n"
			   "  Delete ID mapping")
		},
		{
			"range",
			net_idmap_autorid_delete_range,
			NET_TRANSPORT_LOCAL,
			N_("Delete a domain range mapping"),
			N_("net idmap delete range <RANGE>|(<SID>[ <INDEX>])\n"
			   "  Delete a domain range mapping")
		},
		{
			"ranges",
			net_idmap_autorid_delete_ranges,
			NET_TRANSPORT_LOCAL,
			N_("Delete all domain range mapping for a given "
			   "domain"),
			N_("net idmap delete ranges <SID>\n"
			   "  Delete a domain range mapping")
		},
		{NULL, NULL, 0, NULL, NULL}
	};

	return net_run_function(c, argc, argv, "net idmap delete", func);
}


static int net_idmap_set_mapping(struct net_context *c,
				 int argc, const char **argv)
{
	d_printf("%s\n", _("Not implemented yet"));
	return -1;
}

static void net_idmap_autorid_set_range_usage(void)
{
	d_printf("%s\n%s",
		 _("Usage:"),
		 _("net idmap set range"
		   " <range> <SID> [<index>] [--db=<inputfile>]\n"
		   "  Store a domain-range mapping for a given domain.\n"
		   "    range\tRange number to be set for the domain\n"
		   "    SID\t\tSID of the domain\n"
		   "    index\trange-index number to be set for the domain\n"
		   "    inputfile\tTDB file to add mapping to.\n"));
}

static int net_idmap_autorid_set_range(struct net_context *c,
				       int argc, const char **argv)
{
	int ret = -1;
	TALLOC_CTX *mem_ctx;
	struct db_context *db = NULL;
	const char *domsid;
	uint32_t rangenum;
	uint32_t range_index = 0;
	NTSTATUS status;
	bool ok;

	if (c->display_usage) {
		net_idmap_autorid_set_range_usage();
		return 0;
	}

	if (argc < 2  || argc > 3) {
		net_idmap_autorid_set_range_usage();
		return -1;
	}

	ok = parse_uint32(argv[0], &rangenum);
	if (!ok) {
		d_printf("%s: %s\n", _("Invalid range specification"),
			 argv[0]);
		net_idmap_autorid_set_range_usage();
		return -1;
	}

	domsid = argv[1];

	if (argc == 3) {
		ok = parse_uint32(argv[2], &range_index);
		if (!ok) {
			d_printf("%s: %s\n",
				 _("Invalid index specification"), argv[2]);
			net_idmap_autorid_set_range_usage();
			return -1;
		}
	}

	mem_ctx = talloc_stackframe();
	if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
		goto done;
	}

	status = idmap_autorid_setrange(db, domsid, range_index, rangenum);
	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, "%s: %s\n",
			  _("Failed to save domain mapping"),
			  nt_errstr(status));
		goto done;
	}

	ret = 0;

done:
	TALLOC_FREE(mem_ctx);
	return ret;
}

static bool idmap_store_secret(const char *backend,
			       const char *domain,
			       const char *identity,
			       const char *secret)
{
	char *tmp;
	int r;
	bool ret;

	r = asprintf(&tmp, "IDMAP_%s_%s", backend, domain);

	if (r < 0) return false;

	/* make sure the key is case insensitive */
	if (!strupper_m(tmp)) {
		free(tmp);
		return false;
	}
	ret = secrets_store_generic(tmp, identity, secret);

	free(tmp);
	return ret;
}


static int net_idmap_secret(struct net_context *c, int argc, const char **argv)
{
	TALLOC_CTX *ctx;
	const char *secret;
	const char *dn;
	char *domain;
	char *backend;
	char *opt = NULL;
	bool ret;

	if (argc != 2 || c->display_usage) {
		d_printf("%s\n%s",
			 _("Usage:\n"),
			 _("net idmap set secret <DOMAIN> <secret>\n"
			   "  Set the secret for the specified domain\n"
			   "    DOMAIN\tDomain to set secret for.\n"
			   "    secret\tNew secret to set.\n"));
		return c->display_usage?0:-1;
	}

	secret = argv[1];

	ctx = talloc_new(NULL);
	ALLOC_CHECK(ctx);

	domain = talloc_strdup(ctx, argv[0]);
	ALLOC_CHECK(domain);

	opt = talloc_asprintf(ctx, "idmap config %s", domain);
	ALLOC_CHECK(opt);

	backend = talloc_strdup(ctx, lp_parm_const_string(-1, opt, "backend", "tdb"));
	ALLOC_CHECK(backend);

	if ((!backend) || (!strequal(backend, "ldap") &&
			   !strequal(backend, "rfc2307"))) {
		d_fprintf(stderr,
			  _("The only currently supported backend are LDAP "
			    "and rfc2307\n"));
		talloc_free(ctx);
		return -1;
	}

	dn = lp_parm_const_string(-1, opt, "ldap_user_dn", NULL);
	if ( ! dn) {
		d_fprintf(stderr,
			  _("Missing ldap_user_dn option for domain %s\n"),
			  domain);
		talloc_free(ctx);
		return -1;
	}

	ret = idmap_store_secret("ldap", domain, dn, secret);

	if ( ! ret) {
		d_fprintf(stderr, _("Failed to store secret\n"));
		talloc_free(ctx);
		return -1;
	}

	d_printf(_("Secret stored\n"));
	return 0;
}

static int net_idmap_autorid_set_config(struct net_context *c,
					int argc, const char **argv)
{
	int ret = -1;
	NTSTATUS status;
	TALLOC_CTX *mem_ctx;
	struct db_context *db = NULL;

	if (argc != 1 || c->display_usage) {
		d_printf("%s\n%s",
			 _("Usage:"),
			 _("net idmap set config <config>"
			   " [--db=<inputfile>]\n"
			   " Update CONFIG entry in autorid.\n"
			   "	config\tConfig string to be stored\n"
			   "	inputfile\tTDB file to update config.\n"));
		return c->display_usage ? 0 : -1;
	}

	mem_ctx = talloc_stackframe();

	if (!net_idmap_opendb_autorid(mem_ctx, c, false, &db)) {
		goto done;
	}

	status = idmap_autorid_saveconfigstr(db, argv[0]);
	if (!NT_STATUS_IS_OK(status)) {
		printf("Error storing the config in the database: %s\n",
		       nt_errstr(status));
		goto done;
	}

	ret = 0;

done:
	TALLOC_FREE(mem_ctx);
	return ret;
}

static int net_idmap_set(struct net_context *c, int argc, const char **argv)
{
	struct functable func[] = {
		{
			"mapping",
			net_idmap_set_mapping,
			NET_TRANSPORT_LOCAL,
			N_("Not implemented yet"),
			N_("net idmap set mapping\n"
			   "  Not implemented yet")
		},
		{
			"range",
			net_idmap_autorid_set_range,
			NET_TRANSPORT_LOCAL,
			N_("Store a domain-range mapping"),
			N_("net idmap set range\n"
			   "  Store a domain-range mapping")
		},
		{
			"config",
			net_idmap_autorid_set_config,
			NET_TRANSPORT_LOCAL,
			N_("Save the global configuration in the autorid database"),
			N_("net idmap set config \n"
			   "  Save the global configuration in the autorid database ")
		},
		{
			"secret",
			net_idmap_secret,
			NET_TRANSPORT_LOCAL,
			N_("Set secret for specified domain"),
			N_("net idmap set secret <DOMAIN> <secret>\n"
			   "  Set secret for specified domain")
		},
		{NULL, NULL, 0, NULL, NULL}
	};

	return net_run_function(c, argc, argv, "net idmap set", func);
}

static void net_idmap_autorid_get_range_usage(void)
{
	d_printf("%s\n%s",
		 _("Usage:"),
		 _("net idmap get range <SID> [<index>] [--db=<inputfile>]\n"
		   "  Get the range for a given domain and index.\n"
		   "    SID\t\tSID of the domain\n"
		   "    index\trange-index number to be retrieved\n"
		   "    inputfile\tTDB file to add mapping to.\n"));
}


static int net_idmap_autorid_get_range(struct net_context *c, int argc,
				       const char **argv)
{
	int ret = -1;
	TALLOC_CTX *mem_ctx;
	struct db_context *db = NULL;
	const char *domsid;
	uint32_t rangenum;
	uint32_t range_index = 0;
	uint32_t low_id;
	NTSTATUS status;
	char *keystr;
	bool ok;

	if (c->display_usage) {
		net_idmap_autorid_get_range_usage();
		return 0;
	}

	if (argc < 1  || argc > 2) {
		net_idmap_autorid_get_range_usage();
		return -1;
	}

	domsid = argv[0];

	if (argc == 2) {
		ok = parse_uint32(argv[1], &range_index);
		if (!ok) {
			d_printf("%s: %s\n",
				 _("Invalid index specification"), argv[1]);
			net_idmap_autorid_get_range_usage();
			return -1;
		}
	}

	mem_ctx = talloc_stackframe();
	if (!net_idmap_opendb_autorid(mem_ctx, c, true, &db)) {
		goto done;
	}

	status = idmap_autorid_getrange(db, domsid, range_index, &rangenum,
					&low_id);
	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, "%s: %s\n",
			  _("Failed to load domain range"), nt_errstr(status));
		goto done;
	}

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

	printf("RANGE %"PRIu32": %s (low id: %"PRIu32")\n",
	       rangenum, keystr, low_id);

	ret = 0;

done:
	TALLOC_FREE(mem_ctx);
	return ret;
}

static NTSTATUS net_idmap_autorid_print_range(struct db_context *db,
					      const char *domsid,
					      uint32_t range_index,
					      uint32_t rangenum,
					      void *private_data)
{
	if (range_index == 0) {
		printf("RANGE %"PRIu32": %s\n", rangenum, domsid);
	} else {
		printf("RANGE %"PRIu32": %s#%"PRIu32"\n", rangenum, domsid,
		       range_index);
	}

	return NT_STATUS_OK;
}

static void net_idmap_autorid_get_ranges_usage(void)
{
	d_printf("%s\n%s",
		 _("Usage:"),
		 _("net idmap get ranges <SID> [--db=<inputfile>]\n"
		   "  Get all ranges for a given domain.\n"
		   "    SID\t\tSID of the domain\n"
		   "    inputfile\tTDB file to add mapping to.\n"));
}

static int net_idmap_autorid_get_ranges(struct net_context *c, int argc,
					const char **argv)
{
	int ret = -1;
	TALLOC_CTX *mem_ctx;
	struct db_context *db = NULL;
	const char *domsid;
	NTSTATUS status;

	if (c->display_usage) {
		net_idmap_autorid_get_ranges_usage();
		return 0;
	}

	if (argc != 1) {
		net_idmap_autorid_get_ranges_usage();
		return -1;
	}

	domsid = argv[0];

	mem_ctx = talloc_stackframe();
	if (!net_idmap_opendb_autorid(mem_ctx, c, true, &db)) {
		goto done;
	}

	status = idmap_autorid_iterate_domain_ranges_read(db,
						domsid,
						net_idmap_autorid_print_range,
						NULL, /* private_data */
						NULL  /* count */);
	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, "%s: %s\n",
			  _("Error getting domain ranges"), nt_errstr(status));
		goto done;
	}

	ret = 0;

done:
	talloc_free(mem_ctx);
	return ret;
}

static int net_idmap_autorid_get_config(struct net_context *c, int argc,
					const char **argv)
{
	int ret = -1;
	char *config;
	TALLOC_CTX *mem_ctx;
	NTSTATUS status;
	struct db_context *db = NULL;

	if (argc > 0 || c->display_usage) {
		d_printf("%s\n%s",
			 _("Usage:"),
			 _("net idmap get config"
			   " [--db=<inputfile>]\n"
			   " Get CONFIG entry from autorid database\n"
			   "	inputfile\tTDB file to read config from.\n"));
		return c->display_usage ? 0 : -1;
	}

	mem_ctx = talloc_stackframe();

	if (!net_idmap_opendb_autorid(mem_ctx, c, true, &db)) {
		goto done;
	}

	status = idmap_autorid_getconfigstr(db, mem_ctx, &config);
	if (!NT_STATUS_IS_OK(status)) {
		d_fprintf(stderr, "%s: %s\n",
			  _("Error: unable to read config entry"),
			  nt_errstr(status));
		goto done;
	}

	printf("CONFIG: %s\n", config);
	ret = 0;

done:
	TALLOC_FREE(mem_ctx);
	return ret;
}


static int net_idmap_get(struct net_context *c, int argc, const char **argv)
{
	struct functable func[] = {
		{
			"range",
			net_idmap_autorid_get_range,
			NET_TRANSPORT_LOCAL,
			N_("Get the range for a domain and range-index"),
			N_("net idmap get range\n"
			   "  Get the range for a domain and range-index")
		},
		{
			"ranges",
			net_idmap_autorid_get_ranges,
			NET_TRANSPORT_LOCAL,
			N_("Get all ranges for a domain"),
			N_("net idmap get ranges <SID>\n"
			   "  Get all ranges for a domain")
		},
		{
			"config",
			net_idmap_autorid_get_config,
			NET_TRANSPORT_LOCAL,
			N_("Get the global configuration from the autorid database"),
			N_("net idmap get config \n"
			   "  Get the global configuration from the autorid database ")
		},
		{NULL, NULL, 0, NULL, NULL}
	};

	return net_run_function(c, argc, argv, "net idmap get", func);
}

static int net_idmap_check(struct net_context *c, int argc, const char **argv)
{
	const char* dbfile;
	struct check_options opts;
	struct net_idmap_ctx ctx = { .backend = TDB };

	if ( argc > 1 || c->display_usage) {
		d_printf("%s\n%s",
			 _("Usage:"),
			 _("net idmap check  [-v] [-r] [-a] [-T] [-f] [-l] [[--db=]<TDB>]\n"
			   "  Check an idmap database.\n"
			   "    --verbose,-v\tverbose\n"
			   "    --repair,-r\trepair\n"
			   "    --auto,-a\tnoninteractive mode\n"
			   "    --test,-T\tdry run\n"
			   "    --fore,-f\tforce\n"
			   "    --lock,-l\tlock db while doing the check\n"
			   "    TDB\tidmap database\n"));
		return c->display_usage ? 0 : -1;
	}

	dbfile = (argc > 0) ? argv[0] : net_idmap_dbfile(c, &ctx);
	if (dbfile == NULL) {
		return -1;
	}

	if (ctx.backend != TDB) {
		d_fprintf(stderr, _("Sorry, checking of non-TDB databases is "
				    "currently not supported\n"));
		return -1;
	}

	d_fprintf(stderr, _("check database: %s\n"), dbfile);

	opts = (struct check_options) {
		.lock = c->opt_lock || c->opt_long_list_entries,
		.test = c->opt_testmode,
		.automatic = c->opt_auto,
		.verbose = c->opt_verbose,
		.force = c->opt_force,
		.repair = c->opt_repair || c->opt_reboot,
	};

	return net_idmap_check_db(dbfile, &opts);
}

/***********************************************************
 Look at the current idmap
 **********************************************************/
int net_idmap(struct net_context *c, int argc, const char **argv)
{
	struct functable func[] = {
		{
			"dump",
			net_idmap_dump,
			NET_TRANSPORT_LOCAL,
			N_("Dump the current ID mapping database"),
			N_("net idmap dump\n"
			   "  Dump the current ID mappings")
		},
		{
			"restore",
			net_idmap_restore,
			NET_TRANSPORT_LOCAL,
			N_("Restore entries from a file or stdin"),
			N_("net idmap restore\n"
			   "  Restore entries from stdin")
		},
		{
			"get",
			net_idmap_get,
			NET_TRANSPORT_LOCAL,
			N_("Read data from the ID mapping database"),
			N_("net idmap get\n"
			   "  Read data from the ID mapping database")
		},
		{
			"set",
			net_idmap_set,
			NET_TRANSPORT_LOCAL,
			N_("Write data to the ID mapping database"),
			N_("net idmap set\n"
			   "  Write data to the ID mapping database")
		},
		{
			"delete",
			net_idmap_delete,
			NET_TRANSPORT_LOCAL,
			N_("Delete entries from the ID mapping database"),
			N_("net idmap delete\n"
			   "  Delete entries from the ID mapping database")
		},
		{
			"secret",
			net_idmap_secret,
			NET_TRANSPORT_LOCAL,
			N_("Set secret for specified domain"),
			N_("net idmap secret <DOMAIN> <secret>\n"
			   "  Set secret for specified domain")
		},
		{
			"check",
			net_idmap_check,
			NET_TRANSPORT_LOCAL,
			N_("Check id mappings"),
			N_("net idmap check\n"
			   "  Check id mappings")
		},
		{NULL, NULL, 0, NULL, NULL}
	};

	return net_run_function(c, argc, argv, "net idmap", func);
}