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