summaryrefslogtreecommitdiff
path: root/lib/ldb/common/ldb_msg.c
blob: 9cd7998e21ce423e838eb278abd0ff948ff68405 (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
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
/*
   ldb database library

   Copyright (C) Andrew Tridgell  2004

     ** NOTE! The following LGPL license applies to the ldb
     ** library. This does NOT imply that all of Samba is released
     ** under the LGPL

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 3 of the License, or (at your option) any later version.

   This library 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/

/*
 *  Name: ldb
 *
 *  Component: ldb message component utility functions
 *
 *  Description: functions for manipulating ldb_message structures
 *
 *  Author: Andrew Tridgell
 */

#include "ldb_private.h"

/*
  create a new ldb_message in a given memory context (NULL for top level)
*/
struct ldb_message *ldb_msg_new(TALLOC_CTX *mem_ctx)
{
	return talloc_zero(mem_ctx, struct ldb_message);
}

/*
  find an element in a message by attribute name
*/
struct ldb_message_element *ldb_msg_find_element(const struct ldb_message *msg,
						 const char *attr_name)
{
	unsigned int i;
	for (i=0;i<msg->num_elements;i++) {
		if (ldb_attr_cmp(msg->elements[i].name, attr_name) == 0) {
			return &msg->elements[i];
		}
	}
	return NULL;
}

/*
  see if two ldb_val structures contain exactly the same data
  return 1 for a match, 0 for a mis-match
*/
int ldb_val_equal_exact(const struct ldb_val *v1, const struct ldb_val *v2)
{
	if (v1->length != v2->length) return 0;
	if (v1->data == v2->data) return 1;
	if (v1->length == 0) return 1;

	if (memcmp(v1->data, v2->data, v1->length) == 0) {
		return 1;
	}

	return 0;
}

/*
  find a value in an element
  assumes case sensitive comparison
*/
struct ldb_val *ldb_msg_find_val(const struct ldb_message_element *el,
				 struct ldb_val *val)
{
	unsigned int i;
	for (i=0;i<el->num_values;i++) {
		if (ldb_val_equal_exact(val, &el->values[i])) {
			return &el->values[i];
		}
	}
	return NULL;
}


static int ldb_val_cmp(const struct ldb_val *v1, const struct ldb_val *v2)
{
	if (v1->length != v2->length) {
		return v1->length - v2->length;
	}
	return memcmp(v1->data, v2->data, v1->length);
}


/*
  ldb_msg_find_duplicate_val() will set the **duplicate pointer to the first
  duplicate value it finds. It does a case sensitive comparison (memcmp).

  LDB_ERR_OPERATIONS_ERROR indicates an allocation failure or an unknown
  options flag, otherwise LDB_SUCCESS.
*/
#define LDB_DUP_QUADRATIC_THRESHOLD 10

int ldb_msg_find_duplicate_val(struct ldb_context *ldb,
			       TALLOC_CTX *mem_ctx,
			       const struct ldb_message_element *el,
			       struct ldb_val **duplicate,
			       uint32_t options)
{
	unsigned int i, j;
	struct ldb_val *val;

	if (options != 0) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	*duplicate = NULL;

	/*
	   If there are not many values, it is best to avoid the talloc
	   overhead and just do a brute force search.
	 */
	if (el->num_values < LDB_DUP_QUADRATIC_THRESHOLD) {
		for (j = 0; j < el->num_values; j++) {
			val = &el->values[j];
			for ( i = j + 1; i < el->num_values; i++) {
				if (ldb_val_equal_exact(val, &el->values[i])) {
					*duplicate = val;
					return LDB_SUCCESS;
				}
			}
		}
	} else {
		struct ldb_val *values;
		values = talloc_array(mem_ctx, struct ldb_val, el->num_values);
		if (values == NULL) {
			return LDB_ERR_OPERATIONS_ERROR;
		}

		memcpy(values, el->values,
		       el->num_values * sizeof(struct ldb_val));
		TYPESAFE_QSORT(values, el->num_values, ldb_val_cmp);
		for (i = 1; i < el->num_values; i++) {
			if (ldb_val_equal_exact(&values[i],
						&values[i - 1])) {
				/* find the original location */
				for (j = 0; j < el->num_values; j++) {
					if (ldb_val_equal_exact(&values[i],
								&el->values[j])
						) {
						*duplicate = &el->values[j];
						break;
					}
				}
				talloc_free(values);
				if (*duplicate == NULL) {
					/* how we got here, I don't know */
					return LDB_ERR_OPERATIONS_ERROR;
				}
				return LDB_SUCCESS;
			}
		}
		talloc_free(values);
	}
	return LDB_SUCCESS;
}


/*
  Determine whether the values in an element are also in another element.

  Without any flags, return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS if the elements
  share values, or LDB_SUCCESS if they don't. In this case, the function
  simply determines the set intersection and it doesn't matter in which order
  the elements are provided.

  With the LDB_MSG_FIND_COMMON_REMOVE_DUPLICATES flag, any values in common are
  removed from the first element and LDB_SUCCESS is returned.

  LDB_ERR_OPERATIONS_ERROR indicates an allocation failure or an unknown option.
  LDB_ERR_INAPPROPRIATE_MATCHING is returned if the elements differ in name.
*/

int ldb_msg_find_common_values(struct ldb_context *ldb,
			       TALLOC_CTX *mem_ctx,
			       struct ldb_message_element *el,
			       struct ldb_message_element *el2,
			       uint32_t options)
{
	struct ldb_val *values;
	struct ldb_val *values2;
	unsigned int i, j, k, n_values;

	bool remove_duplicates = options & LDB_MSG_FIND_COMMON_REMOVE_DUPLICATES;

	if ((options & ~LDB_MSG_FIND_COMMON_REMOVE_DUPLICATES) != 0) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	if (strcmp(el->name, el2->name) != 0) {
		return LDB_ERR_INAPPROPRIATE_MATCHING;
	}
	if (el->num_values == 0 || el2->num_values == 0) {
		return LDB_SUCCESS;
	}
	/*
	   With few values, it is better to do the brute-force search than the
	   clever search involving tallocs, memcpys, sorts, etc.
	*/
	if (MIN(el->num_values, el2->num_values) == 1 ||
	    MAX(el->num_values, el2->num_values) < LDB_DUP_QUADRATIC_THRESHOLD) {
		for (i = 0; i < el2->num_values; i++) {
			for (j = 0; j < el->num_values; j++) {
				if (ldb_val_equal_exact(&el->values[j],
							&el2->values[i])) {
					if (! remove_duplicates) {
					    return			\
					      LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
					}
					/*
					  With the remove_duplicates flag, we
					  resolve the intersection by removing
					  the offending one from el.
					*/
					el->num_values--;
					for (k = j; k < el->num_values; k++) {
						el->values[k] = \
							el->values[k + 1];
					}
					j--; /* rewind */
				}
			}
		}
		return LDB_SUCCESS;
	}

	values = talloc_array(mem_ctx, struct ldb_val, el->num_values);
	if (values == NULL) {
		return LDB_ERR_OPERATIONS_ERROR;
	}
	values2 = talloc_array(mem_ctx, struct ldb_val,
				    el2->num_values);
	if (values2 == NULL) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	memcpy(values, el->values,
	       el->num_values * sizeof(struct ldb_val));
	memcpy(values2, el2->values,
	       el2->num_values * sizeof(struct ldb_val));
	TYPESAFE_QSORT(values, el->num_values, ldb_val_cmp);
	TYPESAFE_QSORT(values2, el2->num_values, ldb_val_cmp);

	/*
	   el->n_values may diverge from the number of values in the sorted
	   list when the remove_duplicates flag is used.
	*/
	n_values = el->num_values;
	i = 0;
	j = 0;
	while (i != n_values && j < el2->num_values) {
		int ret = ldb_val_cmp(&values[i], &values2[j]);
		if (ret < 0) {
			i++;
		} else if (ret > 0) {
			j++;
		} else {
			/* we have a collision */
			if (! remove_duplicates) {
				TALLOC_FREE(values);
				TALLOC_FREE(values2);
				return LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS;
			}
			/*
			   With the remove_duplicates flag we need to find
			   this in the original list and remove it, which is
			   inefficient but hopefully rare.
			*/
			for (k = 0; k < el->num_values; k++) {
				if (ldb_val_equal_exact(&el->values[k],
							&values[i])) {
					break;
				}
			}
			el->num_values--;
			for (; k < el->num_values; k++) {
				el->values[k] = el->values[k + 1];
			}
			i++;
		}
	}
	TALLOC_FREE(values);
	TALLOC_FREE(values2);

	return LDB_SUCCESS;
}

/*
  duplicate a ldb_val structure
*/
struct ldb_val ldb_val_dup(TALLOC_CTX *mem_ctx, const struct ldb_val *v)
{
	struct ldb_val v2;
	v2.length = v->length;
	if (v->data == NULL) {
		v2.data = NULL;
		return v2;
	}

	/* the +1 is to cope with buggy C library routines like strndup
	   that look one byte beyond */
	v2.data = talloc_array(mem_ctx, uint8_t, v->length+1);
	if (!v2.data) {
		v2.length = 0;
		return v2;
	}

	memcpy(v2.data, v->data, v->length);
	((char *)v2.data)[v->length] = 0;
	return v2;
}

/**
 * Adds new empty element to msg->elements
 */
static int _ldb_msg_add_el(struct ldb_message *msg,
			   struct ldb_message_element **return_el)
{
	struct ldb_message_element *els;

	/*
	 * TODO: Find out a way to assert on input parameters.
	 * msg and return_el must be valid
	 */

	els = talloc_realloc(msg, msg->elements,
			     struct ldb_message_element, msg->num_elements + 1);
	if (!els) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	ZERO_STRUCT(els[msg->num_elements]);

	msg->elements = els;
	msg->num_elements++;

	*return_el = &els[msg->num_elements-1];

	return LDB_SUCCESS;
}

/**
 * Add an empty element with a given name to a message
 */
int ldb_msg_add_empty(struct ldb_message *msg,
		      const char *attr_name,
		      int flags,
		      struct ldb_message_element **return_el)
{
	int ret;
	struct ldb_message_element *el;

	ret = _ldb_msg_add_el(msg, &el);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	/* initialize newly added element */
	el->flags = flags;
	el->name = talloc_strdup(msg->elements, attr_name);
	if (!el->name) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	if (return_el) {
		*return_el = el;
	}

	return LDB_SUCCESS;
}

/**
 * Adds an element to a message.
 *
 * NOTE: Ownership of ldb_message_element fields
 *       is NOT transferred. Thus, if *el pointer
 *       is invalidated for some reason, this will
 *       corrupt *msg contents also
 */
int ldb_msg_add(struct ldb_message *msg,
		const struct ldb_message_element *el,
		int flags)
{
	int ret;
	struct ldb_message_element *el_new;
	/* We have to copy this, just in case *el is a pointer into
	 * what ldb_msg_add_empty() is about to realloc() */
	struct ldb_message_element el_copy = *el;

	ret = _ldb_msg_add_el(msg, &el_new);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	el_new->flags      = flags;
	el_new->name       = el_copy.name;
	el_new->num_values = el_copy.num_values;
	el_new->values     = el_copy.values;

	return LDB_SUCCESS;
}

/*
 * add a value to a message element
 */
int ldb_msg_element_add_value(TALLOC_CTX *mem_ctx,
			      struct ldb_message_element *el,
			      const struct ldb_val *val)
{
	struct ldb_val *vals;

	if (el->flags & LDB_FLAG_INTERNAL_SHARED_VALUES) {
		/*
		 * Another message is using this message element's values array,
		 * so we don't want to make any modifications to the original
		 * message, or potentially invalidate its own values by calling
		 * talloc_realloc(). Make a copy instead.
		 */
		el->flags &= ~LDB_FLAG_INTERNAL_SHARED_VALUES;

		vals = talloc_array(mem_ctx, struct ldb_val,
				    el->num_values + 1);
		if (vals == NULL) {
			return LDB_ERR_OPERATIONS_ERROR;
		}

		if (el->values != NULL) {
			memcpy(vals, el->values, el->num_values * sizeof(struct ldb_val));
		}
	} else {
		vals = talloc_realloc(mem_ctx, el->values, struct ldb_val,
				      el->num_values + 1);
		if (vals == NULL) {
			return LDB_ERR_OPERATIONS_ERROR;
		}
	}
	el->values = vals;
	el->values[el->num_values] = *val;
	el->num_values++;

	return LDB_SUCCESS;
}

/*
  add a value to a message
*/
int ldb_msg_add_value(struct ldb_message *msg,
		      const char *attr_name,
		      const struct ldb_val *val,
		      struct ldb_message_element **return_el)
{
	struct ldb_message_element *el;
	int ret;

	el = ldb_msg_find_element(msg, attr_name);
	if (!el) {
		ret = ldb_msg_add_empty(msg, attr_name, 0, &el);
		if (ret != LDB_SUCCESS) {
			return ret;
		}
	}

	ret = ldb_msg_element_add_value(msg->elements, el, val);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	if (return_el) {
		*return_el = el;
	}

	return LDB_SUCCESS;
}


/*
  add a value to a message, stealing it into the 'right' place
*/
int ldb_msg_add_steal_value(struct ldb_message *msg,
			    const char *attr_name,
			    struct ldb_val *val)
{
	int ret;
	struct ldb_message_element *el;

	ret = ldb_msg_add_value(msg, attr_name, val, &el);
	if (ret == LDB_SUCCESS) {
		talloc_steal(el->values, val->data);
	}
	return ret;
}


/*
  add a string element to a message, specifying flags
*/
int ldb_msg_add_string_flags(struct ldb_message *msg,
			     const char *attr_name, const char *str,
			     int flags)
{
	struct ldb_val val;
	int ret;
	struct ldb_message_element *el = NULL;

	val.data = discard_const_p(uint8_t, str);
	val.length = strlen(str);

	if (val.length == 0) {
		/* allow empty strings as non-existent attributes */
		return LDB_SUCCESS;
	}

	ret = ldb_msg_add_value(msg, attr_name, &val, &el);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	if (flags != 0) {
		el->flags = flags;
	}

	return LDB_SUCCESS;
}

/*
  add a string element to a message
*/
int ldb_msg_add_string(struct ldb_message *msg,
		       const char *attr_name, const char *str)
{
	return ldb_msg_add_string_flags(msg, attr_name, str, 0);
}

/*
  add a string element to a message, stealing it into the 'right' place
*/
int ldb_msg_add_steal_string(struct ldb_message *msg,
			     const char *attr_name, char *str)
{
	struct ldb_val val;

	val.data = (uint8_t *)str;
	val.length = strlen(str);

	if (val.length == 0) {
		/* allow empty strings as non-existent attributes */
		return LDB_SUCCESS;
	}

	return ldb_msg_add_steal_value(msg, attr_name, &val);
}

/*
  add a DN element to a message
  WARNING: this uses the linearized string from the dn, and does not
  copy the string.
*/
int ldb_msg_add_linearized_dn(struct ldb_message *msg, const char *attr_name,
			      struct ldb_dn *dn)
{
	char *str = ldb_dn_alloc_linearized(msg, dn);

	if (str == NULL) {
		/* we don't want to have unknown DNs added */
		return LDB_ERR_OPERATIONS_ERROR;
	}

	return ldb_msg_add_steal_string(msg, attr_name, str);
}

/*
  add a printf formatted element to a message
*/
int ldb_msg_add_fmt(struct ldb_message *msg,
		    const char *attr_name, const char *fmt, ...)
{
	struct ldb_val val;
	va_list ap;
	char *str;

	va_start(ap, fmt);
	str = talloc_vasprintf(msg, fmt, ap);
	va_end(ap);

	if (str == NULL) return LDB_ERR_OPERATIONS_ERROR;

	val.data   = (uint8_t *)str;
	val.length = strlen(str);

	return ldb_msg_add_steal_value(msg, attr_name, &val);
}

static int ldb_msg_append_value_impl(struct ldb_message *msg,
				     const char *attr_name,
				     const struct ldb_val *val,
				     int flags,
				     struct ldb_message_element **return_el)
{
	struct ldb_message_element *el = NULL;
	int ret;

	ret = ldb_msg_add_empty(msg, attr_name, flags, &el);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	ret = ldb_msg_element_add_value(msg->elements, el, val);
	if (ret != LDB_SUCCESS) {
		return ret;
	}

	if (return_el != NULL) {
		*return_el = el;
	}

	return LDB_SUCCESS;
}

/*
  append a value to a message
*/
int ldb_msg_append_value(struct ldb_message *msg,
			 const char *attr_name,
			 const struct ldb_val *val,
			 int flags)
{
	return ldb_msg_append_value_impl(msg, attr_name, val, flags, NULL);
}

/*
  append a value to a message, stealing it into the 'right' place
*/
int ldb_msg_append_steal_value(struct ldb_message *msg,
			       const char *attr_name,
			       struct ldb_val *val,
			       int flags)
{
	int ret;
	struct ldb_message_element *el = NULL;

	ret = ldb_msg_append_value_impl(msg, attr_name, val, flags, &el);
	if (ret == LDB_SUCCESS) {
		talloc_steal(el->values, val->data);
	}
	return ret;
}

/*
  append a string element to a message, stealing it into the 'right' place
*/
int ldb_msg_append_steal_string(struct ldb_message *msg,
				const char *attr_name, char *str,
				int flags)
{
	struct ldb_val val;

	val.data = (uint8_t *)str;
	val.length = strlen(str);

	if (val.length == 0) {
		/* allow empty strings as non-existent attributes */
		return LDB_SUCCESS;
	}

	return ldb_msg_append_steal_value(msg, attr_name, &val, flags);
}

/*
  append a string element to a message
*/
int ldb_msg_append_string(struct ldb_message *msg,
			  const char *attr_name, const char *str, int flags)
{
	struct ldb_val val;

	val.data = discard_const_p(uint8_t, str);
	val.length = strlen(str);

	if (val.length == 0) {
		/* allow empty strings as non-existent attributes */
		return LDB_SUCCESS;
	}

	return ldb_msg_append_value(msg, attr_name, &val, flags);
}

/*
  append a DN element to a message
  WARNING: this uses the linearized string from the dn, and does not
  copy the string.
*/
int ldb_msg_append_linearized_dn(struct ldb_message *msg, const char *attr_name,
				 struct ldb_dn *dn, int flags)
{
	char *str = ldb_dn_alloc_linearized(msg, dn);

	if (str == NULL) {
		/* we don't want to have unknown DNs added */
		return LDB_ERR_OPERATIONS_ERROR;
	}

	return ldb_msg_append_steal_string(msg, attr_name, str, flags);
}

/*
  append a printf formatted element to a message
*/
int ldb_msg_append_fmt(struct ldb_message *msg, int flags,
		       const char *attr_name, const char *fmt, ...)
{
	struct ldb_val val;
	va_list ap;
	char *str = NULL;

	va_start(ap, fmt);
	str = talloc_vasprintf(msg, fmt, ap);
	va_end(ap);

	if (str == NULL) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	val.data   = (uint8_t *)str;
	val.length = strlen(str);

	return ldb_msg_append_steal_value(msg, attr_name, &val, flags);
}

/*
  compare two ldb_message_element structures
  assumes case sensitive comparison
*/
int ldb_msg_element_compare(struct ldb_message_element *el1,
			    struct ldb_message_element *el2)
{
	unsigned int i;

	if (el1->num_values != el2->num_values) {
		return el1->num_values - el2->num_values;
	}

	for (i=0;i<el1->num_values;i++) {
		if (!ldb_msg_find_val(el2, &el1->values[i])) {
			return -1;
		}
	}

	return 0;
}

/*
  compare two ldb_message_element structures.
  Different ordering is considered a mismatch
*/
bool ldb_msg_element_equal_ordered(const struct ldb_message_element *el1,
				   const struct ldb_message_element *el2)
{
	unsigned i;
	if (el1->num_values != el2->num_values) {
		return false;
	}
	for (i=0;i<el1->num_values;i++) {
		if (ldb_val_equal_exact(&el1->values[i],
					&el2->values[i]) != 1) {
			return false;
		}
	}
	return true;
}

/*
  compare two ldb_message_element structures
  comparing by element name
*/
int ldb_msg_element_compare_name(struct ldb_message_element *el1,
				 struct ldb_message_element *el2)
{
	return ldb_attr_cmp(el1->name, el2->name);
}

/*
  convenience functions to return common types from a message
  these return the first value if the attribute is multi-valued
*/
const struct ldb_val *ldb_msg_find_ldb_val(const struct ldb_message *msg,
					   const char *attr_name)
{
	struct ldb_message_element *el = ldb_msg_find_element(msg, attr_name);
	if (!el || el->num_values == 0) {
		return NULL;
	}
	return &el->values[0];
}

int ldb_msg_find_attr_as_int(const struct ldb_message *msg,
			     const char *attr_name,
			     int default_value)
{
	const struct ldb_val *v = ldb_msg_find_ldb_val(msg, attr_name);
	char buf[sizeof("-2147483648")];
	char *end = NULL;
	int ret;

	if (!v || !v->data) {
		return default_value;
	}

	ZERO_STRUCT(buf);
	if (v->length >= sizeof(buf)) {
		return default_value;
	}

	memcpy(buf, v->data, v->length);
	errno = 0;
	ret = (int) strtoll(buf, &end, 10);
	if (errno != 0) {
		return default_value;
	}
	if (end && end[0] != '\0') {
		return default_value;
	}
	return ret;
}

unsigned int ldb_msg_find_attr_as_uint(const struct ldb_message *msg,
				       const char *attr_name,
				       unsigned int default_value)
{
	const struct ldb_val *v = ldb_msg_find_ldb_val(msg, attr_name);
	char buf[sizeof("-2147483648")];
	char *end = NULL;
	unsigned int ret;

	if (!v || !v->data) {
		return default_value;
	}

	ZERO_STRUCT(buf);
	if (v->length >= sizeof(buf)) {
		return default_value;
	}

	memcpy(buf, v->data, v->length);
	errno = 0;
	ret = (unsigned int) strtoll(buf, &end, 10);
	if (errno != 0) {
		errno = 0;
		ret = (unsigned int) strtoull(buf, &end, 10);
		if (errno != 0) {
			return default_value;
		}
	}
	if (end && end[0] != '\0') {
		return default_value;
	}
	return ret;
}

int64_t ldb_msg_find_attr_as_int64(const struct ldb_message *msg,
				   const char *attr_name,
				   int64_t default_value)
{
	const struct ldb_val *v = ldb_msg_find_ldb_val(msg, attr_name);
	char buf[sizeof("-9223372036854775808")];
	char *end = NULL;
	int64_t ret;

	if (!v || !v->data) {
		return default_value;
	}

	ZERO_STRUCT(buf);
	if (v->length >= sizeof(buf)) {
		return default_value;
	}

	memcpy(buf, v->data, v->length);
	errno = 0;
	ret = (int64_t) strtoll(buf, &end, 10);
	if (errno != 0) {
		return default_value;
	}
	if (end && end[0] != '\0') {
		return default_value;
	}
	return ret;
}

uint64_t ldb_msg_find_attr_as_uint64(const struct ldb_message *msg,
				     const char *attr_name,
				     uint64_t default_value)
{
	const struct ldb_val *v = ldb_msg_find_ldb_val(msg, attr_name);
	char buf[sizeof("-9223372036854775808")];
	char *end = NULL;
	uint64_t ret;

	if (!v || !v->data) {
		return default_value;
	}

	ZERO_STRUCT(buf);
	if (v->length >= sizeof(buf)) {
		return default_value;
	}

	memcpy(buf, v->data, v->length);
	errno = 0;
	ret = (uint64_t) strtoll(buf, &end, 10);
	if (errno != 0) {
		errno = 0;
		ret = (uint64_t) strtoull(buf, &end, 10);
		if (errno != 0) {
			return default_value;
		}
	}
	if (end && end[0] != '\0') {
		return default_value;
	}
	return ret;
}

double ldb_msg_find_attr_as_double(const struct ldb_message *msg,
				   const char *attr_name,
				   double default_value)
{
	const struct ldb_val *v = ldb_msg_find_ldb_val(msg, attr_name);
	char *buf;
	char *end = NULL;
	double ret;

	if (!v || !v->data) {
		return default_value;
	}
	buf = talloc_strndup(msg, (const char *)v->data, v->length);
	if (buf == NULL) {
		return default_value;
	}

	errno = 0;
	ret = strtod(buf, &end);
	talloc_free(buf);
	if (errno != 0) {
		return default_value;
	}
	if (end && end[0] != '\0') {
		return default_value;
	}
	return ret;
}

int ldb_msg_find_attr_as_bool(const struct ldb_message *msg,
			      const char *attr_name,
			      int default_value)
{
	const struct ldb_val *v = ldb_msg_find_ldb_val(msg, attr_name);
	if (!v || !v->data) {
		return default_value;
	}
	if (v->length == 5 && strncasecmp((const char *)v->data, "FALSE", 5) == 0) {
		return 0;
	}
	if (v->length == 4 && strncasecmp((const char *)v->data, "TRUE", 4) == 0) {
		return 1;
	}
	return default_value;
}

const char *ldb_msg_find_attr_as_string(const struct ldb_message *msg,
					const char *attr_name,
					const char *default_value)
{
	const struct ldb_val *v = ldb_msg_find_ldb_val(msg, attr_name);
	if (!v || !v->data) {
		return default_value;
	}
	if (v->data[v->length] != '\0') {
		return default_value;
	}
	return (const char *)v->data;
}

struct ldb_dn *ldb_msg_find_attr_as_dn(struct ldb_context *ldb,
				       TALLOC_CTX *mem_ctx,
				       const struct ldb_message *msg,
				       const char *attr_name)
{
	struct ldb_dn *res_dn;
	const struct ldb_val *v;

	v = ldb_msg_find_ldb_val(msg, attr_name);
	if (!v || !v->data) {
		return NULL;
	}
	res_dn = ldb_dn_from_ldb_val(mem_ctx, ldb, v);
	if ( ! ldb_dn_validate(res_dn)) {
		talloc_free(res_dn);
		return NULL;
	}
	return res_dn;
}

/*
  sort the elements of a message by name
*/
void ldb_msg_sort_elements(struct ldb_message *msg)
{
	TYPESAFE_QSORT(msg->elements, msg->num_elements,
		       ldb_msg_element_compare_name);
}

static struct ldb_message *ldb_msg_copy_shallow_impl(TALLOC_CTX *mem_ctx,
					 const struct ldb_message *msg)
{
	struct ldb_message *msg2;
	unsigned int i;

	msg2 = talloc(mem_ctx, struct ldb_message);
	if (msg2 == NULL) return NULL;

	*msg2 = *msg;

	msg2->elements = talloc_array(msg2, struct ldb_message_element,
				      msg2->num_elements);
	if (msg2->elements == NULL) goto failed;

	for (i=0;i<msg2->num_elements;i++) {
		msg2->elements[i] = msg->elements[i];
	}

	return msg2;

failed:
	talloc_free(msg2);
	return NULL;
}

/*
  shallow copy a message - copying only the elements array so that the caller
  can safely add new elements without changing the message
*/
struct ldb_message *ldb_msg_copy_shallow(TALLOC_CTX *mem_ctx,
					 const struct ldb_message *msg)
{
	struct ldb_message *msg2;
	unsigned int i;

	msg2 = ldb_msg_copy_shallow_impl(mem_ctx, msg);
	if (msg2 == NULL) {
		return NULL;
	}

	for (i = 0; i < msg2->num_elements; ++i) {
		/*
		 * Mark this message's elements as sharing their values with the
		 * original message, so that we don't inadvertently modify or
		 * free them. We don't mark the original message element as
		 * shared, so the original message element should not be
		 * modified or freed while the shallow copy lives.
		 */
		struct ldb_message_element *el = &msg2->elements[i];
		el->flags |= LDB_FLAG_INTERNAL_SHARED_VALUES;
	}

        return msg2;
}

/*
  copy a message, allocating new memory for all parts
*/
struct ldb_message *ldb_msg_copy(TALLOC_CTX *mem_ctx,
				 const struct ldb_message *msg)
{
	struct ldb_message *msg2;
	unsigned int i, j;

	msg2 = ldb_msg_copy_shallow_impl(mem_ctx, msg);
	if (msg2 == NULL) return NULL;

	if (msg2->dn != NULL) {
		msg2->dn = ldb_dn_copy(msg2, msg2->dn);
		if (msg2->dn == NULL) goto failed;
	}

	for (i=0;i<msg2->num_elements;i++) {
		struct ldb_message_element *el = &msg2->elements[i];
		struct ldb_val *values = el->values;
		el->name = talloc_strdup(msg2->elements, el->name);
		if (el->name == NULL) goto failed;
		el->values = talloc_array(msg2->elements, struct ldb_val, el->num_values);
		if (el->values == NULL) goto failed;
		for (j=0;j<el->num_values;j++) {
			el->values[j] = ldb_val_dup(el->values, &values[j]);
			if (el->values[j].data == NULL && values[j].length != 0) {
				goto failed;
			}
		}

                /*
                 * Since we copied this element's values, we can mark them as
                 * not shared.
		 */
		el->flags &= ~LDB_FLAG_INTERNAL_SHARED_VALUES;
	}

	return msg2;

failed:
	talloc_free(msg2);
	return NULL;
}


/**
 * Canonicalize a message, merging elements of the same name
 */
struct ldb_message *ldb_msg_canonicalize(struct ldb_context *ldb,
					 const struct ldb_message *msg)
{
	int ret;
	struct ldb_message *msg2;

	/*
	 * Preserve previous behavior and allocate
	 * *msg2 into *ldb context
	 */
	ret = ldb_msg_normalize(ldb, ldb, msg, &msg2);
	if (ret != LDB_SUCCESS) {
		return NULL;
	}

	return msg2;
}

/**
 * Canonicalize a message, merging elements of the same name
 */
int ldb_msg_normalize(struct ldb_context *ldb,
		      TALLOC_CTX *mem_ctx,
		      const struct ldb_message *msg,
		      struct ldb_message **_msg_out)
{
	unsigned int i;
	struct ldb_message *msg2;

	msg2 = ldb_msg_copy(mem_ctx, msg);
	if (msg2 == NULL) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	ldb_msg_sort_elements(msg2);

	for (i=1; i < msg2->num_elements; i++) {
		struct ldb_message_element *el1 = &msg2->elements[i-1];
		struct ldb_message_element *el2 = &msg2->elements[i];

		if (ldb_msg_element_compare_name(el1, el2) == 0) {
			el1->values = talloc_realloc(msg2->elements,
			                             el1->values, struct ldb_val,
			                             el1->num_values + el2->num_values);
			if (el1->num_values + el2->num_values > 0 && el1->values == NULL) {
				talloc_free(msg2);
				return LDB_ERR_OPERATIONS_ERROR;
			}
			memcpy(el1->values + el1->num_values,
			       el2->values,
			       sizeof(struct ldb_val) * el2->num_values);
			el1->num_values += el2->num_values;
			talloc_free(discard_const_p(char, el2->name));
			if ((i+1) < msg2->num_elements) {
				memmove(el2, el2+1, sizeof(struct ldb_message_element) *
					(msg2->num_elements - (i+1)));
			}
			msg2->num_elements--;
			i--;
		}
	}

	*_msg_out = msg2;
	return LDB_SUCCESS;
}


/**
 * return a ldb_message representing the differences between msg1 and msg2.
 * If you then use this in a ldb_modify() call,
 * it can be used to save edits to a message
 */
struct ldb_message *ldb_msg_diff(struct ldb_context *ldb,
				 struct ldb_message *msg1,
				 struct ldb_message *msg2)
{
	int ldb_ret;
	struct ldb_message *mod;

	ldb_ret = ldb_msg_difference(ldb, ldb, msg1, msg2, &mod);
	if (ldb_ret != LDB_SUCCESS) {
		return NULL;
	}

	return mod;
}

/**
 * return a ldb_message representing the differences between msg1 and msg2.
 * If you then use this in a ldb_modify() call it can be used to save edits to a message
 *
 * Result message is constructed as follows:
 * - LDB_FLAG_MOD_ADD     - elements found only in msg2
 * - LDB_FLAG_MOD_REPLACE - elements in msg2 that have different value in msg1
 *                          Value for msg2 element is used
 * - LDB_FLAG_MOD_DELETE  - elements found only in msg2
 *
 * @return LDB_SUCCESS or LDB_ERR_OPERATIONS_ERROR
 */
int ldb_msg_difference(struct ldb_context *ldb,
		       TALLOC_CTX *mem_ctx,
		       struct ldb_message *msg1,
		       struct ldb_message *msg2,
		       struct ldb_message **_msg_out)
{
	int ldb_res;
	unsigned int i;
	struct ldb_message *mod;
	struct ldb_message_element *el;
	TALLOC_CTX *temp_ctx;

	temp_ctx = talloc_new(mem_ctx);
	if (!temp_ctx) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	mod = ldb_msg_new(temp_ctx);
	if (mod == NULL) {
		goto failed;
	}

	mod->dn = msg1->dn;
	mod->num_elements = 0;
	mod->elements = NULL;

	/*
	 * Canonicalize *msg2 so we have no repeated elements
	 * Resulting message is allocated in *mod's mem context,
	 * as we are going to move some elements from *msg2 to
	 * *mod object later
	 */
	ldb_res = ldb_msg_normalize(ldb, mod, msg2, &msg2);
	if (ldb_res != LDB_SUCCESS) {
		goto failed;
	}

	/* look in msg2 to find elements that need to be added or modified */
	for (i=0;i<msg2->num_elements;i++) {
		el = ldb_msg_find_element(msg1, msg2->elements[i].name);

		if (el && ldb_msg_element_compare(el, &msg2->elements[i]) == 0) {
			continue;
		}

		ldb_res = ldb_msg_add(mod,
		                      &msg2->elements[i],
		                      el ? LDB_FLAG_MOD_REPLACE : LDB_FLAG_MOD_ADD);
		if (ldb_res != LDB_SUCCESS) {
			goto failed;
		}
	}

	/* look in msg1 to find elements that need to be deleted */
	for (i=0;i<msg1->num_elements;i++) {
		el = ldb_msg_find_element(msg2, msg1->elements[i].name);
		if (el == NULL) {
			ldb_res = ldb_msg_add_empty(mod,
			                            msg1->elements[i].name,
			                            LDB_FLAG_MOD_DELETE, NULL);
			if (ldb_res != LDB_SUCCESS) {
				goto failed;
			}
		}
	}

	/* steal resulting message into supplied context */
	talloc_steal(mem_ctx, mod);
	*_msg_out = mod;

	talloc_free(temp_ctx);
	return LDB_SUCCESS;

failed:
	talloc_free(temp_ctx);
	return LDB_ERR_OPERATIONS_ERROR;
}


int ldb_msg_sanity_check(struct ldb_context *ldb,
			 const struct ldb_message *msg)
{
	unsigned int i, j;

	/* basic check on DN */
	if (msg->dn == NULL) {
		ldb_set_errstring(ldb, "ldb message lacks a DN!");
		return LDB_ERR_INVALID_DN_SYNTAX;
	}

	/* basic syntax checks */
	for (i = 0; i < msg->num_elements; i++) {
		for (j = 0; j < msg->elements[i].num_values; j++) {
			if (msg->elements[i].values[j].length == 0) {
				/* an attribute cannot be empty */
				ldb_asprintf_errstring(ldb, "Element %s has empty attribute in ldb message (%s)!",
							    msg->elements[i].name,
							    ldb_dn_get_linearized(msg->dn));
				return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
			}
		}
	}

	return LDB_SUCCESS;
}




/*
  copy an attribute list. This only copies the array, not the elements
  (ie. the elements are left as the same pointers)
*/
const char **ldb_attr_list_copy(TALLOC_CTX *mem_ctx, const char * const *attrs)
{
	const char **ret;
	unsigned int i;

	for (i=0;attrs && attrs[i];i++) /* noop */ ;
	ret = talloc_array(mem_ctx, const char *, i+1);
	if (ret == NULL) {
		return NULL;
	}
	for (i=0;attrs && attrs[i];i++) {
		ret[i] = attrs[i];
	}
	ret[i] = attrs[i];
	return ret;
}


/*
  copy an attribute list. This only copies the array, not the elements
  (ie. the elements are left as the same pointers).  The new attribute is added to the list.
*/
const char **ldb_attr_list_copy_add(TALLOC_CTX *mem_ctx, const char * const *attrs, const char *new_attr)
{
	const char **ret;
	unsigned int i;
	bool found = false;

	for (i=0;attrs && attrs[i];i++) {
		if (ldb_attr_cmp(attrs[i], new_attr) == 0) {
			found = true;
		}
	}
	if (found) {
		return ldb_attr_list_copy(mem_ctx, attrs);
	}
	ret = talloc_array(mem_ctx, const char *, i+2);
	if (ret == NULL) {
		return NULL;
	}
	for (i=0;attrs && attrs[i];i++) {
		ret[i] = attrs[i];
	}
	ret[i] = new_attr;
	ret[i+1] = NULL;
	return ret;
}


/*
  return 1 if an attribute is in a list of attributes, or 0 otherwise
*/
int ldb_attr_in_list(const char * const *attrs, const char *attr)
{
	unsigned int i;
	for (i=0;attrs && attrs[i];i++) {
		if (ldb_attr_cmp(attrs[i], attr) == 0) {
			return 1;
		}
	}
	return 0;
}


/*
  rename the specified attribute in a search result
*/
int ldb_msg_rename_attr(struct ldb_message *msg, const char *attr, const char *replace)
{
	struct ldb_message_element *el = ldb_msg_find_element(msg, attr);
	if (el == NULL) {
		return LDB_SUCCESS;
	}
	el->name = talloc_strdup(msg->elements, replace);
	if (el->name == NULL) {
		return LDB_ERR_OPERATIONS_ERROR;
	}
	return LDB_SUCCESS;
}


/*
  copy the specified attribute in a search result to a new attribute
*/
int ldb_msg_copy_attr(struct ldb_message *msg, const char *attr, const char *replace)
{
	struct ldb_message_element *el = ldb_msg_find_element(msg, attr);
	int ret;

	if (el == NULL) {
		return LDB_SUCCESS;
	}
	ret = ldb_msg_add(msg, el, 0);
	if (ret != LDB_SUCCESS) {
		return ret;
	}
	return ldb_msg_rename_attr(msg, attr, replace);
}

/*
  remove the specified element in a search result
*/
void ldb_msg_remove_element(struct ldb_message *msg, struct ldb_message_element *el)
{
	ptrdiff_t n = (el - msg->elements);
	if (n >= msg->num_elements || n < 0) {
		/* the element is not in the list. the caller is crazy. */
		return;
	}
	msg->num_elements--;
	if (n != msg->num_elements) {
		memmove(el, el+1, (msg->num_elements - n)*sizeof(*el));
	}
}


/*
  remove the specified attribute in a search result
*/
void ldb_msg_remove_attr(struct ldb_message *msg, const char *attr)
{
	struct ldb_message_element *el;

	while ((el = ldb_msg_find_element(msg, attr)) != NULL) {
		ldb_msg_remove_element(msg, el);
	}
}

/*
  return a LDAP formatted GeneralizedTime string
*/
char *ldb_timestring(TALLOC_CTX *mem_ctx, time_t t)
{
	struct tm *tm = gmtime(&t);
	char *ts;
	int r;

	if (!tm) {
		return NULL;
	}

	/* we now excatly how long this string will be */
	ts = talloc_array(mem_ctx, char, 18);

	/* formatted like: 20040408072012.0Z */
	r = snprintf(ts, 18,
			"%04u%02u%02u%02u%02u%02u.0Z",
			tm->tm_year+1900, tm->tm_mon+1,
			tm->tm_mday, tm->tm_hour, tm->tm_min,
			tm->tm_sec);

	if (r != 17) {
		talloc_free(ts);
		errno = EOVERFLOW;
		return NULL;
	}

	return ts;
}

/*
  convert a LDAP GeneralizedTime string to a time_t. Return 0 if unable to convert
*/
time_t ldb_string_to_time(const char *s)
{
	struct tm tm;

	if (s == NULL) return 0;

	memset(&tm, 0, sizeof(tm));
	if (sscanf(s, "%04u%02u%02u%02u%02u%02u.0Z",
		   &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
		   &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
		return 0;
	}
	tm.tm_year -= 1900;
	tm.tm_mon -= 1;

	return timegm(&tm);
}

/*
  convert a LDAP GeneralizedTime string in ldb_val format to a
  time_t.
*/
int ldb_val_to_time(const struct ldb_val *v, time_t *t)
{
	char val[15] = {0};
	struct tm tm = {
		.tm_year = 0,
	};

	if (v == NULL) {
		return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
	}

	if (v->data == NULL) {
		return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
	}

	if (v->length < 16 && v->length != 13) {
		return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
	}

	if (v->data[v->length - 1] != 'Z') {
		return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
	}

	if (v->length == 13) {
		memcpy(val, v->data, 12);

		if (sscanf(val, "%02u%02u%02u%02u%02u%02u",
			&tm.tm_year, &tm.tm_mon, &tm.tm_mday,
			&tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
			return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
		}
		if (tm.tm_year < 50) {
			tm.tm_year += 100;
		}
	} else {

		/*
		 * anything between '.' and 'Z' is silently ignored.
		 */
		if (v->data[14] != '.') {
			return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
		}

		memcpy(val, v->data, 14);

		if (sscanf(val, "%04u%02u%02u%02u%02u%02u",
			&tm.tm_year, &tm.tm_mon, &tm.tm_mday,
			&tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
			return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
		}
		tm.tm_year -= 1900;
	}
	tm.tm_mon -= 1;

	*t = timegm(&tm);

	return LDB_SUCCESS;
}

/*
  return a LDAP formatted UTCTime string
*/
char *ldb_timestring_utc(TALLOC_CTX *mem_ctx, time_t t)
{
	struct tm *tm = gmtime(&t);
	char *ts;
	int r;

	if (!tm) {
		return NULL;
	}

	/* we now excatly how long this string will be */
	ts = talloc_array(mem_ctx, char, 14);

	/* formatted like: 20040408072012.0Z => 040408072012Z */
	r = snprintf(ts, 14,
			"%02u%02u%02u%02u%02u%02uZ",
			(tm->tm_year+1900)%100, tm->tm_mon+1,
			tm->tm_mday, tm->tm_hour, tm->tm_min,
			tm->tm_sec);

	if (r != 13) {
		talloc_free(ts);
		return NULL;
	}

	return ts;
}

/*
  convert a LDAP UTCTime string to a time_t. Return 0 if unable to convert
*/
time_t ldb_string_utc_to_time(const char *s)
{
	struct tm tm;

	if (s == NULL) return 0;

	memset(&tm, 0, sizeof(tm));
	if (sscanf(s, "%02u%02u%02u%02u%02u%02uZ",
		   &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
		   &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
		return 0;
	}
	if (tm.tm_year < 50) {
		tm.tm_year += 100;
	}
	tm.tm_mon -= 1;

	return timegm(&tm);
}


/*
  dump a set of results to a file. Useful from within gdb
*/
void ldb_dump_results(struct ldb_context *ldb, struct ldb_result *result, FILE *f)
{
	unsigned int i;

	for (i = 0; i < result->count; i++) {
		struct ldb_ldif ldif;
		fprintf(f, "# record %d\n", i+1);
		ldif.changetype = LDB_CHANGETYPE_NONE;
		ldif.msg = result->msgs[i];
		ldb_ldif_write_file(ldb, f, &ldif);
	}
}

/*
  checks for a string attribute. Returns "1" on match and otherwise "0".
*/
int ldb_msg_check_string_attribute(const struct ldb_message *msg,
				   const char *name, const char *value)
{
	struct ldb_message_element *el;
	struct ldb_val val;

	el = ldb_msg_find_element(msg, name);
	if (el == NULL) {
		return 0;
	}

	val.data = discard_const_p(uint8_t, value);
	val.length = strlen(value);

	if (ldb_msg_find_val(el, &val)) {
		return 1;
	}

	return 0;
}


/*
  compare a ldb_val to a string
*/
int ldb_val_string_cmp(const struct ldb_val *v, const char *str)
{
	size_t len = strlen(str);
	if (len != v->length) {
		return len - v->length;
	}
	return strncmp((const char *)v->data, str, len);
}