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