summaryrefslogtreecommitdiff
path: root/lib/ldb/common/ldb_pack.c
blob: 9d87a10b9f1ded6e21bfc8ce7b1d6340c5922975 (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
/*
   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 pack/unpack
 *
 *  Description: pack/unpack routines for ldb messages as key/value blobs
 *
 *  Author: Andrew Tridgell
 */

#include "ldb_private.h"

/*
 * These macros are from byte_array.h via libssh
 * TODO: This will be replaced with use of the byte_array.h header when it
 * becomes available.
 *
 * Macros for handling integer types in byte arrays
 *
 * This file is originally from the libssh.org project
 *
 * Copyright (c) 2018 Andreas Schneider <asn@cryptomilk.org>
 *
 * 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 2.1 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, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */
#define _DATA_BYTE_CONST(data, pos) \
	((uint8_t)(((const uint8_t *)(data))[(pos)]))
#define PULL_LE_U8(data, pos) \
	(_DATA_BYTE_CONST(data, pos))
#define PULL_LE_U16(data, pos) \
	((uint16_t)PULL_LE_U8(data, pos) |\
	((uint16_t)(PULL_LE_U8(data, (pos) + 1))) << 8)
#define PULL_LE_U32(data, pos) \
	((uint32_t)(PULL_LE_U16(data, pos) |\
	((uint32_t)PULL_LE_U16(data, (pos) + 2)) << 16))

#define _DATA_BYTE(data, pos) \
	(((uint8_t *)(data))[(pos)])
#define PUSH_LE_U8(data, pos, val) \
	(_DATA_BYTE(data, pos) = ((uint8_t)(val)))
#define PUSH_LE_U16(data, pos, val) \
	(PUSH_LE_U8((data), (pos), (uint8_t)((uint16_t)(val) & 0xff)),\
		    PUSH_LE_U8((data), (pos) + 1,\
			       (uint8_t)((uint16_t)(val) >> 8)))
#define PUSH_LE_U32(data, pos, val) \
	(PUSH_LE_U16((data), (pos), (uint16_t)((uint32_t)(val) & 0xffff)),\
	 PUSH_LE_U16((data), (pos) + 2, (uint16_t)((uint32_t)(val) >> 16)))

#define U32_LEN 4
#define U16_LEN 2
#define U8_LEN 1
#define NULL_PAD_BYTE_LEN 1

static int attribute_storable_values(const struct ldb_message_element *el)
{
	if (el->num_values == 0) return 0;

	if (ldb_attr_cmp(el->name, "distinguishedName") == 0) return 0;

	return el->num_values;
}

static int ldb_pack_data_v1(struct ldb_context *ldb,
			    const struct ldb_message *message,
			    struct ldb_val *data)
{
	unsigned int i, j, real_elements=0;
	size_t size, dn_len, attr_len, value_len;
	const char *dn;
	uint8_t *p;
	size_t len;

	dn = ldb_dn_get_linearized(message->dn);
	if (dn == NULL) {
		errno = ENOMEM;
		return -1;
	}

	/* work out how big it needs to be */
	size = U32_LEN * 2 + NULL_PAD_BYTE_LEN;

	dn_len = strlen(dn);
	if (size + dn_len < size) {
		errno = ENOMEM;
		return -1;
	}
	size += dn_len;

	/*
	 * First calcuate the buffer size we need, and check for
	 * overflows
	 */
	for (i=0;i<message->num_elements;i++) {
		if (attribute_storable_values(&message->elements[i]) == 0) {
			continue;
		}

		real_elements++;

		if (size + U32_LEN + NULL_PAD_BYTE_LEN < size) {
			errno = ENOMEM;
			return -1;
		}
		size += U32_LEN + NULL_PAD_BYTE_LEN;

		attr_len = strlen(message->elements[i].name);
		if (size + attr_len < size) {
			errno = ENOMEM;
			return -1;
		}
		size += attr_len;

		for (j=0;j<message->elements[i].num_values;j++) {
			if (size + U32_LEN + NULL_PAD_BYTE_LEN < size) {
				errno = ENOMEM;
				return -1;
			}
			size += U32_LEN + NULL_PAD_BYTE_LEN;

			value_len = message->elements[i].values[j].length;
			if (size + value_len < size) {
				errno = ENOMEM;
				return -1;
			}
			size += value_len;
		}
	}

	/* allocate it */
	data->data = talloc_array(ldb, uint8_t, size);
	if (!data->data) {
		errno = ENOMEM;
		return -1;
	}
	data->length = size;

	p = data->data;
	PUSH_LE_U32(p, 0, LDB_PACKING_FORMAT);
	p += U32_LEN;
	PUSH_LE_U32(p, 0, real_elements);
	p += U32_LEN;

	/* the dn needs to be packed so we can be case preserving
	   while hashing on a case folded dn */
	len = dn_len;
	memcpy(p, dn, len+NULL_PAD_BYTE_LEN);
	p += len + NULL_PAD_BYTE_LEN;

	for (i=0;i<message->num_elements;i++) {
		if (attribute_storable_values(&message->elements[i]) == 0) {
			continue;
		}
		len = strlen(message->elements[i].name);
		memcpy(p, message->elements[i].name, len+NULL_PAD_BYTE_LEN);
		p += len + NULL_PAD_BYTE_LEN;
		PUSH_LE_U32(p, 0, message->elements[i].num_values);
		p += U32_LEN;
		for (j=0;j<message->elements[i].num_values;j++) {
			PUSH_LE_U32(p, 0,
				    message->elements[i].values[j].length);
			p += U32_LEN;
			memcpy(p, message->elements[i].values[j].data,
			       message->elements[i].values[j].length);
			p[message->elements[i].values[j].length] = 0;
			p += message->elements[i].values[j].length +
				NULL_PAD_BYTE_LEN;
		}
	}

	return 0;
}

/*
 * New pack version designed based on performance profiling of version 1.
 * The approach is to separate value data from the rest of the record's data.
 * This improves performance because value data is not needed during unpacking
 * or filtering of the message's attribute list. During filtering we only copy
 * attributes which are present in the attribute list, however at the parse
 * stage we need to point to all attributes as they may be referenced in the
 * search expression.
 * With this new format, we don't lose time loading data (eg via
 * talloc_memdup()) that is never needed (for the vast majority of attributes
 * are are never found in either the search expression or attribute list).
 * Additional changes include adding a canonicalized DN (for later
 * optimizations) and variable width length fields for faster unpacking.
 * The pack and unpack performance improvement is tested in the torture
 * test torture_ldb_pack_format_perf.
 *
 * Layout:
 *
 * Version (4 bytes)
 * Number of Elements (4 bytes)
 * DN length (4 bytes)
 * DN with null terminator (DN length + 1 bytes)
 * Canonicalized DN length (4 bytes)
 * Canonicalized DN with null terminator (Canonicalized DN length + 1 bytes)
 * Number of bytes from here to value data section (4 bytes)
 * # For each element:
 * 	Element name length (4 bytes)
 * 	Element name with null terminator (Element name length + 1 bytes)
 * 	Number of values (4 bytes)
 * 	Width of value lengths
 * 	# For each value:
 * 		Value data length (#bytes given by width field above)
 * # For each element:
 * 	# For each value:
 *	 	Value data (#bytes given by corresponding length above)
 */
static int ldb_pack_data_v2(struct ldb_context *ldb,
			    const struct ldb_message *message,
			    struct ldb_val *data)
{
	unsigned int i, j, real_elements=0;
	size_t size, dn_len, dn_canon_len, attr_len, value_len;
	const char *dn, *dn_canon;
	uint8_t *p, *q;
	size_t len;
	size_t max_val_len;
	uint8_t val_len_width;

	/*
	 * First half of this function will calculate required size for
	 * packed data. Initial size is 20 = 5 * 4.  5 fixed fields are:
	 * version, num elements, dn len, canon dn len, attr section len
	 */
	size = U32_LEN * 5;

	/*
	 * Get linearized and canonicalized form of the DN and add the lengths
	 * of each to size, plus 1 for null terminator.
	 */
	dn = ldb_dn_get_linearized(message->dn);
	if (dn == NULL) {
		errno = ENOMEM;
		return -1;
	}

	dn_len = strlen(dn) + NULL_PAD_BYTE_LEN;
	if (size + dn_len < size) {
		errno = ENOMEM;
		return -1;
	}
	size += dn_len;

	if (ldb_dn_is_special(message->dn)) {
		dn_canon_len = NULL_PAD_BYTE_LEN;
		dn_canon = discard_const_p(char, "\0");
	} else {
		dn_canon = ldb_dn_canonical_string(message->dn, message->dn);
		if (dn_canon == NULL) {
			errno = ENOMEM;
			return -1;
		}

		dn_canon_len = strlen(dn_canon) + NULL_PAD_BYTE_LEN;
		if (size + dn_canon_len < size) {
			errno = ENOMEM;
			return -1;
		}
	}
	size += dn_canon_len;

	/* Add the size required by each element */
	for (i=0;i<message->num_elements;i++) {
		if (attribute_storable_values(&message->elements[i]) == 0) {
			continue;
		}

		real_elements++;

		/*
		 * Add length of element name + 9 for:
		 * 1 for null terminator
		 * 4 for element name length field
		 * 4 for number of values field
		 */
		attr_len = strlen(message->elements[i].name);
		if (size + attr_len + U32_LEN * 2 + NULL_PAD_BYTE_LEN < size) {
			errno = ENOMEM;
			return -1;
		}
		size += attr_len + U32_LEN * 2 + NULL_PAD_BYTE_LEN;

		/*
		 * Find the max value length, so we can calculate the width
		 * required for the value length fields.
		 */
		max_val_len = 0;
		for (j=0;j<message->elements[i].num_values;j++) {
			value_len = message->elements[i].values[j].length;
			if (value_len > max_val_len) {
				max_val_len = value_len;
			}

			if (size + value_len + NULL_PAD_BYTE_LEN < size) {
				errno = ENOMEM;
				return -1;
			}
			size += value_len + NULL_PAD_BYTE_LEN;
		}

		if (max_val_len <= UCHAR_MAX) {
			val_len_width = U8_LEN;
		} else if (max_val_len <= USHRT_MAX) {
			val_len_width = U16_LEN;
		} else if (max_val_len <= UINT_MAX) {
		        val_len_width = U32_LEN;
		} else {
			errno = EMSGSIZE;
			return -1;
		}

		/* Total size required for val lengths (re-using variable) */
		max_val_len = (val_len_width*message->elements[i].num_values);

		/* Add one for storing the width */
		max_val_len += U8_LEN;
		if (size + max_val_len < size) {
			errno = ENOMEM;
			return -1;
		}
		size += max_val_len;
	}

	/* Allocate */
	data->data = talloc_array(ldb, uint8_t, size);
	if (!data->data) {
		errno = ENOMEM;
		return -1;
	}
	data->length = size;

	/* Packing format version and number of element */
	p = data->data;
	PUSH_LE_U32(p, 0, LDB_PACKING_FORMAT_V2);
	p += U32_LEN;
	PUSH_LE_U32(p, 0, real_elements);
	p += U32_LEN;

	/* Pack DN and Canonicalized DN */
	PUSH_LE_U32(p, 0, dn_len-NULL_PAD_BYTE_LEN);
	p += U32_LEN;
	memcpy(p, dn, dn_len);
	p += dn_len;

	PUSH_LE_U32(p, 0, dn_canon_len-NULL_PAD_BYTE_LEN);
	p += U32_LEN;
	memcpy(p, dn_canon, dn_canon_len);
	p += dn_canon_len;

	/*
	 * Save pointer at this point and leave a U32_LEN gap for
	 * storing the size of the attribute names and value lengths
	 * section
	 */
	q = p;
	p += U32_LEN;

	for (i=0;i<message->num_elements;i++) {
		if (attribute_storable_values(&message->elements[i]) == 0) {
			continue;
		}

		/* Length of el name */
		len = strlen(message->elements[i].name);
		PUSH_LE_U32(p, 0, len);
		p += U32_LEN;

		/*
		 * Even though we have the element name's length, put a null
		 * terminator at the end so if any code uses the name
		 * directly, it'll be safe to do things requiring null
		 * termination like strlen
		 */
		memcpy(p, message->elements[i].name, len+NULL_PAD_BYTE_LEN);
		p += len + NULL_PAD_BYTE_LEN;
		/* Num values */
		PUSH_LE_U32(p, 0, message->elements[i].num_values);
		p += U32_LEN;

		/*
		 * Calculate value length width again. It's faster to
		 * calculate it again than do the array management to
		 * store the result during size calculation.
		 */
		max_val_len = 0;
		for (j=0;j<message->elements[i].num_values;j++) {
			value_len = message->elements[i].values[j].length;
			if (value_len > max_val_len) {
				max_val_len = value_len;
			}
		}

		if (max_val_len <= UCHAR_MAX) {
			val_len_width = U8_LEN;
		} else if (max_val_len <= USHRT_MAX) {
			val_len_width = U16_LEN;
		} else if (max_val_len <= UINT_MAX) {
		        val_len_width = U32_LEN;
		} else {
			errno = EMSGSIZE;
			return -1;
		}

		/* Pack the width */
		*p = val_len_width & 0xFF;
		p += U8_LEN;

		/*
		 * Pack each value's length using the minimum number of bytes
		 * required, which we just calculated. We repeat the loop
		 * for each case here so the compiler can inline code.
		 */
		if (val_len_width == U8_LEN) {
			for (j=0;j<message->elements[i].num_values;j++) {
				PUSH_LE_U8(p, 0,
					message->elements[i].values[j].length);
				p += U8_LEN;
			}
		} else if (val_len_width == U16_LEN) {
			for (j=0;j<message->elements[i].num_values;j++) {
				PUSH_LE_U16(p, 0,
					message->elements[i].values[j].length);
				p += U16_LEN;
			}
		} else if (val_len_width == U32_LEN) {
			for (j=0;j<message->elements[i].num_values;j++) {
				PUSH_LE_U32(p, 0,
					message->elements[i].values[j].length);
				p += U32_LEN;
			}
		}
	}

	/*
	 * We've finished packing the attr names and value lengths
	 * section, so store the size in the U32_LEN gap we left
	 * earlier
	 */
	PUSH_LE_U32(q, 0, p-q);

	/* Now pack the values */
	for (i=0;i<message->num_elements;i++) {
		if (attribute_storable_values(&message->elements[i]) == 0) {
			continue;
		}
		for (j=0;j<message->elements[i].num_values;j++) {
			memcpy(p, message->elements[i].values[j].data,
			       message->elements[i].values[j].length);

			/*
			 * Even though we have the data length, put a null
			 * terminator at the end of each value's data so if
			 * any code uses the data directly, it'll  be safe to
			 * do things requiring null termination like strlen.
			 */
			p[message->elements[i].values[j].length] = 0;
			p += message->elements[i].values[j].length +
				NULL_PAD_BYTE_LEN;
		}
	}

	/*
	 * If we didn't end up at the end of the data here, something has
	 * gone very wrong.
	 */
	if (p != data->data + size) {
		errno = ENOMEM;
		return -1;
	}

	return 0;
}

/*
  pack a ldb message into a linear buffer in a ldb_val

  note that this routine avoids saving elements with zero values,
  as these are equivalent to having no element

  caller frees the data buffer after use
*/
int ldb_pack_data(struct ldb_context *ldb,
		  const struct ldb_message *message,
		  struct ldb_val *data,
		  uint32_t pack_format_version) {

	if (pack_format_version == LDB_PACKING_FORMAT) {
		return ldb_pack_data_v1(ldb, message, data);
	} else if (pack_format_version == LDB_PACKING_FORMAT_V2) {
		return ldb_pack_data_v2(ldb, message, data);
	} else {
		errno = EINVAL;
		return -1;
	}
}

/*
 * Unpack a ldb message from a linear buffer in ldb_val
 */
static int ldb_unpack_data_flags_v1(struct ldb_context *ldb,
				    const struct ldb_val *data,
				    struct ldb_message *message,
				    unsigned int flags,
				    unsigned format)
{
	uint8_t *p;
	size_t remaining;
	size_t dn_len;
	unsigned int i, j;
	unsigned int nelem = 0;
	size_t len;
	struct ldb_val *ldb_val_single_array = NULL;

	message->elements = NULL;

	p = data->data;

	/* Format (U32, already read) + U32 for num_elements */
	if (data->length < U32_LEN * 2) {
		errno = EIO;
		goto failed;
	}

	/* Skip first 4 bytes, format already read */
	p += U32_LEN;
	message->num_elements = PULL_LE_U32(p, 0);
	p += U32_LEN;

	remaining = data->length - U32_LEN * 2;

	switch (format) {
	case LDB_PACKING_FORMAT_NODN:
		message->dn = NULL;
		break;

	case LDB_PACKING_FORMAT:
		/*
		 * With this check, we know that the DN at p is \0
		 * terminated.
		 */
		dn_len = strnlen((char *)p, remaining);
		if (dn_len == remaining) {
			errno = EIO;
			goto failed;
		}
		if (flags & LDB_UNPACK_DATA_FLAG_NO_DN) {
			message->dn = NULL;
		} else {
			struct ldb_val blob;
			blob.data = discard_const_p(uint8_t, p);
			blob.length = dn_len;
			message->dn = ldb_dn_from_ldb_val(message, ldb, &blob);
			if (message->dn == NULL) {
				errno = ENOMEM;
				goto failed;
			}
		}
		/*
		 * Redundant: by definition, remaining must be more
		 * than one less than dn_len, as otherwise it would be
		 * == dn_len
		 */
		if (remaining < dn_len + NULL_PAD_BYTE_LEN) {
			errno = EIO;
			goto failed;
		}
		remaining -= dn_len + NULL_PAD_BYTE_LEN;
		p += dn_len + NULL_PAD_BYTE_LEN;
		break;

	default:
		errno = EIO;
		goto failed;
	}

	if (flags & LDB_UNPACK_DATA_FLAG_NO_ATTRS) {
		return 0;
	}
	
	if (message->num_elements == 0) {
		return 0;
	}

	if (message->num_elements > remaining / 6) {
		errno = EIO;
		goto failed;
	}

	message->elements = talloc_zero_array(message, struct ldb_message_element,
					      message->num_elements);
	if (!message->elements) {
		errno = ENOMEM;
		goto failed;
	}

	/*
	 * In typical use, most values are single-valued.  This makes
	 * it quite expensive to allocate an array of ldb_val for each
	 * of these, just to then hold the pointer to the data buffer
	 * So with LDB_UNPACK_DATA_FLAG_NO_VALUES_ALLOC we allocate this
	 * ahead of time and use it for the single values where possible.
	 * (This is used the the normal search case, but not in the
	 * index case because of caller requirements).
	 */
	if (flags & LDB_UNPACK_DATA_FLAG_NO_VALUES_ALLOC) {
		ldb_val_single_array = talloc_array(message->elements, struct ldb_val,
						    message->num_elements);
		if (ldb_val_single_array == NULL) {
			errno = ENOMEM;
			goto failed;
		}
	}

	for (i=0;i<message->num_elements;i++) {
		const char *attr = NULL;
		size_t attr_len;
		struct ldb_message_element *element = NULL;

		/*
		 * Sanity check: Element must be at least the size of empty
		 * attr name and value and NULL terms for each.
		 */
		if (remaining < U32_LEN * 2 + NULL_PAD_BYTE_LEN * 2) {
			errno = EIO;
			goto failed;
		}

		/*
		 * With this check, we know that the attribute name at
		 * p is \0 terminated.
		 */
		attr_len = strnlen((char *)p, remaining-6);
		if (attr_len == remaining-6) {
			errno = EIO;
			goto failed;
		}
		if (attr_len == 0) {
			errno = EIO;
			goto failed;
		}
		attr = (char *)p;

		element = &message->elements[nelem];
		element->name = attr;
		element->flags = 0;

		if (remaining < (attr_len + NULL_PAD_BYTE_LEN)) {
			errno = EIO;
			goto failed;
		}
		remaining -= attr_len + NULL_PAD_BYTE_LEN;
		p += attr_len + NULL_PAD_BYTE_LEN;
		element->num_values = PULL_LE_U32(p, 0);
		element->values = NULL;
		if ((flags & LDB_UNPACK_DATA_FLAG_NO_VALUES_ALLOC) && element->num_values == 1) {
			element->values = &ldb_val_single_array[nelem];
		} else if (element->num_values != 0) {
			element->values = talloc_array(message->elements,
						       struct ldb_val,
						       element->num_values);
			if (!element->values) {
				errno = ENOMEM;
				goto failed;
			}
		}
		p += U32_LEN;
		if (remaining < U32_LEN) {
			errno = EIO;
			goto failed;
		}
		remaining -= U32_LEN;
		for (j = 0; j < element->num_values; j++) {
			/*
			 * Sanity check: Value must be at least the size of
			 * empty val and NULL terminator.
			 */
			if (remaining < U32_LEN + NULL_PAD_BYTE_LEN) {
				errno = EIO;
				goto failed;
			}
			remaining -= U32_LEN + NULL_PAD_BYTE_LEN;

			len = PULL_LE_U32(p, 0);
			if (remaining < len) {
				errno = EIO;
				goto failed;
			}
			if (len + NULL_PAD_BYTE_LEN < len) {
				errno = EIO;
				goto failed;
			}

			element->values[j].length = len;
			element->values[j].data = p + U32_LEN;
			remaining -= len;
			p += len + U32_LEN + NULL_PAD_BYTE_LEN;
		}
		nelem++;
	}
	/*
	 * Adapt the number of elements to the real number of unpacked elements,
	 * it means that we overallocated elements array.
	 */
	message->num_elements = nelem;

	/*
	 * Shrink the allocated size.  On current talloc behaviour
	 * this will help if we skipped 32 or more attributes.
	 */
	message->elements = talloc_realloc(message, message->elements,
					   struct ldb_message_element,
					   message->num_elements);

	if (remaining != 0) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "Error: %zu bytes unread in ldb_unpack_data_flags",
			  remaining);
	}

	return 0;

