summaryrefslogtreecommitdiff
path: root/source/dsdb/samdb/ldb_modules/schema.c
blob: f2c4d383051dfe48e33743a5fd2958772616d1ff (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
/* 
   ldb database library

   Copyright (C) Simo Sorce  2004-2006

   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/>.
*/

/*
 *  Name: ldb
 *
 *  Component: ldb schema module
 *
 *  Description: add schema check functionality
 *
 *  Author: Simo Sorce
 */

#include "includes.h"
#include "libcli/ldap/ldap.h"
#include "ldb/include/ldb_errors.h"
#include "ldb/include/ldb_private.h"
#include "lib/util/dlinklist.h"
#include "schema_syntax.h"

/* Syntax-Table

   see ldap_server/devdocs/AD-syntaxes.txt
*/

enum schema_class_type {
	SCHEMA_CT_88		= 0,
	SCHEMA_CT_STRUCTURAL	= 1,
	SCHEMA_CT_ABSTRACT	= 2,
	SCHEMA_CT_AUXILIARY	= 3
};

struct schema_attribute {
	char *OID;				/* attributeID     */
	char *name;				/* lDAPDisplayName */
	enum schema_internal_syntax syntax;	/* generated from attributeSyntax, oMSyntax, oMObjectClass */
	bool single;				/* isSingleValued  */
	int min;				/* rangeLower      */
	int max;				/* rangeUpper      */
	int systemflag;				/* systemFlag      */
	int searchflag;				/* searchFlag      */
	bool isdefunct;				/* isDefunct       */
};

struct schema_class {
	char *OID;				/* governsID             */
	char *name;				/* lDAPDisplayName       */
	enum schema_class_type type;		/* objectClassCategory   */
	bool systemOnly;			/* systemOnly            */
	bool isdefunct;				/* isDefunct             */
	int systemflag;				/* systemFlag            */
	char *defobjcat;			/* defaultObjectCategory */
	struct schema_class *parent;		/* subClassOf            */
	struct schema_class **sysaux;		/* systemAuxiliaryClass  */
	struct schema_class **aux;		/* auxiliaryClass        */
	struct schema_class **sysposssup;	/* systemPossSuperiors   */
	struct schema_class **posssup;		/* possSuperiors         */
	struct schema_class **possinf;		/* possibleInferiors     */
	struct schema_attribute **sysmust;	/* systemMustContain     */
	struct schema_attribute **must;		/* MustContain           */
	struct schema_attribute **sysmay;	/* systemMayContain      */
	struct schema_attribute **may;		/* MayContain            */
};

/* TODO: ditcontentrules */

struct schema_private_data {
	struct ldb_dn *schema_dn;
	struct schema_attribute **attrs;
	struct schema_store *attrs_store;
	int num_attributes;
	struct schema_class **class;
	struct schema_store *class_store;
	int num_classes;
};

struct schema_class_dlist {
	struct schema_class *class;
	struct schema_class_dlist *prev;
	struct schema_class_dlist *next;
	enum schema_class_type role;
};

struct schema_context {

	enum sc_op { SC_ADD, SC_MOD, SC_DEL, SC_RENAME } op;
	enum sc_step { SC_INIT, SC_ADD_CHECK_PARENT, SC_ADD_TEMP, SC_DEL_CHECK_CHILDREN } step;

	struct schema_private_data *data;

	struct ldb_module *module;
	struct ldb_request *orig_req;
	struct ldb_request *down_req;

	struct ldb_request *parent_req;
	struct ldb_reply *parent_res;

	struct schema_class_dlist *class_list;
	struct schema_class **sup_list;
	struct schema_class **aux_list;
};

/* FIXME: I'd really like to use an hash table here */
struct schema_link {
	const char *name;
	void *object;
};

struct schema_store {
	struct schema_link *store;
	int num_links;
};

static struct schema_store *schema_store_new(TALLOC_CTX *mem_ctx)
{
	struct schema_store *ht;
	
	ht = talloc(mem_ctx, struct schema_store);
	if (!ht) return NULL;

	ht->store = NULL;
	ht->num_links = 0;

	return ht;
}
	
static int schema_store_add(struct schema_store *ht, const char *key, void *object)
{
	ht->store = talloc_realloc(ht, ht->store, struct schema_link, ht->num_links + 1);
	if (!ht->store) return LDB_ERR_OPERATIONS_ERROR;

	ht->store[ht->num_links].name = key;
	ht->store[ht->num_links].object = object;

	ht->num_links++;

	return LDB_SUCCESS;
}

static void *schema_store_find(struct schema_store *ht, const char *key)
{
	int i;

	for (i = 0; i < ht->num_links; i++) {
		if (strcasecmp(ht->store[i].name, key) == 0) {
			return ht->store[i].object;
		}
	}

	return NULL;
}

#define SCHEMA_CHECK_VALUE(mem, val, mod) \
		do { if (mem == val) { \
			ret = LDB_ERR_OPERATIONS_ERROR; \
			ldb_asprintf_errstring(mod->ldb, \
				"schema module: Memory allocation or attribute error on %s", #mem); \
			goto done; } } while(0)

struct schema_class **schema_get_class_list(struct ldb_module *module,
					    struct schema_private_data *data,
					    struct ldb_message_element *el)
{
	struct schema_class **list;
	int i;
	
	list = talloc_array(data, struct schema_class *, el->num_values + 1);
	if (!list) {
		ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of Memory");
		return NULL;
	}
	
	for (i = 0; i < el->num_values; i++) {
		list[i] = (struct schema_class *)schema_store_find(data->class_store,
								  (char *)el->values[i].data);
		if (!list[i]) {
			ldb_debug_set(module->ldb,
					LDB_DEBUG_ERROR,
					"Class %s referenced but not found in schema\n",
					(char *)el->values[i].data);
			return NULL;
		}
	}
	list[i] = NULL;

	return list;
}

struct schema_attribute **schema_get_attrs_list(struct ldb_module *module,
						struct schema_private_data *data,
						struct ldb_message_element *el)
{
	struct schema_attribute **list;
	int i;

	list = talloc_array(data, struct schema_attribute *, el->num_values + 1);
	if (!list) {
		ldb_debug(module->ldb, LDB_DEBUG_ERROR, "Out of Memory");
		return NULL;
	}
	
	for (i = 0; i < el->num_values; i++) {
		list[i] = (struct schema_attribute *)schema_store_find(data->attrs_store,
								      (char *)el->values[i].data);
		if (!list[i]) {
			ldb_debug_set(module->ldb,
					LDB_DEBUG_ERROR,
					"Attriobute %s referenced but not found in schema\n",
					(char *)el->values[i].data);
			return NULL;
		}
	}
	list[i] = NULL;

	return list;
}

static int schema_init_attrs(struct ldb_module *module, struct schema_private_data *data)
{
	static const char *schema_attrs[] = {	"attributeID",
						"lDAPDisplayName",
						"attributeSyntax",
						"oMSyntax",
						"oMObjectClass",
						"isSingleValued",
						"rangeLower",
						"rangeUpper",
						"searchFlag",
						"systemFlag",
						"isDefunct",
						NULL };
	struct ldb_result *res;
	int ret, i;

	ret = ldb_search(module->ldb,
			 data->schema_dn,
			 LDB_SCOPE_SUBTREE,
			 "(objectClass=attributeSchema)",
			 schema_attrs,
			 &res);

	if (ret != LDB_SUCCESS) {
		goto done;
	}

	data->num_attributes = res->count;
	data->attrs = talloc_array(data, struct schema_attribute *, res->count);
	SCHEMA_CHECK_VALUE(data->attrs, NULL, module);

	data->attrs_store = schema_store_new(data);
	SCHEMA_CHECK_VALUE(data->attrs_store, NULL, module);
	
	for (i = 0; i < res->count; i++) {
		const char *tmp_single;
		const char *attr_syntax;
		uint32_t om_syntax;
		const struct ldb_val *om_class;

		data->attrs[i] = talloc(data->attrs, struct schema_attribute);
		SCHEMA_CHECK_VALUE(data->attrs[i], NULL, module);

		data->attrs[i]->OID = talloc_strdup(data->attrs[i],
						ldb_msg_find_attr_as_string(res->msgs[i], "attributeID", NULL));
		SCHEMA_CHECK_VALUE(data->attrs[i]->OID, NULL, module);
		
		data->attrs[i]->name = talloc_strdup(data->attrs[i],
						ldb_msg_find_attr_as_string(res->msgs[i], "lDAPDisplayName", NULL));
		SCHEMA_CHECK_VALUE(data->attrs[i]->name, NULL, module);

		/* once we have both the OID and the attribute name, add the pointer to the store */
		schema_store_add(data->attrs_store, data->attrs[i]->OID, data->attrs[i]);
		schema_store_add(data->attrs_store, data->attrs[i]->name, data->attrs[i]);

		attr_syntax = ldb_msg_find_attr_as_string(res->msgs[i], "attributeSyntax", NULL);
		SCHEMA_CHECK_VALUE(attr_syntax, NULL, module);
		
		om_syntax = ldb_msg_find_attr_as_uint(res->msgs[i], "oMSyntax", 0);
		/* 0 is not a valid oMSyntax */
		SCHEMA_CHECK_VALUE(om_syntax, 0, module);

		om_class = ldb_msg_find_ldb_val(res->msgs[i], "oMObjectClass");

		ret = map_schema_syntax(om_syntax, attr_syntax, om_class, &data->attrs[i]->syntax);
		if (ret != LDB_SUCCESS) {
			ldb_asprintf_errstring(module->ldb,
				"schema module: invalid om syntax value on %s",
				data->attrs[i]->name);
			goto done;
		}
		
		tmp_single = ldb_msg_find_attr_as_string(res->msgs[i], "isSingleValued", NULL);
		SCHEMA_CHECK_VALUE(tmp_single, NULL, module);
		if (strcmp(tmp_single, "TRUE") == 0) {
			data->attrs[i]->single = 1;
		} else {
			data->attrs[i]->single = 0;
		}

		/* the following are optional */
		data->attrs[i]->min = ldb_msg_find_attr_as_int(res->msgs[i], "rangeLower", INT_MIN);
		data->attrs[i]->max = ldb_msg_find_attr_as_int(res->msgs[i], "rangeUpper", INT_MAX);
		data->attrs[i]->systemflag = ldb_msg_find_attr_as_int(res->msgs[i], "systemFlag", 0);
		data->attrs[i]->searchflag = ldb_msg_find_attr_as_int(res->msgs[i], "searchFlag", 0);
		data->attrs[i]->isdefunct = ldb_msg_find_attr_as_bool(res->msgs[i], "isDefunct", false);
	}

done:
	talloc_free(res);
	return ret;
}

static int schema_init_classes(struct ldb_module *module, struct schema_private_data *data)
{
	const char *schema_attrs[] = {	"governsID",
						"lDAPDisplayName",
						"objectClassCategory",
						"defaultObjectCategory",
						"systemOnly",
						"systemFlag",
						"isDefunct",
						"subClassOf",
						"systemAuxiliaryClass",
						"auxiliaryClass",
						"systemPossSuperiors",
						"possSuperiors",
						"possibleInferiors",
						"systemMustContain",
						"MustContain", 
						"systemMayContain",
						"MayContain",
						NULL };
	struct ldb_result *res;
	int ret, i;

	ret = ldb_search(module->ldb,
			 data->schema_dn,
			 LDB_SCOPE_SUBTREE,
			 "(objectClass=classSchema)",
			 schema_attrs,
			 &res);

	if (ret != LDB_SUCCESS) {
		goto done;
	}

	data->num_classes = res->count;
	data->class = talloc_array(data, struct schema_class *, res->count);
	SCHEMA_CHECK_VALUE(data->class, NULL, module);

	data->class_store = schema_store_new(data);
	SCHEMA_CHECK_VALUE(data->class_store, NULL, module);

	for (i = 0; i < res->count; i++) {
		struct ldb_message_element *el;

		data->class[i] = talloc(data->class, struct schema_class);
		SCHEMA_CHECK_VALUE(data->class[i], NULL, module);

		data->class[i]->OID = talloc_strdup(data->class[i],
						ldb_msg_find_attr_as_string(res->msgs[i], "governsID", NULL));
		SCHEMA_CHECK_VALUE(data->class[i]->OID, NULL, module);

		data->class[i]->name = talloc_strdup(data->class[i],
						ldb_msg_find_attr_as_string(res->msgs[i], "lDAPDisplayName", NULL));
		SCHEMA_CHECK_VALUE(data->class[i]->name, NULL, module);

		/* once we have both the OID and the class name, add the pointer to the store */
		schema_store_add(data->class_store, data->class[i]->OID, data->class[i]);
		schema_store_add(data->class_store, data->class[i]->name, data->class[i]);

		data->class[i]->type = ldb_msg_find_attr_as_int(res->msgs[i], "objectClassCategory", -1);
		/* 0 should not be a valid value, but turn out it is so test with -1 */
		SCHEMA_CHECK_VALUE(data->class[i]->type, -1, module);

		data->class[i]->defobjcat = talloc_strdup(data->class[i],
						ldb_msg_find_attr_as_string(res->msgs[i],
									"defaultObjectCategory", NULL));
/*		SCHEMA_CHECK_VALUE(data->class[i]->defobjcat, NULL, module);
*/
		/* the following attributes are all optional */

		data->class[i]->systemOnly = ldb_msg_find_attr_as_bool(res->msgs[i], "systemOnly", false);
		data->class[i]->systemflag = ldb_msg_find_attr_as_int(res->msgs[i], "systemFlag", 0);
		data->class[i]->isdefunct = ldb_msg_find_attr_as_bool(res->msgs[i], "isDefunct", false);

		/* attributes are loaded first, so we can just go an query the attributes repo */
		
		el = ldb_msg_find_element(res->msgs[i], "systemMustContain");
		if (el) {
			data->class[i]->sysmust = schema_get_attrs_list(module, data, el);
			SCHEMA_CHECK_VALUE(data->class[i]->sysmust, NULL, module);
		}

		el = ldb_msg_find_element(res->msgs[i], "MustContain");
		if (el) {
			data->class[i]->must = schema_get_attrs_list(module, data, el);
			SCHEMA_CHECK_VALUE(data->class[i]->must, NULL, module);
		}

		el = ldb_msg_find_element(res->msgs[i], "systemMayContain");
		if (el) {
			data->class[i]->sysmay = schema_get_attrs_list(module, data, el);
			SCHEMA_CHECK_VALUE(data->class[i]->sysmay, NULL, module);
		}

		el = ldb_msg_find_element(res->msgs[i], "MayContain");
		if (el) {
			data->class[i]->may = schema_get_attrs_list(module, data, el);
			SCHEMA_CHECK_VALUE(data->class[i]->may, NULL, module);
		}

	}

	/* subClassOf, systemAuxiliaryClass, auxiliaryClass, systemPossSuperiors
	 * must be filled in a second loop, when all class objects are allocated
	 * or we may not find a class that has not yet been parsed */
	for (i = 0; i < res->count; i++) {
		struct ldb_message_element *el;
		const char *attr;

		/* this is single valued anyway */
		attr = ldb_msg_find_attr_as_string(res->msgs[i], "subClassOf", NULL);
		SCHEMA_CHECK_VALUE(attr, NULL, module);
		data->class[i]->parent = schema_store_find(data->class_store, attr);
		SCHEMA_CHECK_VALUE(data->class[i]->parent, NULL, module);

		/* the following attributes are all optional */

		data->class[i]->sysaux = NULL;
		el = ldb_msg_find_element(res->msgs[i], "systemAuxiliaryClass");
		if (el) {
			data->class[i]->sysaux = schema_get_class_list(module, data, el); 
			SCHEMA_CHECK_VALUE(data->class[i]->sysaux, NULL, module);
		}

		data->class[i]->aux = NULL;
		el = ldb_msg_find_element(res->msgs[i], "auxiliaryClass");
		if (el) {
			data->class[i]->aux = schema_get_class_list(module, data, el); 
			SCHEMA_CHECK_VALUE(data->class[i]->aux, NULL, module);
		}

		data->class[i]->sysposssup = NULL;
		el = ldb_msg_find_element(res->msgs[i], "systemPossSuperiors");
		if (el) {
			data->class[i]->sysposssup = schema_get_class_list(module, data, el); 
			SCHEMA_CHECK_VALUE(data->class[i]->sysposssup, NULL, module);
		}

		data->class[i]->posssup = NULL;
		el = ldb_msg_find_element(res->msgs[i], "possSuperiors");
		if (el) {
			data->class[i]->posssup = schema_get_class_list(module, data, el); 
			SCHEMA_CHECK_VALUE(data->class[i]->posssup, NULL, module);
		}

		data->class[i]->possinf = NULL;
		el = ldb_msg_find_element(res->msgs[i], "possibleInferiors");
		if (el) {
			data->class[i]->possinf = schema_get_class_list(module, data, el); 
			SCHEMA_CHECK_VALUE(data->class[i]->possinf, NULL, module);
		}
	}

done:
	talloc_free(res);
	return ret;
}

static struct ldb_handle *schema_init_handle(struct ldb_request *req, struct ldb_module *module, enum sc_op op)
{
	struct schema_context *sctx;
	struct ldb_handle *h;

	h = talloc_zero(req, struct ldb_handle);
	if (h == NULL) {
		ldb_set_errstring(module->ldb, "Out of Memory");
		return NULL;
	}

	h->module = module;

	sctx = talloc_zero(h, struct schema_context);
	if (sctx == NULL) {
		ldb_set_errstring(module->ldb, "Out of Memory");
		talloc_free(h);
		return NULL;
	}

	h->private_data = (void *)sctx;

	h->state = LDB_ASYNC_INIT;
	h->status = LDB_SUCCESS;

	sctx->op = op;
	sctx->step = SC_INIT;
	sctx->data = module->private_data;
	sctx->module = module;
	sctx->orig_req = req;

	return h;
}

static int schema_add_check_parent(struct ldb_context *ldb, void *context, struct ldb_reply *ares)
{
	struct schema_context *sctx;

	sctx = talloc_get_type(context, struct schema_context);

	/* we are interested only in the single reply (base search) we receive here */
	if (ares->type == LDB_REPLY_ENTRY) {
		if (sctx->parent_res != NULL) {
			ldb_set_errstring(ldb, "Too many results");
			talloc_free(ares);
			return LDB_ERR_OPERATIONS_ERROR;
		}
		sctx->parent_res = talloc_steal(sctx, ares);
	} else {
		talloc_free(ares);
	}

	return LDB_SUCCESS;
}

static int schema_add_build_parent_req(struct schema_context *sctx)
{
	const char * const parent_attrs[] = { "objectClass", NULL };
	int ret;

	sctx->parent_req = talloc_zero(sctx, struct ldb_request);
	if (sctx->parent_req == NULL) {
		ldb_debug(sctx->module->ldb, LDB_DEBUG_ERROR, "Out of Memory!\n");
		return LDB_ERR_OPERATIONS_ERROR;
	}

	sctx->parent_req->operation = LDB_SEARCH;
	sctx->parent_req->op.search.scope = LDB_SCOPE_BASE;
	sctx->parent_req->op.search.base = ldb_dn_get_parent(sctx->parent_req, sctx->orig_req->op.add.message->dn);
	sctx->parent_req->op.search.tree = ldb_parse_tree(sctx->parent_req, "(objectClass=*)");
	sctx->parent_req->op.search.attrs = parent_attrs;
	sctx->parent_req->controls = NULL;
	sctx->parent_req->context = sctx;
	sctx->parent_req->callback = schema_add_check_parent;
	ret = ldb_set_timeout_from_prev_req(sctx->module->ldb, sctx->orig_req, sctx->parent_req);

	return ret;
}

static struct schema_class_dlist *schema_add_get_dlist_entry_with_class(struct schema_class_dlist *list, struct schema_class *class)
{
	struct schema_class_dlist *temp;

	for (temp = list; temp && (temp->class != class); temp = temp->next) /* noop */ ;
	return temp;
}

static int schema_add_class_to_dlist(struct schema_class_dlist *list, struct schema_class *class, enum schema_class_type role)
{
	struct schema_class_dlist *entry;
	struct schema_class_dlist *temp;
	int ret;

	/* see if this class is usable */
	if (class->isdefunct) {
		return LDB_ERR_NO_SUCH_ATTRIBUTE;
	}

	/* see if this class already exist in the class list */
	if (schema_add_get_dlist_entry_with_class(list, class)) {
		return LDB_SUCCESS;
	}

	/* this is a new class go on and add to the list */
	entry = talloc_zero(list, struct schema_class_dlist);
	if (!entry) return LDB_ERR_OPERATIONS_ERROR;
	entry->class = class;
	entry->role = class->type;

	/* If parent is top (list is guaranteed to start always with top) */
	if (class->parent == list->class) {
		/* if the hierarchy role is structural try to add it just after top */
		if (role == SCHEMA_CT_STRUCTURAL) {
			/* but check no other class at after top has a structural role */
			if (list->next && (list->next->role == SCHEMA_CT_STRUCTURAL)) {
				return LDB_ERR_OBJECT_CLASS_VIOLATION;
			}
			DLIST_ADD_AFTER(list, entry, list);
		} else {
			DLIST_ADD_END(list, entry, struct schema_class_dlist *);
		}
		return LDB_SUCCESS;
	}

	/* search if parent has already been added */
	temp = schema_add_get_dlist_entry_with_class(list->next, class->parent);
	if (temp == NULL) {
		ret = schema_add_class_to_dlist(list, class->parent, role);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
		temp = schema_add_get_dlist_entry_with_class(list->next, class->parent);
	}
	if (!temp) { /* parent not found !? */
		return LDB_ERR_OPERATIONS_ERROR;
	}

	DLIST_ADD_AFTER(list, entry, temp);
	if (role == SCHEMA_CT_STRUCTURAL || role == SCHEMA_CT_AUXILIARY) {
		temp = entry;
		do {
			temp->role = role;
			temp = temp->prev;
			/* stop when hierarchy base is met or when base class parent is top */
		} while (temp->class == temp->next->class->parent &&
			 temp->next->class->parent != list->class);

		/* if we have not reached the head of the list
		 * and role is structural */
		if (temp != list && role == SCHEMA_CT_STRUCTURAL) {
			struct schema_class_dlist *hfirst, *hlast;

			/* check if the list second entry is structural */
			if (list->next->role == SCHEMA_CT_STRUCTURAL) {
				/* we have a confilict here */
				return LDB_ERR_OBJECT_CLASS_VIOLATION;
			}
			/* we have to move this hierarchy of classes
			 * so that the base of the structural hierarchy is right after top */
			 
			hfirst = temp->next;
			hlast = entry;
			/* now hfirst - hlast are the boundaries of the structural hierarchy */
			
			/* extract the structural hierachy from the list */
			hfirst->prev->next = hlast->next;
			if (hlast->next) hlast->next->prev = hfirst->prev;
			
			/* insert the structural hierarchy just after top */
			list->next->prev = hlast;
			hlast->next = list->next;
			list->next = hfirst;
			hfirst->prev = list;
		}	
	}

	return LDB_SUCCESS;
}

/* merge source list into dest list and remove duplicates */
static int schema_merge_class_list(TALLOC_CTX *mem_ctx, struct schema_class ***dest, struct schema_class **source)
{
	struct schema_class **list = *dest;
	int i, j, n, f;

	n = 0;	
	if (list) for (n = 0; list[n]; n++) /* noop */ ;
	f = n;

	for (i = 0; source[i]; i++) {
		for (j = 0; j < f; j++) {
			if (list[j] == source[i]) {
				break;
			}
		}
		if (j < f) { /* duplicate found */
			continue;
		}

		list = talloc_realloc(mem_ctx, list, struct schema_class *, n + 2);
		if (!list) {
			return LDB_ERR_OPERATIONS_ERROR;
		}
		list[n] = source[i];
		n++;
		list[n] = NULL;
	}

	*dest = list;

	return LDB_SUCCESS;
}

/* validate and modify the objectclass attribute to sort and add parents */
static int schema_add_build_objectclass_list(struct schema_context *sctx)
{
	struct schema_class_dlist *temp;
	struct ldb_message_element * el;
	struct schema_class *class;
	int ret, i, an;

	/* First of all initialize list, it must start with class top */
	sctx->class_list = talloc_zero(sctx, struct schema_class_dlist);
	if (!sctx->class_list) return LDB_ERR_OPERATIONS_ERROR;

	sctx->class_list->class = schema_store_find(sctx->data->class_store, "top");
	if (!sctx->class_list->class) return LDB_ERR_OPERATIONS_ERROR;

	el = ldb_msg_find_element(sctx->orig_req->op.add.message, "objectClass");
	if (!el) {
		return LDB_ERR_OBJECT_CLASS_VIOLATION;
	}

	for (i = 0; i < el->num_values; i++) {

		class = schema_store_find(sctx->data->class_store, (char *)el->values[i].data);
		if (!class) {
			return LDB_ERR_NO_SUCH_ATTRIBUTE;
		}
		
		ret = schema_add_class_to_dlist(sctx->class_list, class, class->type);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}

	/* now check if there is any class role that is still not STRUCTURAL or AUXILIARY */
	/* build also the auxiliary class list and the possible superiors list */ 
	temp = sctx->class_list->next; /* top is special, skip it */
	an = 0;

	while (temp) {
		if (temp->role == SCHEMA_CT_ABSTRACT || temp->role == SCHEMA_CT_88) {
			return LDB_ERR_OBJECT_CLASS_VIOLATION;
		}
		if (temp->class->sysaux) {
			ret = schema_merge_class_list(sctx, &sctx->aux_list, temp->class->sysaux);
			if (ret != LDB_SUCCESS) {
				return LDB_ERR_OPERATIONS_ERROR;
			}
		}
		if (temp->class->aux) {
			ret = schema_merge_class_list(sctx, &sctx->aux_list, temp->class->aux);
			if (ret != LDB_SUCCESS) {
				return LDB_ERR_OPERATIONS_ERROR;
			}
		}
		if (temp->class->sysposssup) {
			ret = schema_merge_class_list(sctx, &sctx->sup_list, temp->class->sysposssup);
			if (ret != LDB_SUCCESS) {
				return LDB_ERR_OPERATIONS_ERROR;
			}
		}
		if (temp->class->posssup) {
			ret = schema_merge_class_list(sctx, &sctx->sup_list, temp->class->posssup);
			if (ret != LDB_SUCCESS) {
				return LDB_ERR_OPERATIONS_ERROR;
			}
		}
		temp = temp->next;
	}

	/* complete sup_list with material from the aux classes */
	for (i = 0; sctx->aux_list && sctx->aux_list[i]; i++) {
		if (sctx->aux_list[i]->sysposssup) {
			ret = schema_merge_class_list(sctx, &sctx->sup_list, sctx->aux_list[i]->sysposssup);
			if (ret != LDB_SUCCESS) {
				return LDB_ERR_OPERATIONS_ERROR;
			}
		}
		if (sctx->aux_list[i]->posssup) {
			ret = schema_merge_class_list(sctx, &sctx->sup_list, sctx->aux_list[i]->posssup);
			if (ret != LDB_SUCCESS) {
				return LDB_ERR_OPERATIONS_ERROR;
			}
		}
	}

	if (!sctx->sup_list) return LDB_ERR_NAMING_VIOLATION;

	return LDB_SUCCESS;
}

static int schema_add_check_container_constraints(struct schema_context *sctx)
{
	struct schema_class **parent_possinf = NULL;
	struct schema_class **parent_classes;
	struct schema_class_dlist *temp;
	struct ldb_message_element *el;
	int i, j, ret;

	el = ldb_msg_find_element(sctx->parent_res->message, "objectClass");
	if (!el) {
		/* what the .. */
		return LDB_ERR_OPERATIONS_ERROR;
	}

	parent_classes = talloc_array(sctx, struct schema_class *, el->num_values + 1);

	for (i = 0; i < el->num_values; i++) {

		parent_classes[i] = schema_store_find(sctx->data->class_store, (const char *)el->values[i].data);
		if (!parent_classes[i]) { /* should not be possible */
			return LDB_ERR_OPERATIONS_ERROR;
		}

		if (parent_classes[i]->possinf) {
			ret = schema_merge_class_list(sctx, &parent_possinf, parent_classes[i]->possinf);
			if (ret != LDB_SUCCESS) {
				return LDB_ERR_OPERATIONS_ERROR;
			}
		}

		/* check also embedded auxiliary classes possinf */
		for (j = 0; parent_classes[i]->sysaux && parent_classes[i]->sysaux[j]; j++) {
			if (parent_classes[i]->sysaux[j]->possinf) {
				ret = schema_merge_class_list(sctx, &parent_possinf, parent_classes[i]->sysaux[j]->possinf);
				if (ret != LDB_SUCCESS) {
					return LDB_ERR_OPERATIONS_ERROR;
				}
			}
		}
		for (j = 0; parent_classes[i]->aux && parent_classes[i]->aux[j]; j++) {
			if (parent_classes[i]->aux[j]->possinf) {
				ret = schema_merge_class_list(sctx, &parent_possinf, parent_classes[i]->aux[j]->possinf);
				if (ret != LDB_SUCCESS) {
					return LDB_ERR_OPERATIONS_ERROR;
				}
			}
		}
	}

	/* foreach parent objectclass,
	 *   check parent possible inferiors match all of the child objectclasses
	 *    and that
	 *   poss Superiors of the child objectclasses mathes one of the parent classes
	 */

	temp = sctx->class_list->next; /* skip top it is special */
	while (temp) {

		for (i = 0; parent_possinf[i]; i++) {
			if (temp->class == parent_possinf[i]) {
				break;
			}
		}
		if (parent_possinf[i] == NULL) {
			/* class not found in possible inferiors */
			return LDB_ERR_NAMING_VIOLATION;
		}

		temp = temp->next;
	}

	for (i = 0; parent_classes[i]; i++) {
		for (j = 0; sctx->sup_list[j]; j++) {
			if (sctx->sup_list[j] == parent_classes[i]) {
				break;
			}
		}
		if (sctx->sup_list[j]) { /* possible Superiors match one of the parent classes */
			return LDB_SUCCESS;
		}
	}

	/* no parent classes matched superiors */
	return LDB_ERR_NAMING_VIOLATION;
}

static int schema_add_build_down_req(struct schema_context *sctx)
{
	struct schema_class_dlist *temp;
	struct ldb_message *msg;
	int ret;

	sctx->down_req = talloc(sctx, struct ldb_request);
	if (!sctx->down_req) {
		ldb_set_errstring(sctx->module->ldb, "Out of memory!");
		return LDB_ERR_OPERATIONS_ERROR;
	}

	*(sctx->down_req) = *(sctx->orig_req); /* copy the request */
	msg = ldb_msg_copy_shallow(sctx->down_req, sctx->orig_req->op.add.message);
	if (!msg) {
		ldb_set_errstring(sctx->module->ldb, "Out of memory!");
		return LDB_ERR_OPERATIONS_ERROR;
	}

	/* rebuild the objectclass list */
	ldb_msg_remove_attr(msg, "objectClass");
	ret = ldb_msg_add_empty(msg, "objectClass", 0, NULL);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	/* Add the complete list of classes back to the message */
	for (temp = sctx->class_list; temp; temp = temp->next) {
		ret = ldb_msg_add_string(msg, "objectClass", temp->class->name);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}

	/* objectCategory can be set only by the system */
	if (ldb_msg_find_element(msg, "objectCategory")) {
		return LDB_ERR_CONSTRAINT_VIOLATION;
	}

	/* the OC is mandatory, every class defines it */
	/* use the one defined in the structural class that defines the object */
	for (temp = sctx->class_list->next; temp; temp = temp->next) {
		if (!temp->next) break;
		if (temp->next->role != SCHEMA_CT_STRUCTURAL) break;
	}
/*	oc = talloc_strdup(msg, temp->class->defobjcat);
	ret = ldb_msg_add_string(msg, "objectCategory", oc);
*/
	sctx->down_req->op.add.message = msg;

	return LDB_SUCCESS;
}

static int schema_check_attributes_syntax(struct schema_context *sctx)
{
	struct ldb_message *msg;
	struct schema_attribute *attr;
	int i, ret;

	msg = sctx->orig_req->op.add.message;
	for (i = 0; i < msg->num_elements; i++) {
		attr = schema_store_find(sctx->data->attrs_store, msg->elements[i].name);
		if (attr == NULL) {
			return LDB_ERR_NO_SUCH_ATTRIBUTE;
		}
		ret = schema_validate(sctx->module->ldb, &msg->elements[i], attr->syntax, attr->single, attr->min, attr->max);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}

	return LDB_SUCCESS;
}

static int schema_add_continue(struct ldb_handle *h)
{
	struct schema_context *sctx;
	int ret;

	sctx = talloc_get_type(h->private_data, struct schema_context);

	switch (sctx->step) {
	case SC_INIT:

		/* First of all check that a parent exists for this entry */
		ret = schema_add_build_parent_req(sctx);
		if (ret != LDB_SUCCESS) {
			break;
		}

		sctx->step = SC_ADD_CHECK_PARENT;
		return ldb_next_request(sctx->module, sctx->parent_req);

	case SC_ADD_CHECK_PARENT:

		/* parent search done, check result and go on */
		if (sctx->parent_res == NULL) {
			/* we must have a parent */
			ret = LDB_ERR_NO_SUCH_OBJECT;
			break;
		}

		/* Check objectclasses are ok */
		ret = schema_add_build_objectclass_list(sctx);
	       	if (ret != LDB_SUCCESS) {
			break;
		}

		/* check the parent is of the right type for this object */
		ret = schema_add_check_container_constraints(sctx);
	       	if (ret != LDB_SUCCESS) {
			break;
		}

		/* check attributes syntax */
		
		ret = schema_check_attributes_syntax(sctx);
		if (ret != LDB_SUCCESS) {
			break;
		}

		ret = schema_add_build_down_req(sctx);
		if (ret != LDB_SUCCESS) {
			break;
		}
		sctx->step = SC_ADD_TEMP;

		return ldb_next_request(sctx->module, sctx->down_req);

	default:
		ret = LDB_ERR_OPERATIONS_ERROR;
		break;
	}

	/* this is reached only in case of error */
	/* FIXME: fire an async reply ? */
	h->status = ret;
	h->state = LDB_ASYNC_DONE;
	return ret;
}

static int schema_add(struct ldb_module *module, struct ldb_request *req)
{
	struct schema_context *sctx;
	struct ldb_handle *h;

	if (ldb_dn_is_special(req->op.add.message->dn)) { /* do not manipulate our control entries */
		return ldb_next_request(module, req);
	}

	h = schema_init_handle(req, module, SC_ADD);
	if (!h) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	sctx = talloc_get_type(h->private_data, struct schema_context);
	sctx->orig_req->handle = h;
	return schema_add_continue(h);
}


static int schema_modify(struct ldb_module *module, struct ldb_request *req)
{
	if (ldb_dn_is_special(req->op.mod.message->dn)) { /* do not manipulate our control entries */
		return ldb_next_request(module, req);
	}

	return ldb_next_request(module, req);	
}

static int schema_delete(struct ldb_module *module, struct ldb_request *req)
{
	if (ldb_dn_is_special(req->op.del.dn)) { /* do not manipulate our control entries */
		return ldb_next_request(module, req);
	}
	
	/* First of all check no children exists for this entry */

	return ldb_next_request(module, req);
}

static int schema_rename(struct ldb_module *module, struct ldb_request *req)
{
	if (ldb_dn_is_special(req->op.rename.olddn) &&
	    ldb_dn_is_special(req->op.rename.newdn)) { /* do not manipulate our control entries */
		return ldb_next_request(module, req);
	}

	return ldb_next_request(module, req);
}

static int schema_wait_loop(struct ldb_handle *handle) {
	struct schema_context *sctx;
	int ret;
    
	if (!handle || !handle->private_data) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	if (handle->state == LDB_ASYNC_DONE) {
		return handle->status;
	}

	handle->state = LDB_ASYNC_PENDING;
	handle->status = LDB_SUCCESS;

	sctx = talloc_get_type(handle->private_data, struct schema_context);

	switch (sctx->step) {
	case SC_ADD_CHECK_PARENT:
		ret = ldb_wait(sctx->parent_req->handle, LDB_WAIT_NONE);

		if (ret != LDB_SUCCESS) {
			handle->status = ret;
			goto done;
		}
		if (sctx->parent_req->handle->status != LDB_SUCCESS) {
			handle->status = sctx->parent_req->handle->status;
			goto done;
		}

		if (sctx->parent_req->handle->state != LDB_ASYNC_DONE) {
			return LDB_SUCCESS;
		}

		return schema_add_continue(handle);

	case SC_ADD_TEMP:
		ret = ldb_wait(sctx->down_req->handle, LDB_WAIT_NONE);

		if (ret != LDB_SUCCESS) {
			handle->status = ret;
			goto done;
		}
		if (sctx->down_req->handle->status != LDB_SUCCESS) {
			handle->status = sctx->down_req->handle->status;
			goto done;
		}

		if (sctx->down_req->handle->state != LDB_ASYNC_DONE) {
			return LDB_SUCCESS;
		}

		break;

	default:
		ret = LDB_ERR_OPERATIONS_ERROR;
		goto done;
	}

	ret = LDB_SUCCESS;

done:
	handle->state = LDB_ASYNC_DONE;
	return ret;
}

static int schema_wait_all(struct ldb_handle *handle) {

	int ret;

	while (handle->state != LDB_ASYNC_DONE) {
		ret = schema_wait_loop(handle);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}

	return handle->status;
}

static int schema_wait(struct ldb_handle *handle, enum ldb_wait_type type)
{
	if (type == LDB_WAIT_ALL) {
		return schema_wait_all(handle);
	} else {
		return schema_wait_loop(handle);
	}
}

static int schema_init(struct ldb_module *module)
{
	static const char *schema_attrs[] = { "schemaNamingContext", NULL };
	struct schema_private_data *data;
	struct ldb_result *res;
	int ret;

	/* need to let the partition module to register first */
	ret = ldb_next_init(module);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	data = ldb_get_opaque(module->ldb, "schema_instance");
	if (data) {
		module->private_data = data;
		return LDB_SUCCESS;
	}

	data = talloc_zero(module->ldb, struct schema_private_data);
	if (data == NULL) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	/* find the schema partition */
	ret = ldb_search(module->ldb,
			 ldb_dn_new(module, module->ldb, NULL),
			 LDB_SCOPE_BASE,
			 "(objectClass=*)",
			 schema_attrs,
			 &res);

	if (res->count != 1) {
		/* FIXME: return a clear error string */
		talloc_free(data);
		talloc_free(res);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	data->schema_dn = ldb_msg_find_attr_as_dn(module->ldb, data, res->msgs[0], "schemaNamingContext");
	if (data->schema_dn == NULL) {
		/* FIXME: return a clear error string */
		talloc_free(data);
		talloc_free(res);
		return LDB_ERR_OPERATIONS_ERROR;
	}

	talloc_free(res);

	ret = schema_init_attrs(module, data);
	if (ret != LDB_SUCCESS) {
		talloc_free(data);
		return ret;
	}

	ret = schema_init_classes(module, data);
	if (ret != LDB_SUCCESS) {
		talloc_free(data);
		return ret;
	}

	module->private_data = data;
	ldb_set_opaque(module->ldb, "schema_instance", data);

	return LDB_SUCCESS;
}

_PUBLIC_ const struct ldb_module_ops ldb_schema_module_ops = {
	.name          = "schema",
	.init_context  = schema_init,
	.add           = schema_add,
	.modify        = schema_modify,
	.del           = schema_delete,
	.rename        = schema_rename,
	.wait          = schema_wait
};