summaryrefslogtreecommitdiff
path: root/source4/dsdb/samdb/ldb_modules/objectclass.c
blob: 89dd6efd8a0c79cb8d519078aea62177aca57f02 (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
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
/* 
   ldb database library

   Copyright (C) Simo Sorce  2006-2008
   Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005-2009
   Copyright (C) Matthias Dieter Wallnöfer 2010-2011

   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: objectClass sorting and constraint checking module
 *
 *  Description: 
 *  - sort the objectClass attribute into the class
 *    hierarchy and perform constraint checks (correct RDN name,
 *    valid parent),
 *  - fix DNs into 'standard' case
 *  - Add objectCategory and some other attribute defaults
 *
 *  Author: Andrew Bartlett
 */


#include "includes.h"
#include "ldb_module.h"
#include "util/dlinklist.h"
#include "dsdb/samdb/samdb.h"
#include "librpc/ndr/libndr.h"
#include "librpc/gen_ndr/ndr_security.h"
#include "libcli/security/security.h"
#include "auth/auth.h"
#include "param/param.h"
#include "../libds/common/flags.h"
#include "dsdb/samdb/ldb_modules/schema.h"
#include "dsdb/samdb/ldb_modules/util.h"

struct oc_context {

	struct ldb_module *module;
	struct ldb_request *req;
	const struct dsdb_schema *schema;

	struct ldb_reply *search_res;
	struct ldb_reply *search_res2;

	int (*step_fn)(struct oc_context *);
};

struct class_list {
	struct class_list *prev, *next;
	const struct dsdb_class *objectclass;
};

static struct oc_context *oc_init_context(struct ldb_module *module,
					  struct ldb_request *req)
{
	struct ldb_context *ldb;
	struct oc_context *ac;

	ldb = ldb_module_get_ctx(module);

	ac = talloc_zero(req, struct oc_context);
	if (ac == NULL) {
		ldb_oom(ldb);
		return NULL;
	}

	ac->module = module;
	ac->req = req;
	ac->schema = dsdb_get_schema(ldb, ac);

	return ac;
}

static int objectclass_do_add(struct oc_context *ac);

/* Sort objectClasses into correct order, and validate that all
 * objectClasses specified actually exist in the schema
 */

static int objectclass_sort(struct ldb_module *module,
			    const struct dsdb_schema *schema,
			    TALLOC_CTX *mem_ctx,
			    struct ldb_message_element *objectclass_element,
			    struct class_list **sorted_out) 
{
	struct ldb_context *ldb;
	unsigned int i, lowest;
	struct class_list *unsorted = NULL, *sorted = NULL, *current = NULL, *poss_parent = NULL, *new_parent = NULL, *current_lowest = NULL;

	ldb = ldb_module_get_ctx(module);

	/* DESIGN:
	 *
	 * We work on 4 different 'bins' (implemented here as linked lists):
	 *
	 * * sorted:       the eventual list, in the order we wish to push
	 *                 into the database.  This is the only ordered list.
	 *
	 * * parent_class: The current parent class 'bin' we are
	 *                 trying to find subclasses for
	 *
	 * * subclass:     The subclasses we have found so far
	 *
	 * * unsorted:     The remaining objectClasses
	 *
	 * The process is a matter of filtering objectClasses up from
	 * unsorted into sorted.  Order is irrelevent in the later 3 'bins'.
	 * 
	 * We start with 'top' (found and promoted to parent_class
	 * initially).  Then we find (in unsorted) all the direct
	 * subclasses of 'top'.  parent_classes is concatenated onto
	 * the end of 'sorted', and subclass becomes the list in
	 * parent_class.
	 *
	 * We then repeat, until we find no more subclasses.  Any left
	 * over classes are added to the end.
	 *
	 */

	/* Firstly, dump all the objectClass elements into the
	 * unsorted bin, except for 'top', which is special */
	for (i=0; i < objectclass_element->num_values; i++) {
		current = talloc(mem_ctx, struct class_list);
		if (!current) {
			return ldb_oom(ldb);
		}
		current->objectclass = dsdb_class_by_lDAPDisplayName_ldb_val(schema, &objectclass_element->values[i]);
		if (!current->objectclass) {
			ldb_asprintf_errstring(ldb, "objectclass %.*s is not a valid objectClass in schema", 
					       (int)objectclass_element->values[i].length, (const char *)objectclass_element->values[i].data);
			/* This looks weird, but windows apparently returns this for invalid objectClass values */
			return LDB_ERR_NO_SUCH_ATTRIBUTE;
		} else if (current->objectclass->isDefunct) {
			ldb_asprintf_errstring(ldb, "objectclass %.*s marked as isDefunct objectClass in schema - not valid for new objects", 
					       (int)objectclass_element->values[i].length, (const char *)objectclass_element->values[i].data);
			/* This looks weird, but windows apparently returns this for invalid objectClass values */
			return LDB_ERR_NO_SUCH_ATTRIBUTE;
		}

		/* Don't add top to list, we will do that later */
		if (ldb_attr_cmp("top", current->objectclass->lDAPDisplayName) != 0) {
			DLIST_ADD_END(unsorted, current, struct class_list *);
		}
	}

	/* Add top here, to prevent duplicates */
	current = talloc(mem_ctx, struct class_list);
	current->objectclass = dsdb_class_by_lDAPDisplayName(schema, "top");
	DLIST_ADD_END(sorted, current, struct class_list *);


	/* For each object:  find parent chain */
	for (current = unsorted; schema && current; current = current->next) {
		for (poss_parent = unsorted; poss_parent; poss_parent = poss_parent->next) {
			if (ldb_attr_cmp(poss_parent->objectclass->lDAPDisplayName, current->objectclass->subClassOf) == 0) {
				break;
			}
		}
		/* If we didn't get to the end of the list, we need to add this parent */
		if (poss_parent || (ldb_attr_cmp("top", current->objectclass->subClassOf) == 0)) {
			continue;
		}

		new_parent = talloc(mem_ctx, struct class_list);
		new_parent->objectclass = dsdb_class_by_lDAPDisplayName(schema, current->objectclass->subClassOf);
		DLIST_ADD_END(unsorted, new_parent, struct class_list *);
	}

	do
	{
		lowest = UINT_MAX;
		current_lowest = NULL;
		for (current = unsorted; schema && current; current = current->next) {
			if(current->objectclass->subClass_order < lowest) {
				current_lowest = current;
				lowest = current->objectclass->subClass_order;
			}
		}

		if(current_lowest != NULL) {
			DLIST_REMOVE(unsorted,current_lowest);
			DLIST_ADD_END(sorted,current_lowest, struct class_list *);
		}
	} while(unsorted);


	if (!unsorted) {
		*sorted_out = sorted;
		return LDB_SUCCESS;
	}

	if (!schema) {
		/* If we don't have schema yet, then just merge the lists again */
		DLIST_CONCATENATE(sorted, unsorted, struct class_list *);
		*sorted_out = sorted;
		return LDB_SUCCESS;
	}

	/* This shouldn't happen, and would break MMC, perhaps there
	 * was no 'top', a conflict in the objectClasses or some other
	 * schema error?
	 */
	ldb_asprintf_errstring(ldb, "objectclass %s is not a valid objectClass in objectClass chain", unsorted->objectclass->lDAPDisplayName);
	return LDB_ERR_OBJECT_CLASS_VIOLATION;
}

/*
 * This checks if we have unrelated object classes in our entry's "objectClass"
 * attribute. That means "unsatisfied" abstract classes (no concrete subclass)
 * or two or more disjunct structural ones.
 * If one of these conditions are true, blame.
 */
static int check_unrelated_objectclasses(struct ldb_module *module,
					const struct dsdb_schema *schema,
					const struct dsdb_class *struct_objectclass,
					struct ldb_message_element *objectclass_element)
{
	struct ldb_context *ldb = ldb_module_get_ctx(module);
	unsigned int i;
	bool found;

	if (schema == NULL) {
		return LDB_SUCCESS;
	}

	for (i = 0; i < objectclass_element->num_values; i++) {
		const struct dsdb_class *tmp_class = dsdb_class_by_lDAPDisplayName_ldb_val(schema,
											   &objectclass_element->values[i]);
		const struct dsdb_class *tmp_class2 = struct_objectclass;

		/* Pointer comparison can be used due to the same schema str. */
		if (tmp_class == NULL ||
		    tmp_class == struct_objectclass ||
		    tmp_class->objectClassCategory > 2 ||
		    ldb_attr_cmp(tmp_class->lDAPDisplayName, "top") == 0) {
			continue;
		}

		found = false;
		while (!found &&
		       ldb_attr_cmp(tmp_class2->lDAPDisplayName, "top") != 0) {
			tmp_class2 = dsdb_class_by_lDAPDisplayName(schema,
								   tmp_class2->subClassOf);
			if (tmp_class2 == tmp_class) {
				found = true;
			}
		}
		if (found) {
			continue;
		}

		ldb_asprintf_errstring(ldb,
				       "objectclass: the objectclass '%s' seems to be unrelated to the entry!",
				       tmp_class->lDAPDisplayName);
		return LDB_ERR_OBJECT_CLASS_VIOLATION;
	}

	return LDB_SUCCESS;
}

static int get_search_callback(struct ldb_request *req, struct ldb_reply *ares)
{
	struct ldb_context *ldb;
	struct oc_context *ac;
	int ret;

	ac = talloc_get_type(req->context, struct oc_context);
	ldb = ldb_module_get_ctx(ac->module);

	if (!ares) {
		return ldb_module_done(ac->req, NULL, NULL,
					LDB_ERR_OPERATIONS_ERROR);
	}
	if (ares->error != LDB_SUCCESS &&
	    ares->error != LDB_ERR_NO_SUCH_OBJECT) {
		return ldb_module_done(ac->req, ares->controls,
					ares->response, ares->error);
	}

	ldb_reset_err_string(ldb);

	switch (ares->type) {
	case LDB_REPLY_ENTRY:
		if (ac->search_res != NULL) {
			ldb_set_errstring(ldb, "Too many results");
			talloc_free(ares);
			return ldb_module_done(ac->req, NULL, NULL,
						LDB_ERR_OPERATIONS_ERROR);
		}

		ac->search_res = talloc_steal(ac, ares);
		break;

	case LDB_REPLY_REFERRAL:
		/* ignore */
		talloc_free(ares);
		break;

	case LDB_REPLY_DONE:
		talloc_free(ares);
		ret = ac->step_fn(ac);
		if (ret != LDB_SUCCESS) {
			return ldb_module_done(ac->req, NULL, NULL, ret);
		}
		break;
	}

	return LDB_SUCCESS;
}

static int oc_op_callback(struct ldb_request *req, struct ldb_reply *ares)
{
	struct oc_context *ac;

	ac = talloc_get_type(req->context, struct oc_context);

	if (!ares) {
		return ldb_module_done(ac->req, NULL, NULL,
					LDB_ERR_OPERATIONS_ERROR);
	}

	if (ares->type == LDB_REPLY_REFERRAL) {
		return ldb_module_send_referral(ac->req, ares->referral);
	}

	if (ares->error != LDB_SUCCESS) {
		return ldb_module_done(ac->req, ares->controls,
					ares->response, ares->error);
	}

	if (ares->type != LDB_REPLY_DONE) {
		talloc_free(ares);
		return ldb_module_done(ac->req, NULL, NULL,
					LDB_ERR_OPERATIONS_ERROR);
	}

	return ldb_module_done(ac->req, ares->controls,
				ares->response, ares->error);
}

/* Fix up the DN to be in the standard form, taking particular care to match the parent DN

   This should mean that if the parent is:
    CN=Users,DC=samba,DC=example,DC=com
   and a proposed child is
    cn=Admins ,cn=USERS,dc=Samba,dc=example,dc=COM

   The resulting DN should be:

    CN=Admins,CN=Users,DC=samba,DC=example,DC=com
   
 */
static int fix_dn(struct ldb_context *ldb,
		  TALLOC_CTX *mem_ctx,
		  struct ldb_dn *newdn, struct ldb_dn *parent_dn, 
		  struct ldb_dn **fixed_dn) 
{
	char *upper_rdn_attr;
	const struct ldb_val *rdn_val;

	/* Fix up the DN to be in the standard form, taking particular care to
	 * match the parent DN */
	*fixed_dn = ldb_dn_copy(mem_ctx, parent_dn);
	if (*fixed_dn == NULL) {
		return ldb_oom(ldb);
	}

	/* We need the attribute name in upper case */
	upper_rdn_attr = strupper_talloc(*fixed_dn, 
					 ldb_dn_get_rdn_name(newdn));
	if (upper_rdn_attr == NULL) {
		return ldb_oom(ldb);
	}

	/* Create a new child */
	if (ldb_dn_add_child_fmt(*fixed_dn, "X=X") == false) {
		return ldb_operr(ldb);
	}

	rdn_val = ldb_dn_get_rdn_val(newdn);
	if (rdn_val == NULL) {
		return ldb_operr(ldb);
	}

#if 0
	/* the rules for rDN length constraints are more complex than
	this. Until we understand them we need to leave this
	constraint out. Otherwise we break replication, as windows
	does sometimes send us rDNs longer than 64 */
	if (!rdn_val || rdn_val->length > 64) {
		DEBUG(2,(__location__ ": WARNING: rDN longer than 64 limit for '%s'\n", ldb_dn_get_linearized(newdn)));
	}
#endif


	/* And replace it with CN=foo (we need the attribute in upper case) */
	return ldb_dn_set_component(*fixed_dn, 0, upper_rdn_attr, *rdn_val);
}


static int objectclass_do_add(struct oc_context *ac);

static int objectclass_add(struct ldb_module *module, struct ldb_request *req)
{
	struct ldb_context *ldb;
	struct ldb_request *search_req;
	struct oc_context *ac;
	struct ldb_dn *parent_dn;
	const struct ldb_val *val;
	int ret;
	static const char * const parent_attrs[] = { "objectClass", NULL };

	ldb = ldb_module_get_ctx(module);

	ldb_debug(ldb, LDB_DEBUG_TRACE, "objectclass_add\n");

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

	/* An add operation on the basedn without "NC-add" operation isn't
	 * allowed. */
	if (ldb_dn_compare(ldb_get_default_basedn(ldb), req->op.add.message->dn) == 0) {
		unsigned int instanceType;

		instanceType = ldb_msg_find_attr_as_uint(req->op.add.message,
							 "instanceType", 0);
		if (!(instanceType & INSTANCE_TYPE_IS_NC_HEAD)) {
			char *referral_uri;
			/* When we are trying to readd the root basedn then
			 * this is denied, but with an interesting mechanism:
			 * there is generated a referral with the last
			 * component value as hostname. */
			val = ldb_dn_get_component_val(req->op.add.message->dn,
						       ldb_dn_get_comp_num(req->op.add.message->dn) - 1);
			if (val == NULL) {
				return ldb_operr(ldb);
			}
			referral_uri = talloc_asprintf(req, "ldap://%s/%s", val->data,
						       ldb_dn_get_linearized(req->op.add.message->dn));
			if (referral_uri == NULL) {
				return ldb_module_oom(module);
			}

			return ldb_module_send_referral(req, referral_uri);
		}
	}

	ac = oc_init_context(module, req);
	if (ac == NULL) {
		return ldb_operr(ldb);
	}

	/* If there isn't a parent, just go on to the add processing */
	if (ldb_dn_get_comp_num(ac->req->op.add.message->dn) == 1) {
		return objectclass_do_add(ac);
	}

	/* get copy of parent DN */
	parent_dn = ldb_dn_get_parent(ac, ac->req->op.add.message->dn);
	if (parent_dn == NULL) {
		return ldb_operr(ldb);
	}

	ret = ldb_build_search_req(&search_req, ldb,
				   ac, parent_dn, LDB_SCOPE_BASE,
				   "(objectClass=*)", parent_attrs,
				   NULL,
				   ac, get_search_callback,
				   req);
	LDB_REQ_SET_LOCATION(search_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ac->step_fn = objectclass_do_add;

	return ldb_next_request(ac->module, search_req);
}


/*
  check if this is a special RODC nTDSDSA add
 */
static bool check_rodc_ntdsdsa_add(struct oc_context *ac,
				   const struct dsdb_class *objectclass)
{
	struct ldb_control *rodc_control;

	if (ldb_attr_cmp(objectclass->lDAPDisplayName, "nTDSDSA") != 0) {
		return false;
	}
	rodc_control = ldb_request_get_control(ac->req, LDB_CONTROL_RODC_DCPROMO_OID);
	if (!rodc_control) {
		return false;
	}

	rodc_control->critical = false;
	return true;
}

static int objectclass_do_add(struct oc_context *ac)
{
	struct ldb_context *ldb = ldb_module_get_ctx(ac->module);
	struct ldb_request *add_req;
	struct ldb_message_element *objectclass_element, *el;
	struct ldb_message *msg;
	TALLOC_CTX *mem_ctx;
	struct class_list *sorted, *current;
	const char *rdn_name = NULL;
	char *value;
	const struct dsdb_class *objectclass;
	struct ldb_dn *objectcategory;
	int32_t systemFlags = 0;
	unsigned int i, j;
	bool found;
	int ret;

	msg = ldb_msg_copy_shallow(ac, ac->req->op.add.message);
	if (msg == NULL) {
		return ldb_module_oom(ac->module);
	}

	/* Check if we have a valid parent - this check is needed since
	 * we don't get a LDB_ERR_NO_SUCH_OBJECT error. */
	if (ac->search_res == NULL) {
		unsigned int instanceType;

		/* An add operation on partition DNs without "NC-add" operation
		 * isn't allowed. */
		instanceType = ldb_msg_find_attr_as_uint(msg, "instanceType",
							 0);
		if (!(instanceType & INSTANCE_TYPE_IS_NC_HEAD)) {
			ldb_asprintf_errstring(ldb, "objectclass: Cannot add %s, parent does not exist!", 
					       ldb_dn_get_linearized(msg->dn));
			return LDB_ERR_NO_SUCH_OBJECT;
		}

		/* Don't keep any error messages - we've to add a partition */
		ldb_set_errstring(ldb, NULL);
	} else {
		/* Fix up the DN to be in the standard form, taking
		 * particular care to match the parent DN */
		ret = fix_dn(ldb, msg,
			     ac->req->op.add.message->dn,
			     ac->search_res->message->dn,
			     &msg->dn);
		if (ret != LDB_SUCCESS) {
			ldb_asprintf_errstring(ldb, "objectclass: Could not munge DN %s into normal form",
					       ldb_dn_get_linearized(ac->req->op.add.message->dn));
			return ret;
		}
	}

	if (ac->schema != NULL) {
		objectclass_element = ldb_msg_find_element(msg, "objectClass");
		if (!objectclass_element) {
			ldb_asprintf_errstring(ldb, "objectclass: Cannot add %s, no objectclass specified!",
					       ldb_dn_get_linearized(msg->dn));
			return LDB_ERR_OBJECT_CLASS_VIOLATION;
		}
		if (objectclass_element->num_values == 0) {
			ldb_asprintf_errstring(ldb, "objectclass: Cannot add %s, at least one (structural) objectclass has to be specified!",
					       ldb_dn_get_linearized(msg->dn));
			return LDB_ERR_CONSTRAINT_VIOLATION;
		}

		mem_ctx = talloc_new(ac);
		if (mem_ctx == NULL) {
			return ldb_module_oom(ac->module);
		}

		/* Here we do now get the "objectClass" list from the
		 * database. */
		ret = objectclass_sort(ac->module, ac->schema, mem_ctx,
				       objectclass_element, &sorted);
		if (ret != LDB_SUCCESS) {
			talloc_free(mem_ctx);
			return ret;
		}
		
		ldb_msg_remove_element(msg, objectclass_element);

		/* Well, now we shouldn't find any additional "objectClass"
		 * message element (required by the AD specification). */
		objectclass_element = ldb_msg_find_element(msg, "objectClass");
		if (objectclass_element != NULL) {
			ldb_asprintf_errstring(ldb, "objectclass: Cannot add %s, only one 'objectclass' attribute specification is allowed!",
					       ldb_dn_get_linearized(msg->dn));
			talloc_free(mem_ctx);
			return LDB_ERR_OBJECT_CLASS_VIOLATION;
		}

		/* We must completely replace the existing objectClass entry,
		 * because we need it sorted. */
		ret = ldb_msg_add_empty(msg, "objectClass", 0,
					&objectclass_element);
		if (ret != LDB_SUCCESS) {
			talloc_free(mem_ctx);
			return ret;
		}

		/* Move from the linked list back into an ldb msg */
		for (current = sorted; current; current = current->next) {
			const char *objectclass_name = current->objectclass->lDAPDisplayName;

			ret = ldb_msg_add_string(msg, "objectClass", objectclass_name);
			if (ret != LDB_SUCCESS) {
				ldb_set_errstring(ldb,
						  "objectclass: could not re-add sorted "
						  "objectclass to modify msg");
				talloc_free(mem_ctx);
				return ret;
			}
		}

		talloc_free(mem_ctx);

		/* Make sure its valid to add an object of this type */
		objectclass = get_last_structural_class(ac->schema,
							objectclass_element, ac->req);
		if(objectclass == NULL) {
			ldb_asprintf_errstring(ldb,
					       "Failed to find a structural class for %s",
					       ldb_dn_get_linearized(msg->dn));
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}

		ret = check_unrelated_objectclasses(ac->module, ac->schema,
						    objectclass,
						    objectclass_element);
		if (ret != LDB_SUCCESS) {
			return ret;
		}

		rdn_name = ldb_dn_get_rdn_name(msg->dn);
		if (rdn_name == NULL) {
			return ldb_operr(ldb);
		}
		found = false;
		for (i = 0; (!found) && (i < objectclass_element->num_values);
		     i++) {
			const struct dsdb_class *tmp_class =
				dsdb_class_by_lDAPDisplayName_ldb_val(ac->schema,
								      &objectclass_element->values[i]);

			if (tmp_class == NULL) continue;

			if (ldb_attr_cmp(rdn_name, tmp_class->rDNAttID) == 0)
				found = true;
		}
		if (!found) {
			ldb_asprintf_errstring(ldb,
					       "objectclass: Invalid RDN '%s' for objectclass '%s'!",
					       rdn_name, objectclass->lDAPDisplayName);
			return LDB_ERR_NAMING_VIOLATION;
		}

		if (objectclass->systemOnly &&
		    !ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID) &&
		    !check_rodc_ntdsdsa_add(ac, objectclass)) {
			ldb_asprintf_errstring(ldb,
					       "objectclass: object class '%s' is system-only, rejecting creation of '%s'!",
					       objectclass->lDAPDisplayName,
					       ldb_dn_get_linearized(msg->dn));
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}

		if (ac->search_res && ac->search_res->message) {
			struct ldb_message_element *oc_el
				= ldb_msg_find_element(ac->search_res->message, "objectClass");

			bool allowed_class = false;
			for (i=0; allowed_class == false && oc_el && i < oc_el->num_values; i++) {
				const struct dsdb_class *sclass;

				sclass = dsdb_class_by_lDAPDisplayName_ldb_val(ac->schema,
									       &oc_el->values[i]);
				if (!sclass) {
					/* We don't know this class?  what is going on? */
					continue;
				}
				for (j=0; sclass->systemPossibleInferiors && sclass->systemPossibleInferiors[j]; j++) {
					if (ldb_attr_cmp(objectclass->lDAPDisplayName, sclass->systemPossibleInferiors[j]) == 0) {
						allowed_class = true;
						break;
					}
				}
			}

			if (!allowed_class) {
				ldb_asprintf_errstring(ldb, "structural objectClass %s is not a valid child class for %s",
						objectclass->lDAPDisplayName, ldb_dn_get_linearized(ac->search_res->message->dn));
				return LDB_ERR_NAMING_VIOLATION;
			}
		}

		objectcategory = ldb_msg_find_attr_as_dn(ldb, ac, msg,
							 "objectCategory");
		if (objectcategory == NULL) {
			struct dsdb_extended_dn_store_format *dn_format =
					talloc_get_type(ldb_module_get_private(ac->module),
							struct dsdb_extended_dn_store_format);
			if (dn_format && dn_format->store_extended_dn_in_ldb == false) {
				/* Strip off extended components */
				struct ldb_dn *dn = ldb_dn_new(ac, ldb,
							       objectclass->defaultObjectCategory);
				value = ldb_dn_alloc_linearized(msg, dn);
				talloc_free(dn);
			} else {
				value = talloc_strdup(msg,
						      objectclass->defaultObjectCategory);
			}
			if (value == NULL) {
				return ldb_module_oom(ac->module);
			}

			ret = ldb_msg_add_string(msg, "objectCategory", value);
			if (ret != LDB_SUCCESS) {
				return ret;
			}
		} else {
			const struct dsdb_class *ocClass =
					dsdb_class_by_cn_ldb_val(ac->schema,
								 ldb_dn_get_rdn_val(objectcategory));
			if (ocClass != NULL) {
				struct ldb_dn *dn = ldb_dn_new(ac, ldb,
							       ocClass->defaultObjectCategory);
				if (ldb_dn_compare(objectcategory, dn) != 0) {
					ocClass = NULL;
				}
			}
			talloc_free(objectcategory);
			if (ocClass == NULL) {
				ldb_asprintf_errstring(ldb, "objectclass: Cannot add %s, 'objectCategory' attribute invalid!",
						       ldb_dn_get_linearized(msg->dn));
				return LDB_ERR_OBJECT_CLASS_VIOLATION;
			}
		}

		if (!ldb_msg_find_element(msg, "showInAdvancedViewOnly") && (objectclass->defaultHidingValue == true)) {
			ldb_msg_add_string(msg, "showInAdvancedViewOnly",
						"TRUE");
		}

		/* There are very special rules for systemFlags, see MS-ADTS
		 * MS-ADTS 3.1.1.5.2.4 */

		el = ldb_msg_find_element(msg, "systemFlags");
		if ((el != NULL) && (el->num_values > 1)) {
			ldb_asprintf_errstring(ldb, "objectclass: Cannot add %s, 'systemFlags' attribute multivalued!",
					       ldb_dn_get_linearized(msg->dn));
			return LDB_ERR_CONSTRAINT_VIOLATION;
		}

		systemFlags = ldb_msg_find_attr_as_int(msg, "systemFlags", 0);

		ldb_msg_remove_attr(msg, "systemFlags");

		/* Only the following flags may be set by a client */
		if (ldb_request_get_control(ac->req,
					    LDB_CONTROL_RELAX_OID) == NULL) {
			systemFlags &= ( SYSTEM_FLAG_CONFIG_ALLOW_RENAME
				       | SYSTEM_FLAG_CONFIG_ALLOW_MOVE
				       | SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE
				       | SYSTEM_FLAG_ATTR_IS_RDN );
		}

		/* But the last one ("ATTR_IS_RDN") is only allowed on
		 * "attributeSchema" objects. So truncate if it does not fit. */
		if (ldb_attr_cmp(objectclass->lDAPDisplayName, "attributeSchema") != 0) {
			systemFlags &= ~SYSTEM_FLAG_ATTR_IS_RDN;
		}

		if (ldb_attr_cmp(objectclass->lDAPDisplayName, "server") == 0) {
			systemFlags |= (int32_t)(SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE | SYSTEM_FLAG_CONFIG_ALLOW_RENAME | SYSTEM_FLAG_CONFIG_ALLOW_LIMITED_MOVE);
		} else if (ldb_attr_cmp(objectclass->lDAPDisplayName, "site") == 0
				|| ldb_attr_cmp(objectclass->lDAPDisplayName, "serversContainer") == 0
				|| ldb_attr_cmp(objectclass->lDAPDisplayName, "nTDSDSA") == 0) {
			if (ldb_attr_cmp(objectclass->lDAPDisplayName, "site") == 0)
				systemFlags |= (int32_t)(SYSTEM_FLAG_CONFIG_ALLOW_RENAME);
			systemFlags |= (int32_t)(SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE);
		} else if (ldb_attr_cmp(objectclass->lDAPDisplayName, "siteLink") == 0
				|| ldb_attr_cmp(objectclass->lDAPDisplayName, "subnet") == 0
				|| ldb_attr_cmp(objectclass->lDAPDisplayName, "siteLinkBridge") == 0
				|| ldb_attr_cmp(objectclass->lDAPDisplayName, "nTDSConnection") == 0) {
			systemFlags |= (int32_t)(SYSTEM_FLAG_CONFIG_ALLOW_RENAME);
		}
		/* TODO: If parent object is site or subnet, also add (SYSTEM_FLAG_CONFIG_ALLOW_RENAME) */

		if (el || systemFlags != 0) {
			ret = samdb_msg_add_int(ldb, msg, msg, "systemFlags",
						systemFlags);
			if (ret != LDB_SUCCESS) {
				return ret;
			}
		}

		/* make sure that "isCriticalSystemObject" is not specified! */
		el = ldb_msg_find_element(msg, "isCriticalSystemObject");
		if ((el != NULL) &&
                    !ldb_request_get_control(ac->req, LDB_CONTROL_RELAX_OID)) {
			ldb_set_errstring(ldb,
					  "objectclass: 'isCriticalSystemObject' must not be specified!");
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}
	}

	ret = ldb_build_add_req(&add_req, ldb, ac,
				msg,
				ac->req->controls,
				ac, oc_op_callback,
				ac->req);
	LDB_REQ_SET_LOCATION(add_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	/* perform the add */
	return ldb_next_request(ac->module, add_req);
}

static int oc_modify_callback(struct ldb_request *req,
				struct ldb_reply *ares);
static int objectclass_do_mod(struct oc_context *ac);

static int objectclass_modify(struct ldb_module *module, struct ldb_request *req)
{
	struct ldb_context *ldb = ldb_module_get_ctx(module);
	struct ldb_message_element *objectclass_element;
	struct ldb_message *msg;
	struct ldb_request *down_req;
	struct oc_context *ac;
	bool oc_changes = false;
	int ret;

	ldb_debug(ldb, LDB_DEBUG_TRACE, "objectclass_modify\n");

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

	/* As with the "real" AD we don't accept empty messages */
	if (req->op.mod.message->num_elements == 0) {
		ldb_set_errstring(ldb, "objectclass: modify message must have "
				       "elements/attributes!");
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	ac = oc_init_context(module, req);
	if (ac == NULL) {
		return ldb_operr(ldb);
	}

	/* Without schema, there isn't much to do here */
	if (ac->schema == NULL) {
		talloc_free(ac);
		return ldb_next_request(module, req);
	}

	msg = ldb_msg_copy_shallow(ac, req->op.mod.message);
	if (msg == NULL) {
		return ldb_module_oom(ac->module);
	}

	/* For now change everything except the objectclasses */

	objectclass_element = ldb_msg_find_element(msg, "objectClass");
	if (objectclass_element != NULL) {
		ldb_msg_remove_attr(msg, "objectClass");
		oc_changes = true;
	}

	/* MS-ADTS 3.1.1.5.3.5 - on a forest level < 2003 we do allow updates
	 * only on application NCs - not on the default ones */
	if (oc_changes &&
	    (dsdb_forest_functional_level(ldb) < DS_DOMAIN_FUNCTION_2003)) {
		struct ldb_dn *nc_root;

		ret = dsdb_find_nc_root(ldb, ac, req->op.mod.message->dn,
					&nc_root);
		if (ret != LDB_SUCCESS) {
			return ret;
		}

		if ((ldb_dn_compare(nc_root, ldb_get_default_basedn(ldb)) == 0) ||
		    (ldb_dn_compare(nc_root, ldb_get_config_basedn(ldb)) == 0) ||
		    (ldb_dn_compare(nc_root, ldb_get_schema_basedn(ldb)) == 0)) {
			ldb_set_errstring(ldb,
					  "objectclass: object class changes on objects under the standard name contexts not allowed!");
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}

		talloc_free(nc_root);
	}

	ret = ldb_build_mod_req(&down_req, ldb, ac,
				msg,
				req->controls, ac,
				oc_changes ? oc_modify_callback : oc_op_callback,
				req);
	LDB_REQ_SET_LOCATION(down_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	return ldb_next_request(module, down_req);
}

static int oc_modify_callback(struct ldb_request *req, struct ldb_reply *ares)
{
	static const char * const attrs[] = { "objectClass", NULL };
	struct ldb_context *ldb;
	struct ldb_request *search_req;
	struct oc_context *ac;
	int ret;

	ac = talloc_get_type(req->context, struct oc_context);
	ldb = ldb_module_get_ctx(ac->module);

	if (!ares) {
		return ldb_module_done(ac->req, NULL, NULL,
					LDB_ERR_OPERATIONS_ERROR);
	}

	if (ares->type == LDB_REPLY_REFERRAL) {
		return ldb_module_send_referral(ac->req, ares->referral);
	}

	if (ares->error != LDB_SUCCESS) {
		return ldb_module_done(ac->req, ares->controls,
					ares->response, ares->error);
	}

	if (ares->type != LDB_REPLY_DONE) {
		talloc_free(ares);
		return ldb_module_done(ac->req, NULL, NULL,
					LDB_ERR_OPERATIONS_ERROR);
	}

	talloc_free(ares);

	/* this looks up the real existing object for fetching some important
	 * information (objectclasses) */
	ret = ldb_build_search_req(&search_req, ldb,
				   ac, ac->req->op.mod.message->dn,
				   LDB_SCOPE_BASE,
				   "(objectClass=*)",
				   attrs, NULL, 
				   ac, get_search_callback,
				   ac->req);
	LDB_REQ_SET_LOCATION(search_req);
	if (ret != LDB_SUCCESS) {
		return ldb_module_done(ac->req, NULL, NULL, ret);
	}

	ac->step_fn = objectclass_do_mod;

	ret = ldb_next_request(ac->module, search_req);
	if (ret != LDB_SUCCESS) {
		return ldb_module_done(ac->req, NULL, NULL, ret);
	}

	return LDB_SUCCESS;
}

static int objectclass_do_mod(struct oc_context *ac)
{
	struct ldb_context *ldb;
	struct ldb_request *mod_req;
	struct ldb_message_element *oc_el_entry, *oc_el_change;
	struct ldb_val *vals;
	struct ldb_message *msg;
	TALLOC_CTX *mem_ctx;
	struct class_list *sorted, *current;
	const struct dsdb_class *objectclass;
	unsigned int i, j, k;
	bool found;
	int ret;

	ldb = ldb_module_get_ctx(ac->module);

	/* we should always have a valid entry when we enter here */
	if (ac->search_res == NULL) {
		return ldb_operr(ldb);
	}

	oc_el_entry = ldb_msg_find_element(ac->search_res->message,
					   "objectClass");
	if (oc_el_entry == NULL) {
		/* existing entry without a valid object class? */
		return ldb_operr(ldb);
	}

	/* use a new message structure */
	msg = ldb_msg_new(ac);
	if (msg == NULL) {
		return ldb_module_oom(ac->module);
	}

	msg->dn = ac->req->op.mod.message->dn;

	mem_ctx = talloc_new(ac);
	if (mem_ctx == NULL) {
		return ldb_module_oom(ac->module);
	}

	/* We've to walk over all "objectClass" message elements */
	for (k = 0; k < ac->req->op.mod.message->num_elements; k++) {
		if (ldb_attr_cmp(ac->req->op.mod.message->elements[k].name,
				 "objectClass") != 0) {
			continue;
		}

		oc_el_change = &ac->req->op.mod.message->elements[k];

		switch (oc_el_change->flags & LDB_FLAG_MOD_MASK) {
		case LDB_FLAG_MOD_ADD:
			/* Merge the two message elements */
			for (i = 0; i < oc_el_change->num_values; i++) {
				for (j = 0; j < oc_el_entry->num_values; j++) {
					if (ldb_attr_cmp((char *)oc_el_change->values[i].data,
							 (char *)oc_el_entry->values[j].data) == 0) {
						ldb_asprintf_errstring(ldb,
								       "objectclass: cannot re-add an existing objectclass: '%.*s'!",
								       (int)oc_el_change->values[i].length,
								       (const char *)oc_el_change->values[i].data);
						talloc_free(mem_ctx);
						return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
					}
				}
				/* append the new object class value - code was
				 * copied from "ldb_msg_add_value" */
				vals = talloc_realloc(oc_el_entry, oc_el_entry->values,
						      struct ldb_val,
						      oc_el_entry->num_values + 1);
				if (vals == NULL) {
					talloc_free(mem_ctx);
					return ldb_module_oom(ac->module);
				}
				oc_el_entry->values = vals;
				oc_el_entry->values[oc_el_entry->num_values] =
							oc_el_change->values[i];
				++(oc_el_entry->num_values);
			}

			break;

		case LDB_FLAG_MOD_REPLACE:
			/*
			 * In this case the new "oc_el_entry" is simply
			 * "oc_el_change"
			 */
			oc_el_entry = oc_el_change;

			break;

		case LDB_FLAG_MOD_DELETE:
			/* Merge the two message elements */
			for (i = 0; i < oc_el_change->num_values; i++) {
				found = false;
				for (j = 0; j < oc_el_entry->num_values; j++) {
					if (ldb_attr_cmp((char *)oc_el_change->values[i].data,
							 (char *)oc_el_entry->values[j].data) == 0) {
						found = true;
						/* delete the object class value
						 * - code was copied from
						 * "ldb_msg_remove_element" */
						if (j != oc_el_entry->num_values - 1) {
							memmove(&oc_el_entry->values[j],
								&oc_el_entry->values[j+1],
								((oc_el_entry->num_values-1) - j)*sizeof(struct ldb_val));
						}
						--(oc_el_entry->num_values);
						break;
					}
				}
				if (!found) {
					/* we cannot delete a not existing
					 * object class */
					ldb_asprintf_errstring(ldb,
							       "objectclass: cannot delete this objectclass: '%.*s'!",
							       (int)oc_el_change->values[i].length,
							       (const char *)oc_el_change->values[i].data);
					talloc_free(mem_ctx);
					return LDB_ERR_NO_SUCH_ATTRIBUTE;
				}
			}

			break;
		}

		/* Get the new top-most structural object class */
		objectclass = get_last_structural_class(ac->schema, oc_el_entry,
							ac->req);
		if (objectclass == NULL) {
			ldb_set_errstring(ldb,
					  "objectclass: cannot delete all structural objectclasses!");
			talloc_free(mem_ctx);
			return LDB_ERR_OBJECT_CLASS_VIOLATION;
		}

		ret = check_unrelated_objectclasses(ac->module, ac->schema,
						    objectclass,
						    oc_el_entry);
		if (ret != LDB_SUCCESS) {
			talloc_free(mem_ctx);
			return ret;
		}

		/* Now do the sorting */
		ret = objectclass_sort(ac->module, ac->schema, mem_ctx,
				       oc_el_entry, &sorted);
		if (ret != LDB_SUCCESS) {
			talloc_free(mem_ctx);
			return ret;
		}

		/* (Re)-add an empty "objectClass" attribute on the object
		 * classes change message "msg". */
		ldb_msg_remove_attr(msg, "objectClass");
		ret = ldb_msg_add_empty(msg, "objectClass",
					LDB_FLAG_MOD_REPLACE, &oc_el_entry);
		if (ret != LDB_SUCCESS) {
			talloc_free(mem_ctx);
			return ret;
		}

		/* Move from the linked list back into an ldb msg */
		for (current = sorted; current; current = current->next) {
			const char *objectclass_name = current->objectclass->lDAPDisplayName;

			ret = ldb_msg_add_string(msg, "objectClass",
						 objectclass_name);
			if (ret != LDB_SUCCESS) {
				ldb_set_errstring(ldb,
						  "objectclass: could not re-add sorted objectclasses!");
				talloc_free(mem_ctx);
				return ret;
			}
		}
	}

	talloc_free(mem_ctx);

	/* Now we have the real and definitive change left to do */

	ret = ldb_build_mod_req(&mod_req, ldb, ac,
				msg,
				ac->req->controls,
				ac, oc_op_callback,
				ac->req);
	LDB_REQ_SET_LOCATION(mod_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	return ldb_next_request(ac->module, mod_req);
}

static int objectclass_do_rename(struct oc_context *ac);

static int objectclass_rename(struct ldb_module *module, struct ldb_request *req)
{
	static const char * const attrs[] = { "objectClass", NULL };
	struct ldb_context *ldb;
	struct ldb_request *search_req;
	struct oc_context *ac;
	struct ldb_dn *parent_dn;
	int ret;

	ldb = ldb_module_get_ctx(module);

	ldb_debug(ldb, LDB_DEBUG_TRACE, "objectclass_rename\n");

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

	ac = oc_init_context(module, req);
	if (ac == NULL) {
		return ldb_operr(ldb);
	}

	parent_dn = ldb_dn_get_parent(ac, req->op.rename.newdn);
	if (parent_dn == NULL) {
		ldb_asprintf_errstring(ldb, "objectclass: Cannot rename %s, the parent DN does not exist!",
				       ldb_dn_get_linearized(req->op.rename.olddn));
		return LDB_ERR_NO_SUCH_OBJECT;
	}

	/* this looks up the parent object for fetching some important
	 * information (objectclasses, DN normalisation...) */
	ret = ldb_build_search_req(&search_req, ldb,
				   ac, parent_dn, LDB_SCOPE_BASE,
				   "(objectClass=*)",
				   attrs, NULL,
				   ac, get_search_callback,
				   req);
	LDB_REQ_SET_LOCATION(search_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	/* we have to add the show recycled control, as otherwise DRS
	   deletes will be refused as we will think the target parent
	   does not exist */
	ret = ldb_request_add_control(search_req, LDB_CONTROL_SHOW_RECYCLED_OID,
				      false, NULL);

	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ac->step_fn = objectclass_do_rename;

	return ldb_next_request(ac->module, search_req);
}

static int objectclass_do_rename2(struct oc_context *ac);

static int objectclass_do_rename(struct oc_context *ac)
{
	static const char * const attrs[] = { "objectClass", NULL };
	struct ldb_context *ldb;
	struct ldb_request *search_req;
	int ret;

	ldb = ldb_module_get_ctx(ac->module);

	/* Check if we have a valid parent - this check is needed since
	 * we don't get a LDB_ERR_NO_SUCH_OBJECT error. */
	if (ac->search_res == NULL) {
		ldb_asprintf_errstring(ldb, "objectclass: Cannot rename %s, parent does not exist!",
				       ldb_dn_get_linearized(ac->req->op.rename.olddn));
		return LDB_ERR_OTHER;
	}

	/* now assign "search_res2" to the parent entry to have "search_res"
	 * free for another lookup */
	ac->search_res2 = ac->search_res;
	ac->search_res = NULL;

	/* this looks up the real existing object for fetching some important
	 * information (objectclasses) */
	ret = ldb_build_search_req(&search_req, ldb,
				   ac, ac->req->op.rename.olddn,
				   LDB_SCOPE_BASE,
				   "(objectClass=*)",
				   attrs, NULL,
				   ac, get_search_callback,
				   ac->req);
	LDB_REQ_SET_LOCATION(search_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ac->step_fn = objectclass_do_rename2;

	return ldb_next_request(ac->module, search_req);
}

static int objectclass_do_rename2(struct oc_context *ac)
{
	struct ldb_context *ldb;
	struct ldb_request *rename_req;
	struct ldb_dn *fixed_dn;
	int ret;

	ldb = ldb_module_get_ctx(ac->module);

	/* Check if we have a valid entry - this check is needed since
	 * we don't get a LDB_ERR_NO_SUCH_OBJECT error. */
	if (ac->search_res == NULL) {
		ldb_asprintf_errstring(ldb, "objectclass: Cannot rename %s, entry does not exist!",
				       ldb_dn_get_linearized(ac->req->op.rename.olddn));
		return LDB_ERR_NO_SUCH_OBJECT;
	}

	if (ac->schema != NULL) {
		struct ldb_message_element *oc_el_entry, *oc_el_parent;
		const struct dsdb_class *objectclass;
		const char *rdn_name;
		bool allowed_class = false;
		unsigned int i, j;
		bool found;

		oc_el_entry = ldb_msg_find_element(ac->search_res->message,
						   "objectClass");
		if (oc_el_entry == NULL) {
			/* existing entry without a valid object class? */
			return ldb_operr(ldb);
		}
		objectclass = get_last_structural_class(ac->schema, oc_el_entry, ac->req);
		if (objectclass == NULL) {
			/* existing entry without a valid object class? */
			return ldb_operr(ldb);
		}

		rdn_name = ldb_dn_get_rdn_name(ac->req->op.rename.newdn);
		if (rdn_name == NULL) {
			return ldb_operr(ldb);
		}
		found = false;
		for (i = 0; (!found) && (i < oc_el_entry->num_values); i++) {
			const struct dsdb_class *tmp_class =
				dsdb_class_by_lDAPDisplayName_ldb_val(ac->schema,
								      &oc_el_entry->values[i]);

			if (tmp_class == NULL) continue;

			if (ldb_attr_cmp(rdn_name, tmp_class->rDNAttID) == 0)
				found = true;
		}
		if (!found) {
			ldb_asprintf_errstring(ldb,
					       "objectclass: Invalid RDN '%s' for objectclass '%s'!",
					       rdn_name, objectclass->lDAPDisplayName);
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}

		oc_el_parent = ldb_msg_find_element(ac->search_res2->message,
						    "objectClass");
		if (oc_el_parent == NULL) {
			/* existing entry without a valid object class? */
			return ldb_operr(ldb);
		}

		for (i=0; allowed_class == false && i < oc_el_parent->num_values; i++) {
			const struct dsdb_class *sclass;

			sclass = dsdb_class_by_lDAPDisplayName_ldb_val(ac->schema,
								       &oc_el_parent->values[i]);
			if (!sclass) {
				/* We don't know this class?  what is going on? */
				continue;
			}
			for (j=0; sclass->systemPossibleInferiors && sclass->systemPossibleInferiors[j]; j++) {
				if (ldb_attr_cmp(objectclass->lDAPDisplayName, sclass->systemPossibleInferiors[j]) == 0) {
					allowed_class = true;
					break;
				}
			}
		}

		if (!allowed_class) {
			ldb_asprintf_errstring(ldb,
					       "objectclass: structural objectClass %s is not a valid child class for %s",
					       objectclass->lDAPDisplayName, ldb_dn_get_linearized(ac->search_res2->message->dn));
			return LDB_ERR_NAMING_VIOLATION;
		}
	}

	/* Ensure we are not trying to rename it to be a child of itself */
	if ((ldb_dn_compare_base(ac->req->op.rename.olddn,
				 ac->req->op.rename.newdn) == 0)  &&
	    (ldb_dn_compare(ac->req->op.rename.olddn,
			    ac->req->op.rename.newdn) != 0)) {
		ldb_asprintf_errstring(ldb, "objectclass: Cannot rename %s to be a child of itself",
				       ldb_dn_get_linearized(ac->req->op.rename.olddn));
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/* Fix up the DN to be in the standard form, taking
	 * particular care to match the parent DN */
	ret = fix_dn(ldb, ac,
		     ac->req->op.rename.newdn,
		     ac->search_res2->message->dn,
		     &fixed_dn);
	if (ret != LDB_SUCCESS) {
		ldb_asprintf_errstring(ldb, "objectclass: Could not munge DN %s into normal form",
				       ldb_dn_get_linearized(ac->req->op.rename.newdn));
		return ret;

	}

	ret = ldb_build_rename_req(&rename_req, ldb, ac,
				   ac->req->op.rename.olddn, fixed_dn,
				   ac->req->controls,
				   ac, oc_op_callback,
				   ac->req);
	LDB_REQ_SET_LOCATION(rename_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	/* perform the rename */
	return ldb_next_request(ac->module, rename_req);
}

static int objectclass_do_delete(struct oc_context *ac);

static int objectclass_delete(struct ldb_module *module, struct ldb_request *req)
{
	static const char * const attrs[] = { "nCName", "objectClass",
					      "systemFlags",
					      "isDeleted",
					      "isCriticalSystemObject", NULL };
	struct ldb_context *ldb;
	struct ldb_request *search_req;
	struct oc_context *ac;
	int ret;

	ldb = ldb_module_get_ctx(module);

	ldb_debug(ldb, LDB_DEBUG_TRACE, "objectclass_delete\n");

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

	/* Bypass the constraint checks when we do have the "RELAX" control
	 * set. */
	if (ldb_request_get_control(req, LDB_CONTROL_RELAX_OID) != NULL) {
		return ldb_next_request(module, req);
	}

	ac = oc_init_context(module, req);
	if (ac == NULL) {
		return ldb_operr(ldb);
	}

	/* this looks up the entry object for fetching some important
	 * information (object classes, system flags...) */
	ret = ldb_build_search_req(&search_req, ldb,
				   ac, req->op.del.dn, LDB_SCOPE_BASE,
				   "(objectClass=*)",
				   attrs, req->controls,
				   ac, get_search_callback,
				   req);
	LDB_REQ_SET_LOCATION(search_req);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ac->step_fn = objectclass_do_delete;

	return ldb_next_request(ac->module, search_req);
}

static int objectclass_do_delete(struct oc_context *ac)
{
	struct ldb_context *ldb;
	struct ldb_dn *dn;
	int32_t systemFlags;
	bool isCriticalSystemObject;
	int ret;

	ldb = ldb_module_get_ctx(ac->module);

	/* Check if we have a valid entry - this check is needed since
	 * we don't get a LDB_ERR_NO_SUCH_OBJECT error. */
	if (ac->search_res == NULL) {
		ldb_asprintf_errstring(ldb, "objectclass: Cannot delete %s, entry does not exist!",
				       ldb_dn_get_linearized(ac->req->op.del.dn));
		return LDB_ERR_NO_SUCH_OBJECT;
	}

	/* DC's ntDSDSA object */
	if (ldb_dn_compare(ac->req->op.del.dn, samdb_ntds_settings_dn(ldb)) == 0) {
		ldb_asprintf_errstring(ldb, "objectclass: Cannot delete %s, it's the DC's ntDSDSA object!",
				       ldb_dn_get_linearized(ac->req->op.del.dn));
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/* DC's rIDSet object */
	/* Perform this check only when it does exist - this is needed in order
	 * to don't let existing provisions break. */
	ret = samdb_rid_set_dn(ldb, ac, &dn);
	if ((ret != LDB_SUCCESS) && (ret != LDB_ERR_NO_SUCH_OBJECT)) {
		return ret;
	}
	if (ret == LDB_SUCCESS) {
		if (ldb_dn_compare(ac->req->op.del.dn, dn) == 0) {
			talloc_free(dn);
			ldb_asprintf_errstring(ldb, "objectclass: Cannot delete %s, it's the DC's rIDSet object!",
					       ldb_dn_get_linearized(ac->req->op.del.dn));
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}
		talloc_free(dn);
	}

	/* Only trusted request from system account are allowed to delete
	 * deleted objects.
	 */
	if (ldb_msg_check_string_attribute(ac->search_res->message, "isDeleted", "TRUE") &&
			(ldb_req_is_untrusted(ac->req) ||
				!dsdb_module_am_system(ac->module))) {
		ldb_asprintf_errstring(ldb, "Delete of '%s' failed",
						ldb_dn_get_linearized(ac->req->op.del.dn));
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/* crossRef objects regarding config, schema and default domain NCs */
	if (samdb_find_attribute(ldb, ac->search_res->message, "objectClass",
				 "crossRef") != NULL) {
		dn = ldb_msg_find_attr_as_dn(ldb, ac, ac->search_res->message,
					     "nCName");
		if ((ldb_dn_compare(dn, ldb_get_default_basedn(ldb)) == 0) ||
		    (ldb_dn_compare(dn, ldb_get_config_basedn(ldb)) == 0)) {
			talloc_free(dn);

			ldb_asprintf_errstring(ldb, "objectclass: Cannot delete %s, it's a crossRef object to the main or configuration partition!",
					       ldb_dn_get_linearized(ac->req->op.del.dn));
			return LDB_ERR_NOT_ALLOWED_ON_NON_LEAF;
		}
		if (ldb_dn_compare(dn, ldb_get_schema_basedn(ldb)) == 0) {
			talloc_free(dn);

			ldb_asprintf_errstring(ldb, "objectclass: Cannot delete %s, it's a crossRef object to the schema partition!",
					       ldb_dn_get_linearized(ac->req->op.del.dn));
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}
		talloc_free(dn);
	}

	/* systemFlags */

	systemFlags = ldb_msg_find_attr_as_int(ac->search_res->message,
					       "systemFlags", 0);
	if ((systemFlags & SYSTEM_FLAG_DISALLOW_DELETE) != 0) {
		ldb_asprintf_errstring(ldb, "objectclass: Cannot delete %s, it isn't permitted!",
				       ldb_dn_get_linearized(ac->req->op.del.dn));
		return LDB_ERR_UNWILLING_TO_PERFORM;
	}

	/* isCriticalSystemObject - but this only applies on tree delete
	 * operations - MS-ADTS 3.1.1.5.5.7.2 */
	if (ldb_request_get_control(ac->req, LDB_CONTROL_TREE_DELETE_OID) != NULL) {
		isCriticalSystemObject = ldb_msg_find_attr_as_bool(ac->search_res->message,
								   "isCriticalSystemObject", false);
		if (isCriticalSystemObject) {
			ldb_asprintf_errstring(ldb,
					       "objectclass: Cannot tree-delete %s, it's a critical system object!",
					       ldb_dn_get_linearized(ac->req->op.del.dn));
			return LDB_ERR_UNWILLING_TO_PERFORM;
		}
	}

	return ldb_next_request(ac->module, ac->req);
}

static int objectclass_init(struct ldb_module *module)
{
	struct ldb_context *ldb = ldb_module_get_ctx(module);
	int ret;

	/* Init everything else */
	ret = ldb_next_init(module);
	if (ret != LDB_SUCCESS) {
		return ret;
	}
	
	/* Look for the opaque to indicate we might have to cut down the DN of defaultObjectCategory */
	ldb_module_set_private(module, ldb_get_opaque(ldb, DSDB_EXTENDED_DN_STORE_FORMAT_OPAQUE_NAME));

	ret = ldb_mod_register_control(module, LDB_CONTROL_RODC_DCPROMO_OID);
	if (ret != LDB_SUCCESS) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "objectclass_init: Unable to register control DCPROMO with rootdse\n");
		return ldb_operr(ldb);
	}

	return ret;
}

static const struct ldb_module_ops ldb_objectclass_module_ops = {
	.name		= "objectclass",
	.add		= objectclass_add,
	.modify		= objectclass_modify,
	.rename		= objectclass_rename,
	.del		= objectclass_delete,
	.init_context	= objectclass_init
};

int ldb_objectclass_module_init(const char *version)
{
	LDB_MODULE_CHECK_VERSION(version);
	return ldb_register_module(&ldb_objectclass_module_ops);
}