failed:
	talloc_free(message->elements);
	return -1;
}

/*
 * Unpack a ldb message from a linear buffer in ldb_val
 */
static int ldb_unpack_data_flags_v2(struct ldb_context *ldb,
				    const struct ldb_val *data,
				    struct ldb_message *message,
				    unsigned int flags)
{
	uint8_t *p, *q, *end_p, *value_section_p;
	unsigned int i, j;
	unsigned int nelem = 0;
	size_t len;
	struct ldb_val *ldb_val_single_array = NULL;
	uint8_t val_len_width;

	message->elements = NULL;

	p = data->data;
	end_p = p + data->length;

	/* Skip first 4 bytes, format already read */
	p += U32_LEN;

	/* First fields are fixed: num_elements, DN length */
	if (p + U32_LEN * 2 > end_p) {
		errno = EIO;
		goto failed;
	}

	message->num_elements = PULL_LE_U32(p, 0);
	p += U32_LEN;

	len = PULL_LE_U32(p, 0);
	p += U32_LEN;

	if (p + len + NULL_PAD_BYTE_LEN > end_p) {
		errno = EIO;
		goto failed;
	}

	if (flags & LDB_UNPACK_DATA_FLAG_NO_DN) {
		message->dn = NULL;
	} else {
		struct ldb_val blob;
		blob.data = discard_const_p(uint8_t, p);
		blob.length = len;
		message->dn = ldb_dn_from_ldb_val(message, ldb, &blob);
		if (message->dn == NULL) {
			errno = ENOMEM;
			goto failed;
		}
	}

	p += len + NULL_PAD_BYTE_LEN;

	if (*(p-NULL_PAD_BYTE_LEN) != '\0') {
		errno = EINVAL;
		goto failed;
	}

	/* Now skip the canonicalized DN and its length */
	len = PULL_LE_U32(p, 0) + NULL_PAD_BYTE_LEN;
	p += U32_LEN;

	if (p + len > end_p) {
		errno = EIO;
		goto failed;
	}

	p += len;

	if (*(p-NULL_PAD_BYTE_LEN) != '\0') {
		errno = EINVAL;
		goto failed;
	}

	if (flags & LDB_UNPACK_DATA_FLAG_NO_ATTRS) {
		return 0;
	}

	if (message->num_elements == 0) {
		return 0;
	}

	/*
	 * Sanity check (17 bytes is the minimum element size)
	 */
	if (message->num_elements > (end_p - p) / 17) {
		errno = EIO;
		goto failed;
	}

	message->elements = talloc_zero_array(message,
					      struct ldb_message_element,
					      message->num_elements);
	if (!message->elements) {
		errno = ENOMEM;
		goto failed;
	}

	/*
	 * In typical use, most values are single-valued.  This makes
	 * it quite expensive to allocate an array of ldb_val for each
	 * of these, just to then hold the pointer to the data buffer.
	 * So with LDB_UNPACK_DATA_FLAG_NO_VALUES_ALLOC we allocate this
	 * ahead of time and use it for the single values where possible.
	 * (This is used the the normal search case, but not in the
	 * index case because of caller requirements).
	 */
	if (flags & LDB_UNPACK_DATA_FLAG_NO_VALUES_ALLOC) {
		ldb_val_single_array = talloc_array(message->elements,
						    struct ldb_val,
						    message->num_elements);
		if (ldb_val_single_array == NULL) {
			errno = ENOMEM;
			goto failed;
		}
	}

	q = p + PULL_LE_U32(p, 0);
	value_section_p = q;
	p += U32_LEN;

	for (i=0;i<message->num_elements;i++) {
		const char *attr = NULL;
		size_t attr_len;
		struct ldb_message_element *element = NULL;

		/* Sanity check: minimum element size */
		if (p + (U32_LEN * 2) + /* attr name len, num values */
			(U8_LEN * 2) + /* value length width, one val length */
			(NULL_PAD_BYTE_LEN * 2) /* null for attr name + val */
			> value_section_p) {
			errno = EIO;
			goto failed;
		}

		attr_len = PULL_LE_U32(p, 0);
		p += U32_LEN;

		if (attr_len == 0) {
			errno = EIO;
			goto failed;
		}
		attr = (char *)p;

		p += attr_len + NULL_PAD_BYTE_LEN;
		/*
		 * num_values, val_len_width
		 *
		 * val_len_width is the width specifier
		 * for the variable length encoding
		 */
		if (p + U32_LEN + U8_LEN > value_section_p) {
			errno = EIO;
			goto failed;
		}

		if (*(p-NULL_PAD_BYTE_LEN) != '\0') {
			errno = EINVAL;
			goto failed;
		}

		element = &message->elements[nelem];
		element->name = attr;
		element->flags = 0;

		element->num_values = PULL_LE_U32(p, 0);
		element->values = NULL;
		if ((flags & LDB_UNPACK_DATA_FLAG_NO_VALUES_ALLOC) &&
		    element->num_values == 1) {
			element->values = &ldb_val_single_array[nelem];
		} else if (element->num_values != 0) {
			element->values = talloc_array(message->elements,
						       struct ldb_val,
						       element->num_values);
			if (!element->values) {
				errno = ENOMEM;
				goto failed;
			}
		}

		p += U32_LEN;

		/*
		 * Here we read how wide the remaining lengths are
		 * which avoids storing and parsing a lot of leading
		 * 0s
		 */
		val_len_width = *p;
		p += U8_LEN;

		if (p + val_len_width * element->num_values >
		    value_section_p) {
			errno = EIO;
			goto failed;
		}

		/*
		 * This is structured weird for compiler optimization
		 * purposes, but we need to pull the array of widths
		 * with different macros depending on how wide the
		 * biggest one is (specified by val_len_width)
		 */
		if (val_len_width == U8_LEN) {
			for (j = 0; j < element->num_values; j++) {
				element->values[j].length = PULL_LE_U8(p, 0);
				p += U8_LEN;
			}
		} else if (val_len_width == U16_LEN) {
			for (j = 0; j < element->num_values; j++) {
				element->values[j].length = PULL_LE_U16(p, 0);
				p += U16_LEN;
			}
		} else if (val_len_width == U32_LEN) {
			for (j = 0; j < element->num_values; j++) {
				element->values[j].length = PULL_LE_U32(p, 0);
				p += U32_LEN;
			}
		} else {
			errno = ERANGE;
			goto failed;
		}

		for (j = 0; j < element->num_values; j++) {
			len = element->values[j].length;
			if (len + NULL_PAD_BYTE_LEN < len) {
				errno = EIO;
				goto failed;
			}
			if (q + len + NULL_PAD_BYTE_LEN > end_p) {
				errno = EIO;
				goto failed;
			}

			element->values[j].data = q;
			q += len + NULL_PAD_BYTE_LEN;
		}
		nelem++;
	}

	/*
	 * If p isn't now pointing at the beginning of the value section,
	 * something went very wrong.
	 */
	if (p != value_section_p) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "Error: Data corruption in ldb_unpack_data_flags");
		errno = EIO;
		goto failed;
	}

	/*
	 * Adapt the number of elements to the real number of unpacked
	 * elements it means that we overallocated elements array.
	 */
	message->num_elements = nelem;

	/*
	 * Shrink the allocated size.  On current talloc behaviour
	 * this will help if we skipped 32 or more attributes.
	 */
	message->elements = talloc_realloc(message, message->elements,
					   struct ldb_message_element,
					   message->num_elements);

	if (q != end_p) {
		ldb_debug(ldb, LDB_DEBUG_ERROR,
			  "Error: %zu bytes unread in ldb_unpack_data_flags",
			  end_p - q);
		errno = EIO;
		goto failed;
	}

	return 0;

