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