xref: /netbsd-src/external/bsd/file/dist/src/cdf.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: cdf.c,v 1.16 2018/04/15 19:45:32 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 2008 Christos Zoulas
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28 /*
29  * Parse Composite Document Files, the format used in Microsoft Office
30  * document files before they switched to zipped XML.
31  * Info from: http://sc.openoffice.org/compdocfileformat.pdf
32  *
33  * N.B. This is the "Composite Document File" format, and not the
34  * "Compound Document Format", nor the "Channel Definition Format".
35  */
36 
37 #include "file.h"
38 
39 #ifndef lint
40 #if 0
41 FILE_RCSID("@(#)$File: cdf.c,v 1.110 2017/12/19 00:21:21 christos Exp $")
42 #else
43 __RCSID("$NetBSD: cdf.c,v 1.16 2018/04/15 19:45:32 christos Exp $");
44 #endif
45 #endif
46 
47 #include <assert.h>
48 #ifdef CDF_DEBUG
49 #include <err.h>
50 #endif
51 #include <stdlib.h>
52 #include <unistd.h>
53 #include <string.h>
54 #include <time.h>
55 #include <ctype.h>
56 #ifdef HAVE_LIMITS_H
57 #include <limits.h>
58 #endif
59 
60 #ifndef EFTYPE
61 #define EFTYPE EINVAL
62 #endif
63 
64 #include "cdf.h"
65 
66 #ifdef CDF_DEBUG
67 #define DPRINTF(a) printf a, fflush(stdout)
68 #else
69 #define DPRINTF(a)
70 #endif
71 
72 static union {
73 	char s[4];
74 	uint32_t u;
75 } cdf_bo;
76 
77 #define NEED_SWAP	(cdf_bo.u == (uint32_t)0x01020304)
78 
79 #define CDF_TOLE8(x)	((uint64_t)(NEED_SWAP ? _cdf_tole8(x) : (uint64_t)(x)))
80 #define CDF_TOLE4(x)	((uint32_t)(NEED_SWAP ? _cdf_tole4(x) : (uint32_t)(x)))
81 #define CDF_TOLE2(x)	((uint16_t)(NEED_SWAP ? _cdf_tole2(x) : (uint16_t)(x)))
82 #define CDF_TOLE(x)	(/*CONSTCOND*/sizeof(x) == 2 ? \
83 			    CDF_TOLE2(CAST(uint16_t, x)) : \
84 			(/*CONSTCOND*/sizeof(x) == 4 ? \
85 			    CDF_TOLE4(CAST(uint32_t, x)) : \
86 			    CDF_TOLE8(CAST(uint64_t, x))))
87 #define CDF_GETUINT32(x, y)	cdf_getuint32(x, y)
88 
89 #define CDF_MALLOC(n) cdf_malloc(__FILE__, __LINE__, (n))
90 #define CDF_REALLOC(p, n) cdf_realloc(__FILE__, __LINE__, (p), (n))
91 #define CDF_CALLOC(n, u) cdf_calloc(__FILE__, __LINE__, (n), (u))
92 
93 
94 /*ARGSUSED*/
95 static void *
96 cdf_malloc(const char *file __attribute__((__unused__)),
97     size_t line __attribute__((__unused__)), size_t n)
98 {
99 	DPRINTF(("%s,%zu: %s %zu\n", file, line, __func__, n));
100 	return malloc(n);
101 }
102 
103 /*ARGSUSED*/
104 static void *
105 cdf_realloc(const char *file __attribute__((__unused__)),
106     size_t line __attribute__((__unused__)), void *p, size_t n)
107 {
108 	DPRINTF(("%s,%zu: %s %zu\n", file, line, __func__, n));
109 	return realloc(p, n);
110 }
111 
112 /*ARGSUSED*/
113 static void *
114 cdf_calloc(const char *file __attribute__((__unused__)),
115     size_t line __attribute__((__unused__)), size_t n, size_t u)
116 {
117 	DPRINTF(("%s,%zu: %s %zu %zu\n", file, line, __func__, n, u));
118 	return calloc(n, u);
119 }
120 
121 /*
122  * swap a short
123  */
124 static uint16_t
125 _cdf_tole2(uint16_t sv)
126 {
127 	uint16_t rv;
128 	uint8_t *s = (uint8_t *)(void *)&sv;
129 	uint8_t *d = (uint8_t *)(void *)&rv;
130 	d[0] = s[1];
131 	d[1] = s[0];
132 	return rv;
133 }
134 
135 /*
136  * swap an int
137  */
138 static uint32_t
139 _cdf_tole4(uint32_t sv)
140 {
141 	uint32_t rv;
142 	uint8_t *s = (uint8_t *)(void *)&sv;
143 	uint8_t *d = (uint8_t *)(void *)&rv;
144 	d[0] = s[3];
145 	d[1] = s[2];
146 	d[2] = s[1];
147 	d[3] = s[0];
148 	return rv;
149 }
150 
151 /*
152  * swap a quad
153  */
154 static uint64_t
155 _cdf_tole8(uint64_t sv)
156 {
157 	uint64_t rv;
158 	uint8_t *s = (uint8_t *)(void *)&sv;
159 	uint8_t *d = (uint8_t *)(void *)&rv;
160 	d[0] = s[7];
161 	d[1] = s[6];
162 	d[2] = s[5];
163 	d[3] = s[4];
164 	d[4] = s[3];
165 	d[5] = s[2];
166 	d[6] = s[1];
167 	d[7] = s[0];
168 	return rv;
169 }
170 
171 /*
172  * grab a uint32_t from a possibly unaligned address, and return it in
173  * the native host order.
174  */
175 static uint32_t
176 cdf_getuint32(const uint8_t *p, size_t offs)
177 {
178 	uint32_t rv;
179 	(void)memcpy(&rv, p + offs * sizeof(uint32_t), sizeof(rv));
180 	return CDF_TOLE4(rv);
181 }
182 
183 #define CDF_UNPACK(a)	\
184     (void)memcpy(&(a), &buf[len], sizeof(a)), len += sizeof(a)
185 #define CDF_UNPACKA(a)	\
186     (void)memcpy((a), &buf[len], sizeof(a)), len += sizeof(a)
187 
188 uint16_t
189 cdf_tole2(uint16_t sv)
190 {
191 	return CDF_TOLE2(sv);
192 }
193 
194 uint32_t
195 cdf_tole4(uint32_t sv)
196 {
197 	return CDF_TOLE4(sv);
198 }
199 
200 uint64_t
201 cdf_tole8(uint64_t sv)
202 {
203 	return CDF_TOLE8(sv);
204 }
205 
206 void
207 cdf_swap_header(cdf_header_t *h)
208 {
209 	size_t i;
210 
211 	h->h_magic = CDF_TOLE8(h->h_magic);
212 	h->h_uuid[0] = CDF_TOLE8(h->h_uuid[0]);
213 	h->h_uuid[1] = CDF_TOLE8(h->h_uuid[1]);
214 	h->h_revision = CDF_TOLE2(h->h_revision);
215 	h->h_version = CDF_TOLE2(h->h_version);
216 	h->h_byte_order = CDF_TOLE2(h->h_byte_order);
217 	h->h_sec_size_p2 = CDF_TOLE2(h->h_sec_size_p2);
218 	h->h_short_sec_size_p2 = CDF_TOLE2(h->h_short_sec_size_p2);
219 	h->h_num_sectors_in_sat = CDF_TOLE4(h->h_num_sectors_in_sat);
220 	h->h_secid_first_directory = CDF_TOLE4(h->h_secid_first_directory);
221 	h->h_min_size_standard_stream =
222 	    CDF_TOLE4(h->h_min_size_standard_stream);
223 	h->h_secid_first_sector_in_short_sat =
224 	    CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_short_sat);
225 	h->h_num_sectors_in_short_sat =
226 	    CDF_TOLE4(h->h_num_sectors_in_short_sat);
227 	h->h_secid_first_sector_in_master_sat =
228 	    CDF_TOLE4((uint32_t)h->h_secid_first_sector_in_master_sat);
229 	h->h_num_sectors_in_master_sat =
230 	    CDF_TOLE4(h->h_num_sectors_in_master_sat);
231 	for (i = 0; i < __arraycount(h->h_master_sat); i++)
232 		h->h_master_sat[i] = CDF_TOLE4((uint32_t)h->h_master_sat[i]);
233 }
234 
235 void
236 cdf_unpack_header(cdf_header_t *h, char *buf)
237 {
238 	size_t i;
239 	size_t len = 0;
240 
241 	CDF_UNPACK(h->h_magic);
242 	CDF_UNPACKA(h->h_uuid);
243 	CDF_UNPACK(h->h_revision);
244 	CDF_UNPACK(h->h_version);
245 	CDF_UNPACK(h->h_byte_order);
246 	CDF_UNPACK(h->h_sec_size_p2);
247 	CDF_UNPACK(h->h_short_sec_size_p2);
248 	CDF_UNPACKA(h->h_unused0);
249 	CDF_UNPACK(h->h_num_sectors_in_sat);
250 	CDF_UNPACK(h->h_secid_first_directory);
251 	CDF_UNPACKA(h->h_unused1);
252 	CDF_UNPACK(h->h_min_size_standard_stream);
253 	CDF_UNPACK(h->h_secid_first_sector_in_short_sat);
254 	CDF_UNPACK(h->h_num_sectors_in_short_sat);
255 	CDF_UNPACK(h->h_secid_first_sector_in_master_sat);
256 	CDF_UNPACK(h->h_num_sectors_in_master_sat);
257 	for (i = 0; i < __arraycount(h->h_master_sat); i++)
258 		CDF_UNPACK(h->h_master_sat[i]);
259 }
260 
261 void
262 cdf_swap_dir(cdf_directory_t *d)
263 {
264 	d->d_namelen = CDF_TOLE2(d->d_namelen);
265 	d->d_left_child = CDF_TOLE4((uint32_t)d->d_left_child);
266 	d->d_right_child = CDF_TOLE4((uint32_t)d->d_right_child);
267 	d->d_storage = CDF_TOLE4((uint32_t)d->d_storage);
268 	d->d_storage_uuid[0] = CDF_TOLE8(d->d_storage_uuid[0]);
269 	d->d_storage_uuid[1] = CDF_TOLE8(d->d_storage_uuid[1]);
270 	d->d_flags = CDF_TOLE4(d->d_flags);
271 	d->d_created = CDF_TOLE8((uint64_t)d->d_created);
272 	d->d_modified = CDF_TOLE8((uint64_t)d->d_modified);
273 	d->d_stream_first_sector = CDF_TOLE4((uint32_t)d->d_stream_first_sector);
274 	d->d_size = CDF_TOLE4(d->d_size);
275 }
276 
277 void
278 cdf_swap_class(cdf_classid_t *d)
279 {
280 	d->cl_dword = CDF_TOLE4(d->cl_dword);
281 	d->cl_word[0] = CDF_TOLE2(d->cl_word[0]);
282 	d->cl_word[1] = CDF_TOLE2(d->cl_word[1]);
283 }
284 
285 void
286 cdf_unpack_dir(cdf_directory_t *d, char *buf)
287 {
288 	size_t len = 0;
289 
290 	CDF_UNPACKA(d->d_name);
291 	CDF_UNPACK(d->d_namelen);
292 	CDF_UNPACK(d->d_type);
293 	CDF_UNPACK(d->d_color);
294 	CDF_UNPACK(d->d_left_child);
295 	CDF_UNPACK(d->d_right_child);
296 	CDF_UNPACK(d->d_storage);
297 	CDF_UNPACKA(d->d_storage_uuid);
298 	CDF_UNPACK(d->d_flags);
299 	CDF_UNPACK(d->d_created);
300 	CDF_UNPACK(d->d_modified);
301 	CDF_UNPACK(d->d_stream_first_sector);
302 	CDF_UNPACK(d->d_size);
303 	CDF_UNPACK(d->d_unused0);
304 }
305 
306 int
307 cdf_zero_stream(cdf_stream_t *scn)
308 {
309 	scn->sst_len = 0;
310 	scn->sst_dirlen = 0;
311 	scn->sst_ss = 0;
312 	free(scn->sst_tab);
313 	scn->sst_tab = NULL;
314 	return -1;
315 }
316 
317 static size_t
318 cdf_check_stream(const cdf_stream_t *sst, const cdf_header_t *h)
319 {
320 	size_t ss = sst->sst_dirlen < h->h_min_size_standard_stream ?
321 	    CDF_SHORT_SEC_SIZE(h) : CDF_SEC_SIZE(h);
322 	assert(ss == sst->sst_ss);
323 	return sst->sst_ss;
324 }
325 
326 static int
327 cdf_check_stream_offset(const cdf_stream_t *sst, const cdf_header_t *h,
328     const void *p, size_t tail, int line)
329 {
330 	const char *b = (const char *)sst->sst_tab;
331 	const char *e = ((const char *)p) + tail;
332 	size_t ss = cdf_check_stream(sst, h);
333 	/*LINTED*/(void)&line;
334 	if (e >= b && (size_t)(e - b) <= ss * sst->sst_len)
335 		return 0;
336 	DPRINTF(("%d: offset begin %p < end %p || %" SIZE_T_FORMAT "u"
337 	    " > %" SIZE_T_FORMAT "u [%" SIZE_T_FORMAT "u %"
338 	    SIZE_T_FORMAT "u]\n", line, b, e, (size_t)(e - b),
339 	    ss * sst->sst_len, ss, sst->sst_len));
340 	errno = EFTYPE;
341 	return -1;
342 }
343 
344 static ssize_t
345 cdf_read(const cdf_info_t *info, off_t off, void *buf, size_t len)
346 {
347 	size_t siz = (size_t)off + len;
348 
349 	if ((off_t)(off + len) != (off_t)siz)
350 		goto out;
351 
352 	if (info->i_buf != NULL && info->i_len >= siz) {
353 		(void)memcpy(buf, &info->i_buf[off], len);
354 		return (ssize_t)len;
355 	}
356 
357 	if (info->i_fd == -1)
358 		goto out;
359 
360 	if (pread(info->i_fd, buf, len, off) != (ssize_t)len)
361 		return -1;
362 
363 	return (ssize_t)len;
364 out:
365 	errno = EINVAL;
366 	return -1;
367 }
368 
369 int
370 cdf_read_header(const cdf_info_t *info, cdf_header_t *h)
371 {
372 	char buf[512];
373 
374 	(void)memcpy(cdf_bo.s, "\01\02\03\04", 4);
375 	if (cdf_read(info, (off_t)0, buf, sizeof(buf)) == -1)
376 		return -1;
377 	cdf_unpack_header(h, buf);
378 	cdf_swap_header(h);
379 	if (h->h_magic != CDF_MAGIC) {
380 		DPRINTF(("Bad magic %#" INT64_T_FORMAT "x != %#"
381 		    INT64_T_FORMAT "x\n",
382 		    (unsigned long long)h->h_magic,
383 		    (unsigned long long)CDF_MAGIC));
384 		goto out;
385 	}
386 	if (h->h_sec_size_p2 > 20) {
387 		DPRINTF(("Bad sector size %hu\n", h->h_sec_size_p2));
388 		goto out;
389 	}
390 	if (h->h_short_sec_size_p2 > 20) {
391 		DPRINTF(("Bad short sector size %hu\n",
392 		    h->h_short_sec_size_p2));
393 		goto out;
394 	}
395 	return 0;
396 out:
397 	errno = EFTYPE;
398 	return -1;
399 }
400 
401 
402 ssize_t
403 cdf_read_sector(const cdf_info_t *info, void *buf, size_t offs, size_t len,
404     const cdf_header_t *h, cdf_secid_t id)
405 {
406 	size_t ss = CDF_SEC_SIZE(h);
407 	size_t pos = CDF_SEC_POS(h, id);
408 	assert(ss == len);
409 	return cdf_read(info, (off_t)pos, ((char *)buf) + offs, len);
410 }
411 
412 ssize_t
413 cdf_read_short_sector(const cdf_stream_t *sst, void *buf, size_t offs,
414     size_t len, const cdf_header_t *h, cdf_secid_t id)
415 {
416 	size_t ss = CDF_SHORT_SEC_SIZE(h);
417 	size_t pos = CDF_SHORT_SEC_POS(h, id);
418 	assert(ss == len);
419 	if (pos + len > CDF_SEC_SIZE(h) * sst->sst_len) {
420 		DPRINTF(("Out of bounds read %" SIZE_T_FORMAT "u > %"
421 		    SIZE_T_FORMAT "u\n",
422 		    pos + len, CDF_SEC_SIZE(h) * sst->sst_len));
423 		goto out;
424 	}
425 	(void)memcpy(((char *)buf) + offs,
426 	    ((const char *)sst->sst_tab) + pos, len);
427 	return len;
428 out:
429 	errno = EFTYPE;
430 	return -1;
431 }
432 
433 /*
434  * Read the sector allocation table.
435  */
436 int
437 cdf_read_sat(const cdf_info_t *info, cdf_header_t *h, cdf_sat_t *sat)
438 {
439 	size_t i, j, k;
440 	size_t ss = CDF_SEC_SIZE(h);
441 	cdf_secid_t *msa, mid, sec;
442 	size_t nsatpersec = (ss / sizeof(mid)) - 1;
443 
444 	for (i = 0; i < __arraycount(h->h_master_sat); i++)
445 		if (h->h_master_sat[i] == CDF_SECID_FREE)
446 			break;
447 
448 #define CDF_SEC_LIMIT (UINT32_MAX / (64 * ss))
449 	if ((nsatpersec > 0 &&
450 	    h->h_num_sectors_in_master_sat > CDF_SEC_LIMIT / nsatpersec) ||
451 	    i > CDF_SEC_LIMIT) {
452 		DPRINTF(("Number of sectors in master SAT too big %u %"
453 		    SIZE_T_FORMAT "u\n", h->h_num_sectors_in_master_sat, i));
454 		errno = EFTYPE;
455 		return -1;
456 	}
457 
458 	sat->sat_len = h->h_num_sectors_in_master_sat * nsatpersec + i;
459 	DPRINTF(("sat_len = %" SIZE_T_FORMAT "u ss = %" SIZE_T_FORMAT "u\n",
460 	    sat->sat_len, ss));
461 	if ((sat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(sat->sat_len, ss)))
462 	    == NULL)
463 		return -1;
464 
465 	for (i = 0; i < __arraycount(h->h_master_sat); i++) {
466 		if (h->h_master_sat[i] < 0)
467 			break;
468 		if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
469 		    h->h_master_sat[i]) != (ssize_t)ss) {
470 			DPRINTF(("Reading sector %d", h->h_master_sat[i]));
471 			goto out1;
472 		}
473 	}
474 
475 	if ((msa = CAST(cdf_secid_t *, CDF_CALLOC(1, ss))) == NULL)
476 		goto out1;
477 
478 	mid = h->h_secid_first_sector_in_master_sat;
479 	for (j = 0; j < h->h_num_sectors_in_master_sat; j++) {
480 		if (mid < 0)
481 			goto out;
482 		if (j >= CDF_LOOP_LIMIT) {
483 			DPRINTF(("Reading master sector loop limit"));
484 			goto out3;
485 		}
486 		if (cdf_read_sector(info, msa, 0, ss, h, mid) != (ssize_t)ss) {
487 			DPRINTF(("Reading master sector %d", mid));
488 			goto out2;
489 		}
490 		for (k = 0; k < nsatpersec; k++, i++) {
491 			sec = CDF_TOLE4((uint32_t)msa[k]);
492 			if (sec < 0)
493 				goto out;
494 			if (i >= sat->sat_len) {
495 			    DPRINTF(("Out of bounds reading MSA %" SIZE_T_FORMAT
496 				"u >= %" SIZE_T_FORMAT "u", i, sat->sat_len));
497 			    goto out3;
498 			}
499 			if (cdf_read_sector(info, sat->sat_tab, ss * i, ss, h,
500 			    sec) != (ssize_t)ss) {
501 				DPRINTF(("Reading sector %d",
502 				    CDF_TOLE4(msa[k])));
503 				goto out2;
504 			}
505 		}
506 		mid = CDF_TOLE4((uint32_t)msa[nsatpersec]);
507 	}
508 out:
509 	sat->sat_len = i;
510 	free(msa);
511 	return 0;
512 out3:
513 	errno = EFTYPE;
514 out2:
515 	free(msa);
516 out1:
517 	free(sat->sat_tab);
518 	return -1;
519 }
520 
521 size_t
522 cdf_count_chain(const cdf_sat_t *sat, cdf_secid_t sid, size_t size)
523 {
524 	size_t i, j;
525 	cdf_secid_t maxsector = (cdf_secid_t)((sat->sat_len * size)
526 	    / sizeof(maxsector));
527 
528 	DPRINTF(("Chain:"));
529 	if (sid == CDF_SECID_END_OF_CHAIN) {
530 		/* 0-length chain. */
531 		DPRINTF((" empty\n"));
532 		return 0;
533 	}
534 
535 	for (j = i = 0; sid >= 0; i++, j++) {
536 		DPRINTF((" %d", sid));
537 		if (j >= CDF_LOOP_LIMIT) {
538 			DPRINTF(("Counting chain loop limit"));
539 			goto out;
540 		}
541 		if (sid >= maxsector) {
542 			DPRINTF(("Sector %d >= %d\n", sid, maxsector));
543 			goto out;
544 		}
545 		sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
546 	}
547 	if (i == 0) {
548 		DPRINTF((" none, sid: %d\n", sid));
549 		goto out;
550 
551 	}
552 	DPRINTF(("\n"));
553 	return i;
554 out:
555 	errno = EFTYPE;
556 	return (size_t)-1;
557 }
558 
559 int
560 cdf_read_long_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
561     const cdf_sat_t *sat, cdf_secid_t sid, size_t len, cdf_stream_t *scn)
562 {
563 	size_t ss = CDF_SEC_SIZE(h), i, j;
564 	ssize_t nr;
565 	scn->sst_tab = NULL;
566 	scn->sst_len = cdf_count_chain(sat, sid, ss);
567 	scn->sst_dirlen = MAX(h->h_min_size_standard_stream, len);
568 	scn->sst_ss = ss;
569 
570 	if (sid == CDF_SECID_END_OF_CHAIN || len == 0)
571 		return cdf_zero_stream(scn);
572 
573 	if (scn->sst_len == (size_t)-1)
574 		goto out;
575 
576 	scn->sst_tab = CDF_CALLOC(scn->sst_len, ss);
577 	if (scn->sst_tab == NULL)
578 		return cdf_zero_stream(scn);
579 
580 	for (j = i = 0; sid >= 0; i++, j++) {
581 		if (j >= CDF_LOOP_LIMIT) {
582 			DPRINTF(("Read long sector chain loop limit"));
583 			goto out;
584 		}
585 		if (i >= scn->sst_len) {
586 			DPRINTF(("Out of bounds reading long sector chain "
587 			    "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
588 			    scn->sst_len));
589 			goto out;
590 		}
591 		if ((nr = cdf_read_sector(info, scn->sst_tab, i * ss, ss, h,
592 		    sid)) != (ssize_t)ss) {
593 			if (i == scn->sst_len - 1 && nr > 0) {
594 				/* Last sector might be truncated */
595 				return 0;
596 			}
597 			DPRINTF(("Reading long sector chain %d", sid));
598 			goto out;
599 		}
600 		sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
601 	}
602 	return 0;
603 out:
604 	errno = EFTYPE;
605 	return cdf_zero_stream(scn);
606 }
607 
608 int
609 cdf_read_short_sector_chain(const cdf_header_t *h,
610     const cdf_sat_t *ssat, const cdf_stream_t *sst,
611     cdf_secid_t sid, size_t len, cdf_stream_t *scn)
612 {
613 	size_t ss = CDF_SHORT_SEC_SIZE(h), i, j;
614 	scn->sst_tab = NULL;
615 	scn->sst_len = cdf_count_chain(ssat, sid, CDF_SEC_SIZE(h));
616 	scn->sst_dirlen = len;
617 	scn->sst_ss = ss;
618 
619 	if (scn->sst_len == (size_t)-1)
620 		goto out;
621 
622 	scn->sst_tab = CDF_CALLOC(scn->sst_len, ss);
623 	if (scn->sst_tab == NULL)
624 		return cdf_zero_stream(scn);
625 
626 	for (j = i = 0; sid >= 0; i++, j++) {
627 		if (j >= CDF_LOOP_LIMIT) {
628 			DPRINTF(("Read short sector chain loop limit"));
629 			goto out;
630 		}
631 		if (i >= scn->sst_len) {
632 			DPRINTF(("Out of bounds reading short sector chain "
633 			    "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n",
634 			    i, scn->sst_len));
635 			goto out;
636 		}
637 		if (cdf_read_short_sector(sst, scn->sst_tab, i * ss, ss, h,
638 		    sid) != (ssize_t)ss) {
639 			DPRINTF(("Reading short sector chain %d", sid));
640 			goto out;
641 		}
642 		sid = CDF_TOLE4((uint32_t)ssat->sat_tab[sid]);
643 	}
644 	return 0;
645 out:
646 	errno = EFTYPE;
647 	return cdf_zero_stream(scn);
648 }
649 
650 int
651 cdf_read_sector_chain(const cdf_info_t *info, const cdf_header_t *h,
652     const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
653     cdf_secid_t sid, size_t len, cdf_stream_t *scn)
654 {
655 
656 	if (len < h->h_min_size_standard_stream && sst->sst_tab != NULL)
657 		return cdf_read_short_sector_chain(h, ssat, sst, sid, len,
658 		    scn);
659 	else
660 		return cdf_read_long_sector_chain(info, h, sat, sid, len, scn);
661 }
662 
663 int
664 cdf_read_dir(const cdf_info_t *info, const cdf_header_t *h,
665     const cdf_sat_t *sat, cdf_dir_t *dir)
666 {
667 	size_t i, j;
668 	size_t ss = CDF_SEC_SIZE(h), ns, nd;
669 	char *buf;
670 	cdf_secid_t sid = h->h_secid_first_directory;
671 
672 	ns = cdf_count_chain(sat, sid, ss);
673 	if (ns == (size_t)-1)
674 		return -1;
675 
676 	nd = ss / CDF_DIRECTORY_SIZE;
677 
678 	dir->dir_len = ns * nd;
679 	dir->dir_tab = CAST(cdf_directory_t *,
680 	    CDF_CALLOC(dir->dir_len, sizeof(dir->dir_tab[0])));
681 	if (dir->dir_tab == NULL)
682 		return -1;
683 
684 	if ((buf = CAST(char *, CDF_MALLOC(ss))) == NULL) {
685 		free(dir->dir_tab);
686 		return -1;
687 	}
688 
689 	for (j = i = 0; i < ns; i++, j++) {
690 		if (j >= CDF_LOOP_LIMIT) {
691 			DPRINTF(("Read dir loop limit"));
692 			goto out;
693 		}
694 		if (cdf_read_sector(info, buf, 0, ss, h, sid) != (ssize_t)ss) {
695 			DPRINTF(("Reading directory sector %d", sid));
696 			goto out;
697 		}
698 		for (j = 0; j < nd; j++) {
699 			cdf_unpack_dir(&dir->dir_tab[i * nd + j],
700 			    &buf[j * CDF_DIRECTORY_SIZE]);
701 		}
702 		sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
703 	}
704 	if (NEED_SWAP)
705 		for (i = 0; i < dir->dir_len; i++)
706 			cdf_swap_dir(&dir->dir_tab[i]);
707 	free(buf);
708 	return 0;
709 out:
710 	free(dir->dir_tab);
711 	free(buf);
712 	errno = EFTYPE;
713 	return -1;
714 }
715 
716 
717 int
718 cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h,
719     const cdf_sat_t *sat, cdf_sat_t *ssat)
720 {
721 	size_t i, j;
722 	size_t ss = CDF_SEC_SIZE(h);
723 	cdf_secid_t sid = h->h_secid_first_sector_in_short_sat;
724 
725 	ssat->sat_tab = NULL;
726 	ssat->sat_len = cdf_count_chain(sat, sid, ss);
727 	if (ssat->sat_len == (size_t)-1)
728 		goto out;
729 
730 	ssat->sat_tab = CAST(cdf_secid_t *, CDF_CALLOC(ssat->sat_len, ss));
731 	if (ssat->sat_tab == NULL)
732 		goto out1;
733 
734 	for (j = i = 0; sid >= 0; i++, j++) {
735 		if (j >= CDF_LOOP_LIMIT) {
736 			DPRINTF(("Read short sat sector loop limit"));
737 			goto out;
738 		}
739 		if (i >= ssat->sat_len) {
740 			DPRINTF(("Out of bounds reading short sector chain "
741 			    "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i,
742 			    ssat->sat_len));
743 			goto out;
744 		}
745 		if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) !=
746 		    (ssize_t)ss) {
747 			DPRINTF(("Reading short sat sector %d", sid));
748 			goto out1;
749 		}
750 		sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]);
751 	}
752 	return 0;
753 out:
754 	errno = EFTYPE;
755 out1:
756 	free(ssat->sat_tab);
757 	return -1;
758 }
759 
760 int
761 cdf_read_short_stream(const cdf_info_t *info, const cdf_header_t *h,
762     const cdf_sat_t *sat, const cdf_dir_t *dir, cdf_stream_t *scn,
763     const cdf_directory_t **root)
764 {
765 	size_t i;
766 	const cdf_directory_t *d;
767 
768 	*root = NULL;
769 	for (i = 0; i < dir->dir_len; i++)
770 		if (dir->dir_tab[i].d_type == CDF_DIR_TYPE_ROOT_STORAGE)
771 			break;
772 
773 	/* If the it is not there, just fake it; some docs don't have it */
774 	if (i == dir->dir_len) {
775 		DPRINTF(("Cannot find root storage dir\n"));
776 		goto out;
777 	}
778 	d = &dir->dir_tab[i];
779 	*root = d;
780 
781 	/* If the it is not there, just fake it; some docs don't have it */
782 	if (d->d_stream_first_sector < 0) {
783 		DPRINTF(("No first secror in dir\n"));
784 		goto out;
785 	}
786 
787 	return cdf_read_long_sector_chain(info, h, sat,
788 	    d->d_stream_first_sector, d->d_size, scn);
789 out:
790 	scn->sst_tab = NULL;
791 	(void)cdf_zero_stream(scn);
792 	return 0;
793 }
794 
795 static int
796 cdf_namecmp(const char *d, const uint16_t *s, size_t l)
797 {
798 	for (; l--; d++, s++)
799 		if (*d != CDF_TOLE2(*s))
800 			return (unsigned char)*d - CDF_TOLE2(*s);
801 	return 0;
802 }
803 
804 int
805 cdf_read_doc_summary_info(const cdf_info_t *info, const cdf_header_t *h,
806     const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
807     const cdf_dir_t *dir, cdf_stream_t *scn)
808 {
809 	return cdf_read_user_stream(info, h, sat, ssat, sst, dir,
810 	    "\05DocumentSummaryInformation", scn);
811 }
812 
813 int
814 cdf_read_summary_info(const cdf_info_t *info, const cdf_header_t *h,
815     const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
816     const cdf_dir_t *dir, cdf_stream_t *scn)
817 {
818 	return cdf_read_user_stream(info, h, sat, ssat, sst, dir,
819 	    "\05SummaryInformation", scn);
820 }
821 
822 int
823 cdf_read_user_stream(const cdf_info_t *info, const cdf_header_t *h,
824     const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
825     const cdf_dir_t *dir, const char *name, cdf_stream_t *scn)
826 {
827 	const cdf_directory_t *d;
828 	int i = cdf_find_stream(dir, name, CDF_DIR_TYPE_USER_STREAM);
829 
830 	if (i <= 0) {
831 		memset(scn, 0, sizeof(*scn));
832 		return -1;
833 	}
834 
835 	d = &dir->dir_tab[i - 1];
836 	return cdf_read_sector_chain(info, h, sat, ssat, sst,
837 	    d->d_stream_first_sector, d->d_size, scn);
838 }
839 
840 int
841 cdf_find_stream(const cdf_dir_t *dir, const char *name, int type)
842 {
843 	size_t i, name_len = strlen(name) + 1;
844 
845 	for (i = dir->dir_len; i > 0; i--)
846 		if (dir->dir_tab[i - 1].d_type == type &&
847 		    cdf_namecmp(name, dir->dir_tab[i - 1].d_name, name_len)
848 		    == 0)
849 			break;
850 	if (i > 0)
851 		return CAST(int, i);
852 
853 	DPRINTF(("Cannot find type %d `%s'\n", type, name));
854 	errno = ESRCH;
855 	return 0;
856 }
857 
858 #define CDF_SHLEN_LIMIT (UINT32_MAX / 64)
859 #define CDF_PROP_LIMIT (UINT32_MAX / (64 * sizeof(cdf_property_info_t)))
860 
861 static const void *
862 cdf_offset(const void *p, size_t l)
863 {
864 	return CAST(const void *, CAST(const uint8_t *, p) + l);
865 }
866 
867 static const uint8_t *
868 cdf_get_property_info_pos(const cdf_stream_t *sst, const cdf_header_t *h,
869     const uint8_t *p, const uint8_t *e, size_t i)
870 {
871 	size_t tail = (i << 1) + 1;
872 	size_t ofs;
873 	const uint8_t *q;
874 
875 	if (p >= e) {
876 		DPRINTF(("Past end %p < %p\n", e, p));
877 		return NULL;
878 	}
879 	if (cdf_check_stream_offset(sst, h, p, (tail + 1) * sizeof(uint32_t),
880 	    __LINE__) == -1)
881 		return NULL;
882 	ofs = CDF_GETUINT32(p, tail);
883 	q = CAST(const uint8_t *, cdf_offset(CAST(const void *, p),
884 	    ofs - 2 * sizeof(uint32_t)));
885 
886 	if (q < p) {
887 		DPRINTF(("Wrapped around %p < %p\n", q, p));
888 		return NULL;
889 	}
890 
891 	if (q >= e) {
892 		DPRINTF(("Ran off the end %p >= %p\n", q, e));
893 		return NULL;
894 	}
895 	return q;
896 }
897 
898 static cdf_property_info_t *
899 cdf_grow_info(cdf_property_info_t **info, size_t *maxcount, size_t incr)
900 {
901 	cdf_property_info_t *inp;
902 	size_t newcount = *maxcount + incr;
903 
904 	if (newcount > CDF_PROP_LIMIT) {
905 		DPRINTF(("exceeded property limit %zu > %zu\n",
906 		    newcount, CDF_PROP_LIMIT));
907 		goto out;
908 	}
909 	inp = CAST(cdf_property_info_t *,
910 	    CDF_REALLOC(*info, newcount * sizeof(*inp)));
911 	if (inp == NULL)
912 		goto out;
913 
914 	*info = inp;
915 	*maxcount = newcount;
916 	return inp;
917 out:
918 	free(*info);
919 	*maxcount = 0;
920 	*info = NULL;
921 	return NULL;
922 }
923 
924 static int
925 cdf_copy_info(cdf_property_info_t *inp, const void *p, const void *e,
926     size_t len)
927 {
928 	if (inp->pi_type & CDF_VECTOR)
929 		return 0;
930 
931 	if ((size_t)(CAST(const char *, e) - CAST(const char *, p)) < len)
932 		return 0;
933 
934 	(void)memcpy(&inp->pi_val, p, len);
935 
936 	switch (len) {
937 	case 2:
938 		inp->pi_u16 = CDF_TOLE2(inp->pi_u16);
939 		break;
940 	case 4:
941 		inp->pi_u32 = CDF_TOLE4(inp->pi_u32);
942 		break;
943 	case 8:
944 		inp->pi_u64 = CDF_TOLE8(inp->pi_u64);
945 		break;
946 	default:
947 		abort();
948 	}
949 	return 1;
950 }
951 
952 int
953 cdf_read_property_info(const cdf_stream_t *sst, const cdf_header_t *h,
954     uint32_t offs, cdf_property_info_t **info, size_t *count, size_t *maxcount)
955 {
956 	const cdf_section_header_t *shp;
957 	cdf_section_header_t sh;
958 	const uint8_t *p, *q, *e;
959 	size_t i, o4, nelements, j, slen, left;
960 	cdf_property_info_t *inp;
961 
962 	if (offs > UINT32_MAX / 4) {
963 		errno = EFTYPE;
964 		goto out;
965 	}
966 	shp = CAST(const cdf_section_header_t *,
967 	    cdf_offset(sst->sst_tab, offs));
968 	if (cdf_check_stream_offset(sst, h, shp, sizeof(*shp), __LINE__) == -1)
969 		goto out;
970 	sh.sh_len = CDF_TOLE4(shp->sh_len);
971 	if (sh.sh_len > CDF_SHLEN_LIMIT) {
972 		errno = EFTYPE;
973 		goto out;
974 	}
975 
976 	if (cdf_check_stream_offset(sst, h, shp, sh.sh_len, __LINE__) == -1)
977 		goto out;
978 
979 	sh.sh_properties = CDF_TOLE4(shp->sh_properties);
980 	DPRINTF(("section len: %u properties %u\n", sh.sh_len,
981 	    sh.sh_properties));
982 	if (sh.sh_properties > CDF_PROP_LIMIT)
983 		goto out;
984 	inp = cdf_grow_info(info, maxcount, sh.sh_properties);
985 	if (inp == NULL)
986 		goto out;
987 	inp += *count;
988 	*count += sh.sh_properties;
989 	p = CAST(const uint8_t *, cdf_offset(sst->sst_tab, offs + sizeof(sh)));
990 	e = CAST(const uint8_t *, cdf_offset(shp, sh.sh_len));
991 	if (p >= e || cdf_check_stream_offset(sst, h, e, 0, __LINE__) == -1)
992 		goto out;
993 
994 	for (i = 0; i < sh.sh_properties; i++) {
995 		if ((q = cdf_get_property_info_pos(sst, h, p, e, i)) == NULL)
996 			goto out;
997 		inp[i].pi_id = CDF_GETUINT32(p, i << 1);
998 		left = CAST(size_t, e - q);
999 		if (left < sizeof(uint32_t)) {
1000 			DPRINTF(("short info (no type)_\n"));
1001 			goto out;
1002 		}
1003 		inp[i].pi_type = CDF_GETUINT32(q, 0);
1004 		DPRINTF(("%" SIZE_T_FORMAT "u) id=%#x type=%#x offs=%#tx,%#x\n",
1005 		    i, inp[i].pi_id, inp[i].pi_type, q - p, offs));
1006 		if (inp[i].pi_type & CDF_VECTOR) {
1007 			if (left < sizeof(uint32_t) * 2) {
1008 				DPRINTF(("missing CDF_VECTOR length\n"));
1009 				goto out;
1010 			}
1011 			nelements = CDF_GETUINT32(q, 1);
1012 			if (nelements == 0) {
1013 				DPRINTF(("CDF_VECTOR with nelements == 0\n"));
1014 				goto out;
1015 			}
1016 			slen = 2;
1017 		} else {
1018 			nelements = 1;
1019 			slen = 1;
1020 		}
1021 		o4 = slen * sizeof(uint32_t);
1022 		if (inp[i].pi_type & (CDF_ARRAY|CDF_BYREF|CDF_RESERVED))
1023 			goto unknown;
1024 		switch (inp[i].pi_type & CDF_TYPEMASK) {
1025 		case CDF_NULL:
1026 		case CDF_EMPTY:
1027 			break;
1028 		case CDF_SIGNED16:
1029 			if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int16_t)))
1030 				goto unknown;
1031 			break;
1032 		case CDF_SIGNED32:
1033 		case CDF_BOOL:
1034 		case CDF_UNSIGNED32:
1035 		case CDF_FLOAT:
1036 			if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int32_t)))
1037 				goto unknown;
1038 			break;
1039 		case CDF_SIGNED64:
1040 		case CDF_UNSIGNED64:
1041 		case CDF_DOUBLE:
1042 		case CDF_FILETIME:
1043 			if (!cdf_copy_info(&inp[i], &q[o4], e, sizeof(int64_t)))
1044 				goto unknown;
1045 			break;
1046 		case CDF_LENGTH32_STRING:
1047 		case CDF_LENGTH32_WSTRING:
1048 			if (nelements > 1) {
1049 				size_t nelem = inp - *info;
1050 				inp = cdf_grow_info(info, maxcount, nelements);
1051 				if (inp == NULL)
1052 					goto out;
1053 				inp += nelem;
1054 			}
1055 			DPRINTF(("nelements = %" SIZE_T_FORMAT "u\n",
1056 			    nelements));
1057 			for (j = 0; j < nelements && i < sh.sh_properties;
1058 			    j++, i++)
1059 			{
1060 				uint32_t l;
1061 
1062 				if (o4 + sizeof(uint32_t) > left)
1063 					goto out;
1064 
1065 				l = CDF_GETUINT32(q, slen);
1066 				o4 += sizeof(uint32_t);
1067 				if (o4 + l > left)
1068 					goto out;
1069 
1070 				inp[i].pi_str.s_len = l;
1071 				inp[i].pi_str.s_buf = CAST(const char *,
1072 				    CAST(const void *, &q[o4]));
1073 
1074 				DPRINTF(("o=%zu l=%d(%" SIZE_T_FORMAT
1075 				    "u), t=%zu s=%s\n", o4, l,
1076 				    CDF_ROUND(l, sizeof(l)), left,
1077 				    inp[i].pi_str.s_buf));
1078 
1079 				if (l & 1)
1080 					l++;
1081 
1082 				slen += l >> 1;
1083 				o4 = slen * sizeof(uint32_t);
1084 			}
1085 			i--;
1086 			break;
1087 		case CDF_CLIPBOARD:
1088 			if (inp[i].pi_type & CDF_VECTOR)
1089 				goto unknown;
1090 			break;
1091 		default:
1092 		unknown:
1093 			memset(&inp[i].pi_val, 0, sizeof(inp[i].pi_val));
1094 			DPRINTF(("Don't know how to deal with %#x\n",
1095 			    inp[i].pi_type));
1096 			break;
1097 		}
1098 	}
1099 	return 0;
1100 out:
1101 	free(*info);
1102 	*info = NULL;
1103 	*count = 0;
1104 	*maxcount = 0;
1105 	errno = EFTYPE;
1106 	return -1;
1107 }
1108 
1109 int
1110 cdf_unpack_summary_info(const cdf_stream_t *sst, const cdf_header_t *h,
1111     cdf_summary_info_header_t *ssi, cdf_property_info_t **info, size_t *count)
1112 {
1113 	size_t maxcount;
1114 	const cdf_summary_info_header_t *si =
1115 	    CAST(const cdf_summary_info_header_t *, sst->sst_tab);
1116 	const cdf_section_declaration_t *sd =
1117 	    CAST(const cdf_section_declaration_t *, (const void *)
1118 	    ((const char *)sst->sst_tab + CDF_SECTION_DECLARATION_OFFSET));
1119 
1120 	if (cdf_check_stream_offset(sst, h, si, sizeof(*si), __LINE__) == -1 ||
1121 	    cdf_check_stream_offset(sst, h, sd, sizeof(*sd), __LINE__) == -1)
1122 		return -1;
1123 	ssi->si_byte_order = CDF_TOLE2(si->si_byte_order);
1124 	ssi->si_os_version = CDF_TOLE2(si->si_os_version);
1125 	ssi->si_os = CDF_TOLE2(si->si_os);
1126 	ssi->si_class = si->si_class;
1127 	cdf_swap_class(&ssi->si_class);
1128 	ssi->si_count = CDF_TOLE4(si->si_count);
1129 	*count = 0;
1130 	maxcount = 0;
1131 	*info = NULL;
1132 	if (cdf_read_property_info(sst, h, CDF_TOLE4(sd->sd_offset), info,
1133 	    count, &maxcount) == -1)
1134 		return -1;
1135 	return 0;
1136 }
1137 
1138 
1139 #define extract_catalog_field(t, f, l) \
1140     if (b + l + sizeof(cep->f) > eb) { \
1141 	    cep->ce_namlen = 0; \
1142 	    break; \
1143     } \
1144     memcpy(&cep->f, b + (l), sizeof(cep->f)); \
1145     ce[i].f = CAST(t, CDF_TOLE(cep->f))
1146 
1147 int
1148 cdf_unpack_catalog(const cdf_header_t *h, const cdf_stream_t *sst,
1149     cdf_catalog_t **cat)
1150 {
1151 	size_t ss = cdf_check_stream(sst, h);
1152 	const char *b = CAST(const char *, sst->sst_tab);
1153 	const char *nb, *eb = b + ss * sst->sst_len;
1154 	size_t nr, i, j, k;
1155 	cdf_catalog_entry_t *ce;
1156 	uint16_t reclen;
1157 	const uint16_t *np;
1158 
1159 	for (nr = 0;; nr++) {
1160 		memcpy(&reclen, b, sizeof(reclen));
1161 		reclen = CDF_TOLE2(reclen);
1162 		if (reclen == 0)
1163 			break;
1164 		b += reclen;
1165 		if (b > eb)
1166 		    break;
1167 	}
1168 	if (nr == 0)
1169 		return -1;
1170 	nr--;
1171 	*cat = CAST(cdf_catalog_t *,
1172 	    CDF_MALLOC(sizeof(cdf_catalog_t) + nr * sizeof(*ce)));
1173 	if (*cat == NULL)
1174 		return -1;
1175 	ce = (*cat)->cat_e;
1176 	memset(ce, 0, nr * sizeof(*ce));
1177 	b = CAST(const char *, sst->sst_tab);
1178 	for (j = i = 0; i < nr; b += reclen) {
1179 		cdf_catalog_entry_t *cep = &ce[j];
1180 		uint16_t rlen;
1181 
1182 		extract_catalog_field(uint16_t, ce_namlen, 0);
1183 		extract_catalog_field(uint16_t, ce_num, 4);
1184 		extract_catalog_field(uint64_t, ce_timestamp, 8);
1185 		reclen = cep->ce_namlen;
1186 
1187 		if (reclen < 14) {
1188 			cep->ce_namlen = 0;
1189 			continue;
1190 		}
1191 
1192 		cep->ce_namlen = __arraycount(cep->ce_name) - 1;
1193 		rlen = reclen - 14;
1194 		if (cep->ce_namlen > rlen)
1195 			cep->ce_namlen = rlen;
1196 
1197 		np = CAST(const uint16_t *, CAST(const void *, (b + 16)));
1198 		nb = CAST(const char *, CAST(const void *,
1199 		    (np + cep->ce_namlen)));
1200 		if (nb > eb) {
1201 			cep->ce_namlen = 0;
1202 			break;
1203 		}
1204 
1205 		for (k = 0; k < cep->ce_namlen; k++)
1206 			cep->ce_name[k] = np[k]; /* XXX: CDF_TOLE2? */
1207 		cep->ce_name[cep->ce_namlen] = 0;
1208 		j = i;
1209 		i++;
1210 	}
1211 	(*cat)->cat_num = j;
1212 	return 0;
1213 }
1214 
1215 int
1216 cdf_print_classid(char *buf, size_t buflen, const cdf_classid_t *id)
1217 {
1218 	return snprintf(buf, buflen, "%.8x-%.4x-%.4x-%.2x%.2x-"
1219 	    "%.2x%.2x%.2x%.2x%.2x%.2x", id->cl_dword, id->cl_word[0],
1220 	    id->cl_word[1], id->cl_two[0], id->cl_two[1], id->cl_six[0],
1221 	    id->cl_six[1], id->cl_six[2], id->cl_six[3], id->cl_six[4],
1222 	    id->cl_six[5]);
1223 }
1224 
1225 static const struct {
1226 	uint32_t v;
1227 	const char *n;
1228 } vn[] = {
1229 	{ CDF_PROPERTY_CODE_PAGE, "Code page" },
1230 	{ CDF_PROPERTY_TITLE, "Title" },
1231 	{ CDF_PROPERTY_SUBJECT, "Subject" },
1232 	{ CDF_PROPERTY_AUTHOR, "Author" },
1233 	{ CDF_PROPERTY_KEYWORDS, "Keywords" },
1234 	{ CDF_PROPERTY_COMMENTS, "Comments" },
1235 	{ CDF_PROPERTY_TEMPLATE, "Template" },
1236 	{ CDF_PROPERTY_LAST_SAVED_BY, "Last Saved By" },
1237 	{ CDF_PROPERTY_REVISION_NUMBER, "Revision Number" },
1238 	{ CDF_PROPERTY_TOTAL_EDITING_TIME, "Total Editing Time" },
1239 	{ CDF_PROPERTY_LAST_PRINTED, "Last Printed" },
1240 	{ CDF_PROPERTY_CREATE_TIME, "Create Time/Date" },
1241 	{ CDF_PROPERTY_LAST_SAVED_TIME, "Last Saved Time/Date" },
1242 	{ CDF_PROPERTY_NUMBER_OF_PAGES, "Number of Pages" },
1243 	{ CDF_PROPERTY_NUMBER_OF_WORDS, "Number of Words" },
1244 	{ CDF_PROPERTY_NUMBER_OF_CHARACTERS, "Number of Characters" },
1245 	{ CDF_PROPERTY_THUMBNAIL, "Thumbnail" },
1246 	{ CDF_PROPERTY_NAME_OF_APPLICATION, "Name of Creating Application" },
1247 	{ CDF_PROPERTY_SECURITY, "Security" },
1248 	{ CDF_PROPERTY_LOCALE_ID, "Locale ID" },
1249 };
1250 
1251 int
1252 cdf_print_property_name(char *buf, size_t bufsiz, uint32_t p)
1253 {
1254 	size_t i;
1255 
1256 	for (i = 0; i < __arraycount(vn); i++)
1257 		if (vn[i].v == p)
1258 			return snprintf(buf, bufsiz, "%s", vn[i].n);
1259 	return snprintf(buf, bufsiz, "%#x", p);
1260 }
1261 
1262 int
1263 cdf_print_elapsed_time(char *buf, size_t bufsiz, cdf_timestamp_t ts)
1264 {
1265 	int len = 0;
1266 	int days, hours, mins, secs;
1267 
1268 	ts /= CDF_TIME_PREC;
1269 	secs = (int)(ts % 60);
1270 	ts /= 60;
1271 	mins = (int)(ts % 60);
1272 	ts /= 60;
1273 	hours = (int)(ts % 24);
1274 	ts /= 24;
1275 	days = (int)ts;
1276 
1277 	if (days) {
1278 		len += snprintf(buf + len, bufsiz - len, "%dd+", days);
1279 		if ((size_t)len >= bufsiz)
1280 			return len;
1281 	}
1282 
1283 	if (days || hours) {
1284 		len += snprintf(buf + len, bufsiz - len, "%.2d:", hours);
1285 		if ((size_t)len >= bufsiz)
1286 			return len;
1287 	}
1288 
1289 	len += snprintf(buf + len, bufsiz - len, "%.2d:", mins);
1290 	if ((size_t)len >= bufsiz)
1291 		return len;
1292 
1293 	len += snprintf(buf + len, bufsiz - len, "%.2d", secs);
1294 	return len;
1295 }
1296 
1297 char *
1298 cdf_u16tos8(char *buf, size_t len, const uint16_t *p)
1299 {
1300 	size_t i;
1301 	for (i = 0; i < len && p[i]; i++)
1302 		buf[i] = (char)p[i];
1303 	buf[i] = '\0';
1304 	return buf;
1305 }
1306 
1307 #ifdef CDF_DEBUG
1308 void
1309 cdf_dump_header(const cdf_header_t *h)
1310 {
1311 	size_t i;
1312 
1313 #define DUMP(a, b) (void)fprintf(stderr, "%40.40s = " a "\n", # b, h->h_ ## b)
1314 #define DUMP2(a, b) (void)fprintf(stderr, "%40.40s = " a " (" a ")\n", # b, \
1315     h->h_ ## b, 1 << h->h_ ## b)
1316 	DUMP("%d", revision);
1317 	DUMP("%d", version);
1318 	DUMP("%#x", byte_order);
1319 	DUMP2("%d", sec_size_p2);
1320 	DUMP2("%d", short_sec_size_p2);
1321 	DUMP("%d", num_sectors_in_sat);
1322 	DUMP("%d", secid_first_directory);
1323 	DUMP("%d", min_size_standard_stream);
1324 	DUMP("%d", secid_first_sector_in_short_sat);
1325 	DUMP("%d", num_sectors_in_short_sat);
1326 	DUMP("%d", secid_first_sector_in_master_sat);
1327 	DUMP("%d", num_sectors_in_master_sat);
1328 	for (i = 0; i < __arraycount(h->h_master_sat); i++) {
1329 		if (h->h_master_sat[i] == CDF_SECID_FREE)
1330 			break;
1331 		(void)fprintf(stderr, "%35.35s[%.3" SIZE_T_FORMAT "u] = %d\n",
1332 		    "master_sat", i, h->h_master_sat[i]);
1333 	}
1334 }
1335 
1336 void
1337 cdf_dump_sat(const char *prefix, const cdf_sat_t *sat, size_t size)
1338 {
1339 	size_t i, j, s = size / sizeof(cdf_secid_t);
1340 
1341 	for (i = 0; i < sat->sat_len; i++) {
1342 		(void)fprintf(stderr, "%s[%" SIZE_T_FORMAT "u]:\n%.6"
1343 		    SIZE_T_FORMAT "u: ", prefix, i, i * s);
1344 		for (j = 0; j < s; j++) {
1345 			(void)fprintf(stderr, "%5d, ",
1346 			    CDF_TOLE4(sat->sat_tab[s * i + j]));
1347 			if ((j + 1) % 10 == 0)
1348 				(void)fprintf(stderr, "\n%.6" SIZE_T_FORMAT
1349 				    "u: ", i * s + j + 1);
1350 		}
1351 		(void)fprintf(stderr, "\n");
1352 	}
1353 }
1354 
1355 void
1356 cdf_dump(const void *v, size_t len)
1357 {
1358 	size_t i, j;
1359 	const unsigned char *p = v;
1360 	char abuf[16];
1361 
1362 	(void)fprintf(stderr, "%.4x: ", 0);
1363 	for (i = 0, j = 0; i < len; i++, p++) {
1364 		(void)fprintf(stderr, "%.2x ", *p);
1365 		abuf[j++] = isprint(*p) ? *p : '.';
1366 		if (j == 16) {
1367 			j = 0;
1368 			abuf[15] = '\0';
1369 			(void)fprintf(stderr, "%s\n%.4" SIZE_T_FORMAT "x: ",
1370 			    abuf, i + 1);
1371 		}
1372 	}
1373 	(void)fprintf(stderr, "\n");
1374 }
1375 
1376 void
1377 cdf_dump_stream(const cdf_stream_t *sst)
1378 {
1379 	size_t ss = sst->sst_ss;
1380 	cdf_dump(sst->sst_tab, ss * sst->sst_len);
1381 }
1382 
1383 void
1384 cdf_dump_dir(const cdf_info_t *info, const cdf_header_t *h,
1385     const cdf_sat_t *sat, const cdf_sat_t *ssat, const cdf_stream_t *sst,
1386     const cdf_dir_t *dir)
1387 {
1388 	size_t i, j;
1389 	cdf_directory_t *d;
1390 	char name[__arraycount(d->d_name)];
1391 	cdf_stream_t scn;
1392 	struct timespec ts;
1393 
1394 	static const char *types[] = { "empty", "user storage",
1395 	    "user stream", "lockbytes", "property", "root storage" };
1396 
1397 	for (i = 0; i < dir->dir_len; i++) {
1398 		char buf[26];
1399 		d = &dir->dir_tab[i];
1400 		for (j = 0; j < sizeof(name); j++)
1401 			name[j] = (char)CDF_TOLE2(d->d_name[j]);
1402 		(void)fprintf(stderr, "Directory %" SIZE_T_FORMAT "u: %s\n",
1403 		    i, name);
1404 		if (d->d_type < __arraycount(types))
1405 			(void)fprintf(stderr, "Type: %s\n", types[d->d_type]);
1406 		else
1407 			(void)fprintf(stderr, "Type: %d\n", d->d_type);
1408 		(void)fprintf(stderr, "Color: %s\n",
1409 		    d->d_color ? "black" : "red");
1410 		(void)fprintf(stderr, "Left child: %d\n", d->d_left_child);
1411 		(void)fprintf(stderr, "Right child: %d\n", d->d_right_child);
1412 		(void)fprintf(stderr, "Flags: %#x\n", d->d_flags);
1413 		cdf_timestamp_to_timespec(&ts, d->d_created);
1414 		(void)fprintf(stderr, "Created %s", cdf_ctime(&ts.tv_sec, buf));
1415 		cdf_timestamp_to_timespec(&ts, d->d_modified);
1416 		(void)fprintf(stderr, "Modified %s",
1417 		    cdf_ctime(&ts.tv_sec, buf));
1418 		(void)fprintf(stderr, "Stream %d\n", d->d_stream_first_sector);
1419 		(void)fprintf(stderr, "Size %d\n", d->d_size);
1420 		switch (d->d_type) {
1421 		case CDF_DIR_TYPE_USER_STORAGE:
1422 			(void)fprintf(stderr, "Storage: %d\n", d->d_storage);
1423 			break;
1424 		case CDF_DIR_TYPE_USER_STREAM:
1425 			if (sst == NULL)
1426 				break;
1427 			if (cdf_read_sector_chain(info, h, sat, ssat, sst,
1428 			    d->d_stream_first_sector, d->d_size, &scn) == -1) {
1429 				warn("Can't read stream for %s at %d len %d",
1430 				    name, d->d_stream_first_sector, d->d_size);
1431 				break;
1432 			}
1433 			cdf_dump_stream(&scn);
1434 			free(scn.sst_tab);
1435 			break;
1436 		default:
1437 			break;
1438 		}
1439 
1440 	}
1441 }
1442 
1443 void
1444 cdf_dump_property_info(const cdf_property_info_t *info, size_t count)
1445 {
1446 	cdf_timestamp_t tp;
1447 	struct timespec ts;
1448 	char buf[64];
1449 	size_t i, j;
1450 
1451 	for (i = 0; i < count; i++) {
1452 		cdf_print_property_name(buf, sizeof(buf), info[i].pi_id);
1453 		(void)fprintf(stderr, "%" SIZE_T_FORMAT "u) %s: ", i, buf);
1454 		switch (info[i].pi_type) {
1455 		case CDF_NULL:
1456 			break;
1457 		case CDF_SIGNED16:
1458 			(void)fprintf(stderr, "signed 16 [%hd]\n",
1459 			    info[i].pi_s16);
1460 			break;
1461 		case CDF_SIGNED32:
1462 			(void)fprintf(stderr, "signed 32 [%d]\n",
1463 			    info[i].pi_s32);
1464 			break;
1465 		case CDF_UNSIGNED32:
1466 			(void)fprintf(stderr, "unsigned 32 [%u]\n",
1467 			    info[i].pi_u32);
1468 			break;
1469 		case CDF_FLOAT:
1470 			(void)fprintf(stderr, "float [%g]\n",
1471 			    info[i].pi_f);
1472 			break;
1473 		case CDF_DOUBLE:
1474 			(void)fprintf(stderr, "double [%g]\n",
1475 			    info[i].pi_d);
1476 			break;
1477 		case CDF_LENGTH32_STRING:
1478 			(void)fprintf(stderr, "string %u [%.*s]\n",
1479 			    info[i].pi_str.s_len,
1480 			    info[i].pi_str.s_len, info[i].pi_str.s_buf);
1481 			break;
1482 		case CDF_LENGTH32_WSTRING:
1483 			(void)fprintf(stderr, "string %u [",
1484 			    info[i].pi_str.s_len);
1485 			for (j = 0; j < info[i].pi_str.s_len - 1; j++)
1486 			    (void)fputc(info[i].pi_str.s_buf[j << 1], stderr);
1487 			(void)fprintf(stderr, "]\n");
1488 			break;
1489 		case CDF_FILETIME:
1490 			tp = info[i].pi_tp;
1491 			if (tp < 1000000000000000LL) {
1492 				cdf_print_elapsed_time(buf, sizeof(buf), tp);
1493 				(void)fprintf(stderr, "timestamp %s\n", buf);
1494 			} else {
1495 				char tbuf[26];
1496 				cdf_timestamp_to_timespec(&ts, tp);
1497 				(void)fprintf(stderr, "timestamp %s",
1498 				    cdf_ctime(&ts.tv_sec, tbuf));
1499 			}
1500 			break;
1501 		case CDF_CLIPBOARD:
1502 			(void)fprintf(stderr, "CLIPBOARD %u\n", info[i].pi_u32);
1503 			break;
1504 		default:
1505 			DPRINTF(("Don't know how to deal with %#x\n",
1506 			    info[i].pi_type));
1507 			break;
1508 		}
1509 	}
1510 }
1511 
1512 
1513 void
1514 cdf_dump_summary_info(const cdf_header_t *h, const cdf_stream_t *sst)
1515 {
1516 	char buf[128];
1517 	cdf_summary_info_header_t ssi;
1518 	cdf_property_info_t *info;
1519 	size_t count;
1520 
1521 	(void)&h;
1522 	if (cdf_unpack_summary_info(sst, h, &ssi, &info, &count) == -1)
1523 		return;
1524 	(void)fprintf(stderr, "Endian: %#x\n", ssi.si_byte_order);
1525 	(void)fprintf(stderr, "Os Version %d.%d\n", ssi.si_os_version & 0xff,
1526 	    ssi.si_os_version >> 8);
1527 	(void)fprintf(stderr, "Os %d\n", ssi.si_os);
1528 	cdf_print_classid(buf, sizeof(buf), &ssi.si_class);
1529 	(void)fprintf(stderr, "Class %s\n", buf);
1530 	(void)fprintf(stderr, "Count %d\n", ssi.si_count);
1531 	cdf_dump_property_info(info, count);
1532 	free(info);
1533 }
1534 
1535 
1536 void
1537 cdf_dump_catalog(const cdf_header_t *h, const cdf_stream_t *sst)
1538 {
1539 	cdf_catalog_t *cat;
1540 	cdf_unpack_catalog(h, sst, &cat);
1541 	const cdf_catalog_entry_t *ce = cat->cat_e;
1542 	struct timespec ts;
1543 	char tbuf[64], sbuf[256];
1544 	size_t i;
1545 
1546 	printf("Catalog:\n");
1547 	for (i = 0; i < cat->cat_num; i++) {
1548 		cdf_timestamp_to_timespec(&ts, ce[i].ce_timestamp);
1549 		printf("\t%d %s %s", ce[i].ce_num,
1550 		    cdf_u16tos8(sbuf, ce[i].ce_namlen, ce[i].ce_name),
1551 		    cdf_ctime(&ts.tv_sec, tbuf));
1552 	}
1553 	free(cat);
1554 }
1555 
1556 #endif
1557 
1558 #ifdef TEST
1559 int
1560 main(int argc, char *argv[])
1561 {
1562 	int i;
1563 	cdf_header_t h;
1564 	cdf_sat_t sat, ssat;
1565 	cdf_stream_t sst, scn;
1566 	cdf_dir_t dir;
1567 	cdf_info_t info;
1568 	const cdf_directory_t *root;
1569 #ifdef __linux__
1570 #define getprogname() __progname
1571 	extern char *__progname;
1572 #endif
1573 	if (argc < 2) {
1574 		(void)fprintf(stderr, "Usage: %s <filename>\n", getprogname());
1575 		return -1;
1576 	}
1577 
1578 	info.i_buf = NULL;
1579 	info.i_len = 0;
1580 	for (i = 1; i < argc; i++) {
1581 		if ((info.i_fd = open(argv[1], O_RDONLY)) == -1)
1582 			err(EXIT_FAILURE, "Cannot open `%s'", argv[1]);
1583 
1584 		if (cdf_read_header(&info, &h) == -1)
1585 			err(EXIT_FAILURE, "Cannot read header");
1586 #ifdef CDF_DEBUG
1587 		cdf_dump_header(&h);
1588 #endif
1589 
1590 		if (cdf_read_sat(&info, &h, &sat) == -1)
1591 			err(EXIT_FAILURE, "Cannot read sat");
1592 #ifdef CDF_DEBUG
1593 		cdf_dump_sat("SAT", &sat, CDF_SEC_SIZE(&h));
1594 #endif
1595 
1596 		if (cdf_read_ssat(&info, &h, &sat, &ssat) == -1)
1597 			err(EXIT_FAILURE, "Cannot read ssat");
1598 #ifdef CDF_DEBUG
1599 		cdf_dump_sat("SSAT", &ssat, CDF_SHORT_SEC_SIZE(&h));
1600 #endif
1601 
1602 		if (cdf_read_dir(&info, &h, &sat, &dir) == -1)
1603 			err(EXIT_FAILURE, "Cannot read dir");
1604 
1605 		if (cdf_read_short_stream(&info, &h, &sat, &dir, &sst, &root)
1606 		    == -1)
1607 			err(EXIT_FAILURE, "Cannot read short stream");
1608 #ifdef CDF_DEBUG
1609 		cdf_dump_stream(&sst);
1610 #endif
1611 
1612 #ifdef CDF_DEBUG
1613 		cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir);
1614 #endif
1615 
1616 
1617 		if (cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir,
1618 		    &scn) == -1)
1619 			warn("Cannot read summary info");
1620 #ifdef CDF_DEBUG
1621 		else
1622 			cdf_dump_summary_info(&h, &scn);
1623 #endif
1624 		if (cdf_read_user_stream(&info, &h, &sat, &ssat, &sst,
1625 		    &dir, "Catalog", &scn) == -1)
1626 			warn("Cannot read catalog");
1627 #ifdef CDF_DEBUG
1628 		else
1629 			cdf_dump_catalog(&h, &scn);
1630 #endif
1631 
1632 		(void)close(info.i_fd);
1633 	}
1634 
1635 	return 0;
1636 }
1637 #endif
1638