failed:
	talloc_free(message->elements);
	return -1;
}

int ldb_unpack_get_format(const struct ldb_val *data,
			  uint32_t *pack_format_version)
{
	if (data->length < U32_LEN) {
		return LDB_ERR_OPERATIONS_ERROR;
	}
	*pack_format_version = PULL_LE_U32(data->data, 0);
	return LDB_SUCCESS;
}

/*
 * Unpack a ldb message from a linear buffer in ldb_val
 */
int ldb_unpack_data_flags(struct ldb_context *ldb,
			  const struct ldb_val *data,
			  struct ldb_message *message,
			  unsigned int flags)
{
	unsigned format;

	if (data->length < U32_LEN) {
		errno = EIO;
		return -1;
	}

	format = PULL_LE_U32(data->data, 0);
	if (format == LDB_PACKING_FORMAT_V2) {
		return ldb_unpack_data_flags_v2(ldb, data, message, flags);
	}

	/*
	 * The v1 function we're about to call takes either LDB_PACKING_FORMAT
	 * or LDB_PACKING_FORMAT_NODN packing format versions, and will error
	 * if given some other version, so we don't need to do any further
	 * checks on 'format'.
	 */
	return ldb_unpack_data_flags_v1(ldb, data, message, flags, format);
}


/*
 * Unpack a ldb message from a linear buffer in ldb_val
 *
 * Free with ldb_unpack_data_free()
 */
int ldb_unpack_data(struct ldb_context *ldb,
		    const struct ldb_val *data,
		    struct ldb_message *message)
{
	return ldb_unpack_data_flags(ldb, data, message, 0);
}

/*
  add the special distinguishedName element
*/
static int msg_add_distinguished_name(struct ldb_message *msg)
{
	const char *dn_attr = "distinguishedName";
	char *dn = NULL;

	if (ldb_msg_find_element(msg, dn_attr)) {
		/*
		 * This should not happen, but this is
		 * existing behaviour...
		 */
		return LDB_SUCCESS;
	}

	dn = ldb_dn_alloc_linearized(msg, msg->dn);
	if (dn == NULL) {
		return LDB_ERR_OPERATIONS_ERROR;
	}

	return ldb_msg_add_steal_string(msg, dn_attr, dn);
}

/*
 * filter the specified list of attributes from msg,
 * adding requested attributes, and perhaps all for *,
 * but not the DN to filtered_msg.
 */
int ldb_filter_attrs(struct ldb_context *ldb,
		     const struct ldb_message *msg,
		     const char *const *attrs,
		     struct ldb_message *filtered_msg)
{
	unsigned int i;
	bool keep_all = false;
	bool add_dn = false;
	uint32_t num_elements;
	uint32_t elements_size;

	if (attrs) {
		/* check for special attrs */
		for (i = 0; attrs[i]; i++) {
			int cmp = strcmp(attrs[i], "*");
			if (cmp == 0) {
				keep_all = true;
				break;
			}
			cmp = ldb_attr_cmp(attrs[i], "distinguishedName");
			if (cmp == 0) {
				add_dn = true;
			}
		}
	} else {
		keep_all = true;
	}

	if (keep_all) {
		add_dn = true;
		elements_size = msg->num_elements + 1;

	/* Shortcuts for the simple cases */
	} else if (add_dn && i == 1) {
		if (msg_add_distinguished_name(filtered_msg) != 0) {
			goto failed;
		}
		return 0;
	} else if (i == 0) {
		return 0;

	/* Otherwise we are copying at most as many element as we have attributes */
	} else {
		elements_size = i;
	}

	filtered_msg->elements = talloc_array(filtered_msg,
					      struct ldb_message_element,
					      elements_size);
	if (filtered_msg->elements == NULL) goto failed;

	num_elements = 0;

	for (i = 0; i < msg->num_elements; i++) {
		struct ldb_message_element *el = &msg->elements[i];
		struct ldb_message_element *el2 = &filtered_msg->elements[num_elements];
		unsigned int j;

		if (keep_all == false) {
			bool found = false;
			for (j = 0; attrs[j]; j++) {
				int cmp = ldb_attr_cmp(el->name, attrs[j]);
				if (cmp == 0) {
					found = true;
					break;
				}
			}
			if (found == false) {
				continue;
			}
		}
		*el2 = *el;
		el2->name = talloc_strdup(filtered_msg->elements,
					  el->name);
		if (el2->name == NULL) {
			goto failed;
		}
		el2->values = talloc_array(filtered_msg->elements,
					   struct ldb_val, el->num_values);
		if (el2->values == NULL) {
			goto failed;
		}
		for (j=0;j<el->num_values;j++) {
			el2->values[j] = ldb_val_dup(el2->values, &el->values[j]);
			if (el2->values[j].data == NULL && el->values[j].length != 0) {
				goto failed;
			}
		}
		num_elements++;

		/* Pidginhole principle: we can't have more elements
		 * than the number of attributes if they are unique in
		 * the DB */
		if (num_elements > elements_size) {
			goto failed;
		}
	}

	filtered_msg->num_elements = num_elements;

	if (add_dn) {
		if (msg_add_distinguished_name(filtered_msg) != 0) {
			goto failed;
		}
	}

	if (filtered_msg->num_elements > 0) {
		filtered_msg->elements
			= talloc_realloc(filtered_msg,
					 filtered_msg->elements,
					 struct ldb_message_element,
					 filtered_msg->num_elements);
		if (filtered_msg->elements == NULL) {
			goto failed;
		}
	} else {
		talloc_free(filtered_msg->elements);
		filtered_msg->elements = NULL;
	}

	return 0;
failed:
	return -1;
}