1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * Copyright (c) 2009 Andreas Henriksson <andreas@fatal.se>
4  * Copyright (c) 2009-2011 Michihiro NAKAJIMA
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 AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_iso9660.c 201246 2009-12-30 05:30:35Z kientzle $");
30 
31 #ifdef HAVE_ERRNO_H
32 #include <errno.h>
33 #endif
34 /* #include <stdint.h> */ /* See archive_platform.h */
35 #include <stdio.h>
36 #ifdef HAVE_STDLIB_H
37 #include <stdlib.h>
38 #endif
39 #ifdef HAVE_STRING_H
40 #include <string.h>
41 #endif
42 #include <time.h>
43 #ifdef HAVE_ZLIB_H
44 #include <zlib.h>
45 #endif
46 
47 #include "archive.h"
48 #include "archive_endian.h"
49 #include "archive_entry.h"
50 #include "archive_entry_locale.h"
51 #include "archive_private.h"
52 #include "archive_read_private.h"
53 #include "archive_string.h"
54 
55 /*
56  * An overview of ISO 9660 format:
57  *
58  * Each disk is laid out as follows:
59  *   * 32k reserved for private use
60  *   * Volume descriptor table.  Each volume descriptor
61  *     is 2k and specifies basic format information.
62  *     The "Primary Volume Descriptor" (PVD) is defined by the
63  *     standard and should always be present; other volume
64  *     descriptors include various vendor-specific extensions.
65  *   * Files and directories.  Each file/dir is specified by
66  *     an "extent" (starting sector and length in bytes).
67  *     Dirs are just files with directory records packed one
68  *     after another.  The PVD contains a single dir entry
69  *     specifying the location of the root directory.  Everything
70  *     else follows from there.
71  *
72  * This module works by first reading the volume descriptors, then
73  * building a list of directory entries, sorted by starting
74  * sector.  At each step, I look for the earliest dir entry that
75  * hasn't yet been read, seek forward to that location and read
76  * that entry.  If it's a dir, I slurp in the new dir entries and
77  * add them to the heap; if it's a regular file, I return the
78  * corresponding archive_entry and wait for the client to request
79  * the file body.  This strategy allows us to read most compliant
80  * CDs with a single pass through the data, as required by libarchive.
81  */
82 #define	LOGICAL_BLOCK_SIZE	2048
83 #define	SYSTEM_AREA_BLOCK	16
84 
85 /* Structure of on-disk primary volume descriptor. */
86 #define PVD_type_offset 0
87 #define PVD_type_size 1
88 #define PVD_id_offset (PVD_type_offset + PVD_type_size)
89 #define PVD_id_size 5
90 #define PVD_version_offset (PVD_id_offset + PVD_id_size)
91 #define PVD_version_size 1
92 #define PVD_reserved1_offset (PVD_version_offset + PVD_version_size)
93 #define PVD_reserved1_size 1
94 #define PVD_system_id_offset (PVD_reserved1_offset + PVD_reserved1_size)
95 #define PVD_system_id_size 32
96 #define PVD_volume_id_offset (PVD_system_id_offset + PVD_system_id_size)
97 #define PVD_volume_id_size 32
98 #define PVD_reserved2_offset (PVD_volume_id_offset + PVD_volume_id_size)
99 #define PVD_reserved2_size 8
100 #define PVD_volume_space_size_offset (PVD_reserved2_offset + PVD_reserved2_size)
101 #define PVD_volume_space_size_size 8
102 #define PVD_reserved3_offset (PVD_volume_space_size_offset + PVD_volume_space_size_size)
103 #define PVD_reserved3_size 32
104 #define PVD_volume_set_size_offset (PVD_reserved3_offset + PVD_reserved3_size)
105 #define PVD_volume_set_size_size 4
106 #define PVD_volume_sequence_number_offset (PVD_volume_set_size_offset + PVD_volume_set_size_size)
107 #define PVD_volume_sequence_number_size 4
108 #define PVD_logical_block_size_offset (PVD_volume_sequence_number_offset + PVD_volume_sequence_number_size)
109 #define PVD_logical_block_size_size 4
110 #define PVD_path_table_size_offset (PVD_logical_block_size_offset + PVD_logical_block_size_size)
111 #define PVD_path_table_size_size 8
112 #define PVD_type_1_path_table_offset (PVD_path_table_size_offset + PVD_path_table_size_size)
113 #define PVD_type_1_path_table_size 4
114 #define PVD_opt_type_1_path_table_offset (PVD_type_1_path_table_offset + PVD_type_1_path_table_size)
115 #define PVD_opt_type_1_path_table_size 4
116 #define PVD_type_m_path_table_offset (PVD_opt_type_1_path_table_offset + PVD_opt_type_1_path_table_size)
117 #define PVD_type_m_path_table_size 4
118 #define PVD_opt_type_m_path_table_offset (PVD_type_m_path_table_offset + PVD_type_m_path_table_size)
119 #define PVD_opt_type_m_path_table_size 4
120 #define PVD_root_directory_record_offset (PVD_opt_type_m_path_table_offset + PVD_opt_type_m_path_table_size)
121 #define PVD_root_directory_record_size 34
122 #define PVD_volume_set_id_offset (PVD_root_directory_record_offset + PVD_root_directory_record_size)
123 #define PVD_volume_set_id_size 128
124 #define PVD_publisher_id_offset (PVD_volume_set_id_offset + PVD_volume_set_id_size)
125 #define PVD_publisher_id_size 128
126 #define PVD_preparer_id_offset (PVD_publisher_id_offset + PVD_publisher_id_size)
127 #define PVD_preparer_id_size 128
128 #define PVD_application_id_offset (PVD_preparer_id_offset + PVD_preparer_id_size)
129 #define PVD_application_id_size 128
130 #define PVD_copyright_file_id_offset (PVD_application_id_offset + PVD_application_id_size)
131 #define PVD_copyright_file_id_size 37
132 #define PVD_abstract_file_id_offset (PVD_copyright_file_id_offset + PVD_copyright_file_id_size)
133 #define PVD_abstract_file_id_size 37
134 #define PVD_bibliographic_file_id_offset (PVD_abstract_file_id_offset + PVD_abstract_file_id_size)
135 #define PVD_bibliographic_file_id_size 37
136 #define PVD_creation_date_offset (PVD_bibliographic_file_id_offset + PVD_bibliographic_file_id_size)
137 #define PVD_creation_date_size 17
138 #define PVD_modification_date_offset (PVD_creation_date_offset + PVD_creation_date_size)
139 #define PVD_modification_date_size 17
140 #define PVD_expiration_date_offset (PVD_modification_date_offset + PVD_modification_date_size)
141 #define PVD_expiration_date_size 17
142 #define PVD_effective_date_offset (PVD_expiration_date_offset + PVD_expiration_date_size)
143 #define PVD_effective_date_size 17
144 #define PVD_file_structure_version_offset (PVD_effective_date_offset + PVD_effective_date_size)
145 #define PVD_file_structure_version_size 1
146 #define PVD_reserved4_offset (PVD_file_structure_version_offset + PVD_file_structure_version_size)
147 #define PVD_reserved4_size 1
148 #define PVD_application_data_offset (PVD_reserved4_offset + PVD_reserved4_size)
149 #define PVD_application_data_size 512
150 #define PVD_reserved5_offset (PVD_application_data_offset + PVD_application_data_size)
151 #define PVD_reserved5_size (2048 - PVD_reserved5_offset)
152 
153 /* TODO: It would make future maintenance easier to just hardcode the
154  * above values.  In particular, ECMA119 states the offsets as part of
155  * the standard.  That would eliminate the need for the following check.*/
156 #if PVD_reserved5_offset != 1395
157 #error PVD offset and size definitions are wrong.
158 #endif
159 
160 
161 /* Structure of optional on-disk supplementary volume descriptor. */
162 #define SVD_type_offset 0
163 #define SVD_type_size 1
164 #define SVD_id_offset (SVD_type_offset + SVD_type_size)
165 #define SVD_id_size 5
166 #define SVD_version_offset (SVD_id_offset + SVD_id_size)
167 #define SVD_version_size 1
168 /* ... */
169 #define SVD_reserved1_offset	72
170 #define SVD_reserved1_size	8
171 #define SVD_volume_space_size_offset 80
172 #define SVD_volume_space_size_size 8
173 #define SVD_escape_sequences_offset (SVD_volume_space_size_offset + SVD_volume_space_size_size)
174 #define SVD_escape_sequences_size 32
175 /* ... */
176 #define SVD_logical_block_size_offset 128
177 #define SVD_logical_block_size_size 4
178 #define SVD_type_L_path_table_offset 140
179 #define SVD_type_M_path_table_offset 148
180 /* ... */
181 #define SVD_root_directory_record_offset 156
182 #define SVD_root_directory_record_size 34
183 #define SVD_file_structure_version_offset 881
184 #define SVD_reserved2_offset	882
185 #define SVD_reserved2_size	1
186 #define SVD_reserved3_offset	1395
187 #define SVD_reserved3_size	653
188 /* ... */
189 /* FIXME: validate correctness of last SVD entry offset. */
190 
191 /* Structure of an on-disk directory record. */
192 /* Note:  ISO9660 stores each multi-byte integer twice, once in
193  * each byte order.  The sizes here are the size of just one
194  * of the two integers.  (This is why the offset of a field isn't
195  * the same as the offset+size of the previous field.) */
196 #define DR_length_offset 0
197 #define DR_length_size 1
198 #define DR_ext_attr_length_offset 1
199 #define DR_ext_attr_length_size 1
200 #define DR_extent_offset 2
201 #define DR_extent_size 4
202 #define DR_size_offset 10
203 #define DR_size_size 4
204 #define DR_date_offset 18
205 #define DR_date_size 7
206 #define DR_flags_offset 25
207 #define DR_flags_size 1
208 #define DR_file_unit_size_offset 26
209 #define DR_file_unit_size_size 1
210 #define DR_interleave_offset 27
211 #define DR_interleave_size 1
212 #define DR_volume_sequence_number_offset 28
213 #define DR_volume_sequence_number_size 2
214 #define DR_name_len_offset 32
215 #define DR_name_len_size 1
216 #define DR_name_offset 33
217 
218 #ifdef HAVE_ZLIB_H
219 static const unsigned char zisofs_magic[8] = {
220 	0x37, 0xE4, 0x53, 0x96, 0xC9, 0xDB, 0xD6, 0x07
221 };
222 
223 struct zisofs {
224 	/* Set 1 if this file compressed by paged zlib */
225 	int		 pz;
226 	int		 pz_log2_bs; /* Log2 of block size */
227 	uint64_t	 pz_uncompressed_size;
228 
229 	int		 initialized;
230 	unsigned char	*uncompressed_buffer;
231 	size_t		 uncompressed_buffer_size;
232 
233 	uint32_t	 pz_offset;
234 	unsigned char	 header[16];
235 	size_t		 header_avail;
236 	int		 header_passed;
237 	unsigned char	*block_pointers;
238 	size_t		 block_pointers_alloc;
239 	size_t		 block_pointers_size;
240 	size_t		 block_pointers_avail;
241 	size_t		 block_off;
242 	uint32_t	 block_avail;
243 
244 	z_stream	 stream;
245 	int		 stream_valid;
246 };
247 #else
248 struct zisofs {
249 	/* Set 1 if this file compressed by paged zlib */
250 	int		 pz;
251 };
252 #endif
253 
254 struct content {
255 	uint64_t	 offset;/* Offset on disk.		*/
256 	uint64_t	 size;	/* File size in bytes.		*/
257 	struct content	*next;
258 };
259 
260 /* In-memory storage for a directory record. */
261 struct file_info {
262 	struct file_info	*use_next;
263 	struct file_info	*parent;
264 	struct file_info	*next;
265 	struct file_info	*re_next;
266 	int		 subdirs;
267 	uint64_t	 key;		/* Heap Key.			*/
268 	uint64_t	 offset;	/* Offset on disk.		*/
269 	uint64_t	 size;		/* File size in bytes.		*/
270 	uint32_t	 ce_offset;	/* Offset of CE.		*/
271 	uint32_t	 ce_size;	/* Size of CE.			*/
272 	char		 rr_moved;	/* Flag to rr_moved.		*/
273 	char		 rr_moved_has_re_only;
274 	char		 re;		/* Having RRIP "RE" extension.	*/
275 	char		 re_descendant;
276 	uint64_t	 cl_offset;	/* Having RRIP "CL" extension.	*/
277 	int		 birthtime_is_set;
278 	time_t		 birthtime;	/* File created time.		*/
279 	time_t		 mtime;		/* File last modified time.	*/
280 	time_t		 atime;		/* File last accessed time.	*/
281 	time_t		 ctime;		/* File attribute change time.	*/
282 	uint64_t	 rdev;		/* Device number.		*/
283 	mode_t		 mode;
284 	uid_t		 uid;
285 	gid_t		 gid;
286 	int64_t		 number;
287 	int		 nlinks;
288 	struct archive_string name; /* Pathname */
289 	unsigned char	*utf16be_name;
290 	size_t		 utf16be_bytes;
291 	char		 name_continues; /* Non-zero if name continues */
292 	struct archive_string symlink;
293 	char		 symlink_continues; /* Non-zero if link continues */
294 	/* Set 1 if this file compressed by paged zlib(zisofs) */
295 	int		 pz;
296 	int		 pz_log2_bs; /* Log2 of block size */
297 	uint64_t	 pz_uncompressed_size;
298 	/* Set 1 if this file is multi extent. */
299 	int		 multi_extent;
300 	struct {
301 		struct content	*first;
302 		struct content	**last;
303 	} contents;
304 	struct {
305 		struct file_info	*first;
306 		struct file_info	**last;
307 	} rede_files;
308 };
309 
310 struct heap_queue {
311 	struct file_info **files;
312 	int		 allocated;
313 	int		 used;
314 };
315 
316 struct iso9660 {
317 	int	magic;
318 #define ISO9660_MAGIC   0x96609660
319 
320 	int opt_support_joliet;
321 	int opt_support_rockridge;
322 
323 	struct archive_string pathname;
324 	char	seenRockridge;	/* Set true if RR extensions are used. */
325 	char	seenSUSP;	/* Set true if SUSP is beging used. */
326 	char	seenJoliet;
327 
328 	unsigned char	suspOffset;
329 	struct file_info *rr_moved;
330 	struct read_ce_queue {
331 		struct read_ce_req {
332 			uint64_t	 offset;/* Offset of CE on disk. */
333 			struct file_info *file;
334 		}		*reqs;
335 		int		 cnt;
336 		int		 allocated;
337 	}	read_ce_req;
338 
339 	int64_t		previous_number;
340 	struct archive_string previous_pathname;
341 
342 	struct file_info		*use_files;
343 	struct heap_queue		 pending_files;
344 	struct {
345 		struct file_info	*first;
346 		struct file_info	**last;
347 	}	cache_files;
348 	struct {
349 		struct file_info	*first;
350 		struct file_info	**last;
351 	}	re_files;
352 
353 	uint64_t current_position;
354 	ssize_t	logical_block_size;
355 	uint64_t volume_size; /* Total size of volume in bytes. */
356 	int32_t  volume_block;/* Total size of volume in logical blocks. */
357 
358 	struct vd {
359 		int		location;	/* Location of Extent.	*/
360 		uint32_t	size;
361 	} primary, joliet;
362 
363 	int64_t	entry_sparse_offset;
364 	int64_t	entry_bytes_remaining;
365 	size_t  entry_bytes_unconsumed;
366 	struct zisofs	 entry_zisofs;
367 	struct content	*entry_content;
368 	struct archive_string_conv *sconv_utf16be;
369 	/*
370 	 * Buffers for a full pathname in UTF-16BE in Joliet extensions.
371 	 */
372 #define UTF16_NAME_MAX	1024
373 	unsigned char *utf16be_path;
374 	size_t		 utf16be_path_len;
375 	unsigned char *utf16be_previous_path;
376 	size_t		 utf16be_previous_path_len;
377 };
378 
379 static int	archive_read_format_iso9660_bid(struct archive_read *, int);
380 static int	archive_read_format_iso9660_options(struct archive_read *,
381 		    const char *, const char *);
382 static int	archive_read_format_iso9660_cleanup(struct archive_read *);
383 static int	archive_read_format_iso9660_read_data(struct archive_read *,
384 		    const void **, size_t *, int64_t *);
385 static int	archive_read_format_iso9660_read_data_skip(struct archive_read *);
386 static int	archive_read_format_iso9660_read_header(struct archive_read *,
387 		    struct archive_entry *);
388 static const char *build_pathname(struct archive_string *, struct file_info *);
389 static int	build_pathname_utf16be(unsigned char *, size_t, size_t *,
390 		    struct file_info *);
391 #if DEBUG
392 static void	dump_isodirrec(FILE *, const unsigned char *isodirrec);
393 #endif
394 static time_t	time_from_tm(struct tm *);
395 static time_t	isodate17(const unsigned char *);
396 static time_t	isodate7(const unsigned char *);
397 static int	isBootRecord(struct iso9660 *, const unsigned char *);
398 static int	isVolumePartition(struct iso9660 *, const unsigned char *);
399 static int	isVDSetTerminator(struct iso9660 *, const unsigned char *);
400 static int	isJolietSVD(struct iso9660 *, const unsigned char *);
401 static int	isSVD(struct iso9660 *, const unsigned char *);
402 static int	isEVD(struct iso9660 *, const unsigned char *);
403 static int	isPVD(struct iso9660 *, const unsigned char *);
404 static int	next_cache_entry(struct archive_read *, struct iso9660 *,
405 		    struct file_info **);
406 static int	next_entry_seek(struct archive_read *, struct iso9660 *,
407 		    struct file_info **);
408 static struct file_info *
409 		parse_file_info(struct archive_read *a,
410 		    struct file_info *parent, const unsigned char *isodirrec);
411 static int	parse_rockridge(struct archive_read *a,
412 		    struct file_info *file, const unsigned char *start,
413 		    const unsigned char *end);
414 static int	register_CE(struct archive_read *a, int32_t location,
415 		    struct file_info *file);
416 static int	read_CE(struct archive_read *a, struct iso9660 *iso9660);
417 static void	parse_rockridge_NM1(struct file_info *,
418 		    const unsigned char *, int);
419 static void	parse_rockridge_SL1(struct file_info *,
420 		    const unsigned char *, int);
421 static void	parse_rockridge_TF1(struct file_info *,
422 		    const unsigned char *, int);
423 static void	parse_rockridge_ZF1(struct file_info *,
424 		    const unsigned char *, int);
425 static void	register_file(struct iso9660 *, struct file_info *);
426 static void	release_files(struct iso9660 *);
427 static unsigned	toi(const void *p, int n);
428 static inline void re_add_entry(struct iso9660 *, struct file_info *);
429 static inline struct file_info * re_get_entry(struct iso9660 *);
430 static inline int rede_add_entry(struct file_info *);
431 static inline struct file_info * rede_get_entry(struct file_info *);
432 static inline void cache_add_entry(struct iso9660 *iso9660,
433 		    struct file_info *file);
434 static inline struct file_info *cache_get_entry(struct iso9660 *iso9660);
435 static int	heap_add_entry(struct archive_read *a, struct heap_queue *heap,
436 		    struct file_info *file, uint64_t key);
437 static struct file_info *heap_get_entry(struct heap_queue *heap);
438 
439 #define add_entry(arch, iso9660, file)	\
440 	heap_add_entry(arch, &((iso9660)->pending_files), file, file->offset)
441 #define next_entry(iso9660)		\
442 	heap_get_entry(&((iso9660)->pending_files))
443 
444 int
445 archive_read_support_format_iso9660(struct archive *_a)
446 {
447 	struct archive_read *a = (struct archive_read *)_a;
448 	struct iso9660 *iso9660;
449 	int r;
450 
451 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
452 	    ARCHIVE_STATE_NEW, "archive_read_support_format_iso9660");
453 
454 	iso9660 = (struct iso9660 *)calloc(1, sizeof(*iso9660));
455 	if (iso9660 == NULL) {
456 		archive_set_error(&a->archive, ENOMEM,
457 		    "Can't allocate iso9660 data");
458 		return (ARCHIVE_FATAL);
459 	}
460 	iso9660->magic = ISO9660_MAGIC;
461 	iso9660->cache_files.first = NULL;
462 	iso9660->cache_files.last = &(iso9660->cache_files.first);
463 	iso9660->re_files.first = NULL;
464 	iso9660->re_files.last = &(iso9660->re_files.first);
465 	/* Enable to support Joliet extensions by default.	*/
466 	iso9660->opt_support_joliet = 1;
467 	/* Enable to support Rock Ridge extensions by default.	*/
468 	iso9660->opt_support_rockridge = 1;
469 
470 	r = __archive_read_register_format(a,
471 	    iso9660,
472 	    "iso9660",
473 	    archive_read_format_iso9660_bid,
474 	    archive_read_format_iso9660_options,
475 	    archive_read_format_iso9660_read_header,
476 	    archive_read_format_iso9660_read_data,
477 	    archive_read_format_iso9660_read_data_skip,
478 	    archive_read_format_iso9660_cleanup);
479 
480 	if (r != ARCHIVE_OK) {
481 		free(iso9660);
482 		return (r);
483 	}
484 	return (ARCHIVE_OK);
485 }
486 
487 
488 static int
489 archive_read_format_iso9660_bid(struct archive_read *a, int best_bid)
490 {
491 	struct iso9660 *iso9660;
492 	ssize_t bytes_read;
493 	const unsigned char *p;
494 	int seenTerminator;
495 
496 	/* If there's already a better bid than we can ever
497 	   make, don't bother testing. */
498 	if (best_bid > 48)
499 		return (-1);
500 
501 	iso9660 = (struct iso9660 *)(a->format->data);
502 
503 	/*
504 	 * Skip the first 32k (reserved area) and get the first
505 	 * 8 sectors of the volume descriptor table.  Of course,
506 	 * if the I/O layer gives us more, we'll take it.
507 	 */
508 #define RESERVED_AREA	(SYSTEM_AREA_BLOCK * LOGICAL_BLOCK_SIZE)
509 	p = __archive_read_ahead(a,
510 	    RESERVED_AREA + 8 * LOGICAL_BLOCK_SIZE,
511 	    &bytes_read);
512 	if (p == NULL)
513 	    return (-1);
514 
515 	/* Skip the reserved area. */
516 	bytes_read -= RESERVED_AREA;
517 	p += RESERVED_AREA;
518 
519 	/* Check each volume descriptor. */
520 	seenTerminator = 0;
521 	for (; bytes_read > LOGICAL_BLOCK_SIZE;
522 	    bytes_read -= LOGICAL_BLOCK_SIZE, p += LOGICAL_BLOCK_SIZE) {
523 		/* Do not handle undefined Volume Descriptor Type. */
524 		if (p[0] >= 4 && p[0] <= 254)
525 			return (0);
526 		/* Standard Identifier must be "CD001" */
527 		if (memcmp(p + 1, "CD001", 5) != 0)
528 			return (0);
529 		if (isPVD(iso9660, p))
530 			continue;
531 		if (!iso9660->joliet.location) {
532 			if (isJolietSVD(iso9660, p))
533 				continue;
534 		}
535 		if (isBootRecord(iso9660, p))
536 			continue;
537 		if (isEVD(iso9660, p))
538 			continue;
539 		if (isSVD(iso9660, p))
540 			continue;
541 		if (isVolumePartition(iso9660, p))
542 			continue;
543 		if (isVDSetTerminator(iso9660, p)) {
544 			seenTerminator = 1;
545 			break;
546 		}
547 		return (0);
548 	}
549 	/*
550 	 * ISO 9660 format must have Primary Volume Descriptor and
551 	 * Volume Descriptor Set Terminator.
552 	 */
553 	if (seenTerminator && iso9660->primary.location > 16)
554 		return (48);
555 
556 	/* We didn't find a valid PVD; return a bid of zero. */
557 	return (0);
558 }
559 
560 static int
561 archive_read_format_iso9660_options(struct archive_read *a,
562 		const char *key, const char *val)
563 {
564 	struct iso9660 *iso9660;
565 
566 	iso9660 = (struct iso9660 *)(a->format->data);
567 
568 	if (strcmp(key, "joliet") == 0) {
569 		if (val == NULL || strcmp(val, "off") == 0 ||
570 				strcmp(val, "ignore") == 0 ||
571 				strcmp(val, "disable") == 0 ||
572 				strcmp(val, "0") == 0)
573 			iso9660->opt_support_joliet = 0;
574 		else
575 			iso9660->opt_support_joliet = 1;
576 		return (ARCHIVE_OK);
577 	}
578 	if (strcmp(key, "rockridge") == 0 ||
579 	    strcmp(key, "Rockridge") == 0) {
580 		iso9660->opt_support_rockridge = val != NULL;
581 		return (ARCHIVE_OK);
582 	}
583 
584 	/* Note: The "warn" return is just to inform the options
585 	 * supervisor that we didn't handle it.  It will generate
586 	 * a suitable error if no one used this option. */
587 	return (ARCHIVE_WARN);
588 }
589 
590 static int
591 isBootRecord(struct iso9660 *iso9660, const unsigned char *h)
592 {
593 	(void)iso9660; /* UNUSED */
594 
595 	/* Type of the Volume Descriptor Boot Record must be 0. */
596 	if (h[0] != 0)
597 		return (0);
598 
599 	/* Volume Descriptor Version must be 1. */
600 	if (h[6] != 1)
601 		return (0);
602 
603 	return (1);
604 }
605 
606 static int
607 isVolumePartition(struct iso9660 *iso9660, const unsigned char *h)
608 {
609 	int32_t location;
610 
611 	/* Type of the Volume Partition Descriptor must be 3. */
612 	if (h[0] != 3)
613 		return (0);
614 
615 	/* Volume Descriptor Version must be 1. */
616 	if (h[6] != 1)
617 		return (0);
618 	/* Unused Field */
619 	if (h[7] != 0)
620 		return (0);
621 
622 	location = archive_le32dec(h + 72);
623 	if (location <= SYSTEM_AREA_BLOCK ||
624 	    location >= iso9660->volume_block)
625 		return (0);
626 	if ((uint32_t)location != archive_be32dec(h + 76))
627 		return (0);
628 
629 	return (1);
630 }
631 
632 static int
633 isVDSetTerminator(struct iso9660 *iso9660, const unsigned char *h)
634 {
635 	int i;
636 
637 	(void)iso9660; /* UNUSED */
638 
639 	/* Type of the Volume Descriptor Set Terminator must be 255. */
640 	if (h[0] != 255)
641 		return (0);
642 
643 	/* Volume Descriptor Version must be 1. */
644 	if (h[6] != 1)
645 		return (0);
646 
647 	/* Reserved field must be 0. */
648 	for (i = 7; i < 2048; ++i)
649 		if (h[i] != 0)
650 			return (0);
651 
652 	return (1);
653 }
654 
655 static int
656 isJolietSVD(struct iso9660 *iso9660, const unsigned char *h)
657 {
658 	const unsigned char *p;
659 	ssize_t logical_block_size;
660 	int32_t volume_block;
661 
662 	/* Check if current sector is a kind of Supplementary Volume
663 	 * Descriptor. */
664 	if (!isSVD(iso9660, h))
665 		return (0);
666 
667 	/* FIXME: do more validations according to joliet spec. */
668 
669 	/* check if this SVD contains joliet extension! */
670 	p = h + SVD_escape_sequences_offset;
671 	/* N.B. Joliet spec says p[1] == '\\', but.... */
672 	if (p[0] == '%' && p[1] == '/') {
673 		int level = 0;
674 
675 		if (p[2] == '@')
676 			level = 1;
677 		else if (p[2] == 'C')
678 			level = 2;
679 		else if (p[2] == 'E')
680 			level = 3;
681 		else /* not joliet */
682 			return (0);
683 
684 		iso9660->seenJoliet = level;
685 
686 	} else /* not joliet */
687 		return (0);
688 
689 	logical_block_size =
690 	    archive_le16dec(h + SVD_logical_block_size_offset);
691 	volume_block = archive_le32dec(h + SVD_volume_space_size_offset);
692 
693 	iso9660->logical_block_size = logical_block_size;
694 	iso9660->volume_block = volume_block;
695 	iso9660->volume_size = logical_block_size * (uint64_t)volume_block;
696 	/* Read Root Directory Record in Volume Descriptor. */
697 	p = h + SVD_root_directory_record_offset;
698 	iso9660->joliet.location = archive_le32dec(p + DR_extent_offset);
699 	iso9660->joliet.size = archive_le32dec(p + DR_size_offset);
700 
701 	return (48);
702 }
703 
704 static int
705 isSVD(struct iso9660 *iso9660, const unsigned char *h)
706 {
707 	const unsigned char *p;
708 	ssize_t logical_block_size;
709 	int32_t volume_block;
710 	int32_t location;
711 	int i;
712 
713 	(void)iso9660; /* UNUSED */
714 
715 	/* Type 2 means it's a SVD. */
716 	if (h[SVD_type_offset] != 2)
717 		return (0);
718 
719 	/* Reserved field must be 0. */
720 	for (i = 0; i < SVD_reserved1_size; ++i)
721 		if (h[SVD_reserved1_offset + i] != 0)
722 			return (0);
723 	for (i = 0; i < SVD_reserved2_size; ++i)
724 		if (h[SVD_reserved2_offset + i] != 0)
725 			return (0);
726 	for (i = 0; i < SVD_reserved3_size; ++i)
727 		if (h[SVD_reserved3_offset + i] != 0)
728 			return (0);
729 
730 	/* File structure version must be 1 for ISO9660/ECMA119. */
731 	if (h[SVD_file_structure_version_offset] != 1)
732 		return (0);
733 
734 	logical_block_size =
735 	    archive_le16dec(h + SVD_logical_block_size_offset);
736 	if (logical_block_size <= 0)
737 		return (0);
738 
739 	volume_block = archive_le32dec(h + SVD_volume_space_size_offset);
740 	if (volume_block <= SYSTEM_AREA_BLOCK+4)
741 		return (0);
742 
743 	/* Location of Occurrence of Type L Path Table must be
744 	 * available location,
745 	 * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */
746 	location = archive_le32dec(h+SVD_type_L_path_table_offset);
747 	if (location < SYSTEM_AREA_BLOCK+2 || location >= volume_block)
748 		return (0);
749 
750 	/* The Type M Path Table must be at a valid location (WinISO
751 	 * and probably other programs omit this, so we allow zero)
752 	 *
753 	 * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */
754 	location = archive_be32dec(h+SVD_type_M_path_table_offset);
755 	if ((location > 0 && location < SYSTEM_AREA_BLOCK+2)
756 	    || location >= volume_block)
757 		return (0);
758 
759 	/* Read Root Directory Record in Volume Descriptor. */
760 	p = h + SVD_root_directory_record_offset;
761 	if (p[DR_length_offset] != 34)
762 		return (0);
763 
764 	return (48);
765 }
766 
767 static int
768 isEVD(struct iso9660 *iso9660, const unsigned char *h)
769 {
770 	const unsigned char *p;
771 	ssize_t logical_block_size;
772 	int32_t volume_block;
773 	int32_t location;
774 	int i;
775 
776 	(void)iso9660; /* UNUSED */
777 
778 	/* Type of the Enhanced Volume Descriptor must be 2. */
779 	if (h[PVD_type_offset] != 2)
780 		return (0);
781 
782 	/* EVD version must be 2. */
783 	if (h[PVD_version_offset] != 2)
784 		return (0);
785 
786 	/* Reserved field must be 0. */
787 	if (h[PVD_reserved1_offset] != 0)
788 		return (0);
789 
790 	/* Reserved field must be 0. */
791 	for (i = 0; i < PVD_reserved2_size; ++i)
792 		if (h[PVD_reserved2_offset + i] != 0)
793 			return (0);
794 
795 	/* Reserved field must be 0. */
796 	for (i = 0; i < PVD_reserved3_size; ++i)
797 		if (h[PVD_reserved3_offset + i] != 0)
798 			return (0);
799 
800 	/* Logical block size must be > 0. */
801 	/* I've looked at Ecma 119 and can't find any stronger
802 	 * restriction on this field. */
803 	logical_block_size =
804 	    archive_le16dec(h + PVD_logical_block_size_offset);
805 	if (logical_block_size <= 0)
806 		return (0);
807 
808 	volume_block =
809 	    archive_le32dec(h + PVD_volume_space_size_offset);
810 	if (volume_block <= SYSTEM_AREA_BLOCK+4)
811 		return (0);
812 
813 	/* File structure version must be 2 for ISO9660:1999. */
814 	if (h[PVD_file_structure_version_offset] != 2)
815 		return (0);
816 
817 	/* Location of Occurrence of Type L Path Table must be
818 	 * available location,
819 	 * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */
820 	location = archive_le32dec(h+PVD_type_1_path_table_offset);
821 	if (location < SYSTEM_AREA_BLOCK+2 || location >= volume_block)
822 		return (0);
823 
824 	/* Location of Occurrence of Type M Path Table must be
825 	 * available location,
826 	 * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */
827 	location = archive_be32dec(h+PVD_type_m_path_table_offset);
828 	if ((location > 0 && location < SYSTEM_AREA_BLOCK+2)
829 	    || location >= volume_block)
830 		return (0);
831 
832 	/* Reserved field must be 0. */
833 	for (i = 0; i < PVD_reserved4_size; ++i)
834 		if (h[PVD_reserved4_offset + i] != 0)
835 			return (0);
836 
837 	/* Reserved field must be 0. */
838 	for (i = 0; i < PVD_reserved5_size; ++i)
839 		if (h[PVD_reserved5_offset + i] != 0)
840 			return (0);
841 
842 	/* Read Root Directory Record in Volume Descriptor. */
843 	p = h + PVD_root_directory_record_offset;
844 	if (p[DR_length_offset] != 34)
845 		return (0);
846 
847 	return (48);
848 }
849 
850 static int
851 isPVD(struct iso9660 *iso9660, const unsigned char *h)
852 {
853 	const unsigned char *p;
854 	ssize_t logical_block_size;
855 	int32_t volume_block;
856 	int32_t location;
857 	int i;
858 
859 	/* Type of the Primary Volume Descriptor must be 1. */
860 	if (h[PVD_type_offset] != 1)
861 		return (0);
862 
863 	/* PVD version must be 1. */
864 	if (h[PVD_version_offset] != 1)
865 		return (0);
866 
867 	/* Reserved field must be 0. */
868 	if (h[PVD_reserved1_offset] != 0)
869 		return (0);
870 
871 	/* Reserved field must be 0. */
872 	for (i = 0; i < PVD_reserved2_size; ++i)
873 		if (h[PVD_reserved2_offset + i] != 0)
874 			return (0);
875 
876 	/* Reserved field must be 0. */
877 	for (i = 0; i < PVD_reserved3_size; ++i)
878 		if (h[PVD_reserved3_offset + i] != 0)
879 			return (0);
880 
881 	/* Logical block size must be > 0. */
882 	/* I've looked at Ecma 119 and can't find any stronger
883 	 * restriction on this field. */
884 	logical_block_size =
885 	    archive_le16dec(h + PVD_logical_block_size_offset);
886 	if (logical_block_size <= 0)
887 		return (0);
888 
889 	volume_block = archive_le32dec(h + PVD_volume_space_size_offset);
890 	if (volume_block <= SYSTEM_AREA_BLOCK+4)
891 		return (0);
892 
893 	/* File structure version must be 1 for ISO9660/ECMA119. */
894 	if (h[PVD_file_structure_version_offset] != 1)
895 		return (0);
896 
897 	/* Location of Occurrence of Type L Path Table must be
898 	 * available location,
899 	 * > SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */
900 	location = archive_le32dec(h+PVD_type_1_path_table_offset);
901 	if (location < SYSTEM_AREA_BLOCK+2 || location >= volume_block)
902 		return (0);
903 
904 	/* The Type M Path Table must also be at a valid location
905 	 * (although ECMA 119 requires a Type M Path Table, WinISO and
906 	 * probably other programs omit it, so we permit a zero here)
907 	 *
908 	 * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */
909 	location = archive_be32dec(h+PVD_type_m_path_table_offset);
910 	if ((location > 0 && location < SYSTEM_AREA_BLOCK+2)
911 	    || location >= volume_block)
912 		return (0);
913 
914 	/* Reserved field must be 0. */
915 	/* But accept NetBSD/FreeBSD "makefs" images with 0x20 here. */
916 	for (i = 0; i < PVD_reserved4_size; ++i)
917 		if (h[PVD_reserved4_offset + i] != 0
918 		    && h[PVD_reserved4_offset + i] != 0x20)
919 			return (0);
920 
921 	/* Reserved field must be 0. */
922 	for (i = 0; i < PVD_reserved5_size; ++i)
923 		if (h[PVD_reserved5_offset + i] != 0)
924 			return (0);
925 
926 	/* XXX TODO: Check other values for sanity; reject more
927 	 * malformed PVDs. XXX */
928 
929 	/* Read Root Directory Record in Volume Descriptor. */
930 	p = h + PVD_root_directory_record_offset;
931 	if (p[DR_length_offset] != 34)
932 		return (0);
933 
934 	if (!iso9660->primary.location) {
935 		iso9660->logical_block_size = logical_block_size;
936 		iso9660->volume_block = volume_block;
937 		iso9660->volume_size = logical_block_size * (uint64_t)volume_block;
938 		iso9660->primary.location = archive_le32dec(p + DR_extent_offset);
939 		iso9660->primary.size = archive_le32dec(p + DR_size_offset);
940 	}
941 
942 	return (48);
943 }
944 
945 static int
946 read_children(struct archive_read *a, struct file_info *parent)
947 {
948 	struct iso9660 *iso9660;
949 	const unsigned char *b, *p;
950 	struct file_info *multi;
951 	size_t step, skip_size;
952 
953 	iso9660 = (struct iso9660 *)(a->format->data);
954 	if (iso9660->current_position > parent->offset) {
955 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
956 		    "Ignoring out-of-order directory (%s) %jd > %jd",
957 		    parent->name.s,
958 		    (intmax_t)iso9660->current_position,
959 		    (intmax_t)parent->offset);
960 		return (ARCHIVE_WARN);
961 	}
962 	if (parent->offset + parent->size > iso9660->volume_size) {
963 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
964 		    "Directory is beyond end-of-media: %s",
965 		    parent->name.s);
966 		return (ARCHIVE_WARN);
967 	}
968 	if (iso9660->current_position < parent->offset) {
969 		int64_t skipsize;
970 
971 		skipsize = parent->offset - iso9660->current_position;
972 		skipsize = __archive_read_consume(a, skipsize);
973 		if (skipsize < 0)
974 			return ((int)skipsize);
975 		iso9660->current_position = parent->offset;
976 	}
977 
978 	step = ((parent->size + iso9660->logical_block_size -1) /
979 	    iso9660->logical_block_size) * iso9660->logical_block_size;
980 	b = __archive_read_ahead(a, step, NULL);
981 	if (b == NULL) {
982 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
983 		    "Failed to read full block when scanning "
984 		    "ISO9660 directory list");
985 		return (ARCHIVE_FATAL);
986 	}
987 	iso9660->current_position += step;
988 	multi = NULL;
989 	skip_size = step;
990 	while (step) {
991 		p = b;
992 		b += iso9660->logical_block_size;
993 		step -= iso9660->logical_block_size;
994 		for (; *p != 0 && p < b && p + *p <= b; p += *p) {
995 			struct file_info *child;
996 
997 			/* N.B.: these special directory identifiers
998 			 * are 8 bit "values" even on a
999 			 * Joliet CD with UCS-2 (16bit) encoding.
1000 			 */
1001 
1002 			/* Skip '.' entry. */
1003 			if (*(p + DR_name_len_offset) == 1
1004 			    && *(p + DR_name_offset) == '\0')
1005 				continue;
1006 			/* Skip '..' entry. */
1007 			if (*(p + DR_name_len_offset) == 1
1008 			    && *(p + DR_name_offset) == '\001')
1009 				continue;
1010 			child = parse_file_info(a, parent, p);
1011 			if (child == NULL) {
1012 				__archive_read_consume(a, skip_size);
1013 				return (ARCHIVE_FATAL);
1014 			}
1015 			if (child->cl_offset == 0 &&
1016 			    (child->multi_extent || multi != NULL)) {
1017 				struct content *con;
1018 
1019 				if (multi == NULL) {
1020 					multi = child;
1021 					multi->contents.first = NULL;
1022 					multi->contents.last =
1023 					    &(multi->contents.first);
1024 				}
1025 				con = malloc(sizeof(struct content));
1026 				if (con == NULL) {
1027 					archive_set_error(
1028 					    &a->archive, ENOMEM,
1029 					    "No memory for multi extent");
1030 					__archive_read_consume(a, skip_size);
1031 					return (ARCHIVE_FATAL);
1032 				}
1033 				con->offset = child->offset;
1034 				con->size = child->size;
1035 				con->next = NULL;
1036 				*multi->contents.last = con;
1037 				multi->contents.last = &(con->next);
1038 				if (multi == child) {
1039 					if (add_entry(a, iso9660, child)
1040 					    != ARCHIVE_OK)
1041 						return (ARCHIVE_FATAL);
1042 				} else {
1043 					multi->size += child->size;
1044 					if (!child->multi_extent)
1045 						multi = NULL;
1046 				}
1047 			} else
1048 				if (add_entry(a, iso9660, child) != ARCHIVE_OK)
1049 					return (ARCHIVE_FATAL);
1050 		}
1051 	}
1052 
1053 	__archive_read_consume(a, skip_size);
1054 
1055 	/* Read data which recorded by RRIP "CE" extension. */
1056 	if (read_CE(a, iso9660) != ARCHIVE_OK)
1057 		return (ARCHIVE_FATAL);
1058 
1059 	return (ARCHIVE_OK);
1060 }
1061 
1062 static int
1063 archive_read_format_iso9660_read_header(struct archive_read *a,
1064     struct archive_entry *entry)
1065 {
1066 	struct iso9660 *iso9660;
1067 	struct file_info *file;
1068 	int r, rd_r = ARCHIVE_OK;
1069 
1070 	iso9660 = (struct iso9660 *)(a->format->data);
1071 
1072 	if (!a->archive.archive_format) {
1073 		a->archive.archive_format = ARCHIVE_FORMAT_ISO9660;
1074 		a->archive.archive_format_name = "ISO9660";
1075 	}
1076 
1077 	if (iso9660->current_position == 0) {
1078 		int64_t skipsize;
1079 		struct vd *vd;
1080 		const void *block;
1081 		char seenJoliet;
1082 
1083 		vd = &(iso9660->primary);
1084 		if (!iso9660->opt_support_joliet)
1085 			iso9660->seenJoliet = 0;
1086 		if (iso9660->seenJoliet &&
1087 			vd->location > iso9660->joliet.location)
1088 			/* This condition is unlikely; by way of caution. */
1089 			vd = &(iso9660->joliet);
1090 
1091 		skipsize = LOGICAL_BLOCK_SIZE * vd->location;
1092 		skipsize = __archive_read_consume(a, skipsize);
1093 		if (skipsize < 0)
1094 			return ((int)skipsize);
1095 		iso9660->current_position = skipsize;
1096 
1097 		block = __archive_read_ahead(a, vd->size, NULL);
1098 		if (block == NULL) {
1099 			archive_set_error(&a->archive,
1100 			    ARCHIVE_ERRNO_MISC,
1101 			    "Failed to read full block when scanning "
1102 			    "ISO9660 directory list");
1103 			return (ARCHIVE_FATAL);
1104 		}
1105 
1106 		/*
1107 		 * While reading Root Directory, flag seenJoliet
1108 		 * must be zero to avoid converting special name
1109 		 * 0x00(Current Directory) and next byte to UCS2.
1110 		 */
1111 		seenJoliet = iso9660->seenJoliet;/* Save flag. */
1112 		iso9660->seenJoliet = 0;
1113 		file = parse_file_info(a, NULL, block);
1114 		if (file == NULL)
1115 			return (ARCHIVE_FATAL);
1116 		iso9660->seenJoliet = seenJoliet;
1117 		if (vd == &(iso9660->primary) && iso9660->seenRockridge
1118 		    && iso9660->seenJoliet)
1119 			/*
1120 			 * If iso image has RockRidge and Joliet,
1121 			 * we use RockRidge Extensions.
1122 			 */
1123 			iso9660->seenJoliet = 0;
1124 		if (vd == &(iso9660->primary) && !iso9660->seenRockridge
1125 		    && iso9660->seenJoliet) {
1126 			/* Switch reading data from primary to joliet. */
1127 			vd = &(iso9660->joliet);
1128 			skipsize = LOGICAL_BLOCK_SIZE * vd->location;
1129 			skipsize -= iso9660->current_position;
1130 			skipsize = __archive_read_consume(a, skipsize);
1131 			if (skipsize < 0)
1132 				return ((int)skipsize);
1133 			iso9660->current_position += skipsize;
1134 
1135 			block = __archive_read_ahead(a, vd->size, NULL);
1136 			if (block == NULL) {
1137 				archive_set_error(&a->archive,
1138 				    ARCHIVE_ERRNO_MISC,
1139 				    "Failed to read full block when scanning "
1140 				    "ISO9660 directory list");
1141 				return (ARCHIVE_FATAL);
1142 			}
1143 			iso9660->seenJoliet = 0;
1144 			file = parse_file_info(a, NULL, block);
1145 			if (file == NULL)
1146 				return (ARCHIVE_FATAL);
1147 			iso9660->seenJoliet = seenJoliet;
1148 		}
1149 		/* Store the root directory in the pending list. */
1150 		if (add_entry(a, iso9660, file) != ARCHIVE_OK)
1151 			return (ARCHIVE_FATAL);
1152 		if (iso9660->seenRockridge) {
1153 			a->archive.archive_format =
1154 			    ARCHIVE_FORMAT_ISO9660_ROCKRIDGE;
1155 			a->archive.archive_format_name =
1156 			    "ISO9660 with Rockridge extensions";
1157 		}
1158 	}
1159 
1160 	file = NULL;/* Eliminate a warning. */
1161 	/* Get the next entry that appears after the current offset. */
1162 	r = next_entry_seek(a, iso9660, &file);
1163 	if (r != ARCHIVE_OK)
1164 		return (r);
1165 
1166 	if (iso9660->seenJoliet) {
1167 		/*
1168 		 * Convert UTF-16BE of a filename to local locale MBS
1169 		 * and store the result into a filename field.
1170 		 */
1171 		if (iso9660->sconv_utf16be == NULL) {
1172 			iso9660->sconv_utf16be =
1173 			    archive_string_conversion_from_charset(
1174 				&(a->archive), "UTF-16BE", 1);
1175 			if (iso9660->sconv_utf16be == NULL)
1176 				/* Coundn't allocate memory */
1177 				return (ARCHIVE_FATAL);
1178 		}
1179 		if (iso9660->utf16be_path == NULL) {
1180 			iso9660->utf16be_path = malloc(UTF16_NAME_MAX);
1181 			if (iso9660->utf16be_path == NULL) {
1182 				archive_set_error(&a->archive, ENOMEM,
1183 				    "No memory");
1184 				return (ARCHIVE_FATAL);
1185 			}
1186 		}
1187 		if (iso9660->utf16be_previous_path == NULL) {
1188 			iso9660->utf16be_previous_path = malloc(UTF16_NAME_MAX);
1189 			if (iso9660->utf16be_previous_path == NULL) {
1190 				archive_set_error(&a->archive, ENOMEM,
1191 				    "No memory");
1192 				return (ARCHIVE_FATAL);
1193 			}
1194 		}
1195 
1196 		iso9660->utf16be_path_len = 0;
1197 		if (build_pathname_utf16be(iso9660->utf16be_path,
1198 		    UTF16_NAME_MAX, &(iso9660->utf16be_path_len), file) != 0) {
1199 			archive_set_error(&a->archive,
1200 			    ARCHIVE_ERRNO_FILE_FORMAT,
1201 			    "Pathname is too long");
1202 		}
1203 
1204 		r = archive_entry_copy_pathname_l(entry,
1205 		    (const char *)iso9660->utf16be_path,
1206 		    iso9660->utf16be_path_len,
1207 		    iso9660->sconv_utf16be);
1208 		if (r != 0) {
1209 			if (errno == ENOMEM) {
1210 				archive_set_error(&a->archive, ENOMEM,
1211 				    "No memory for Pathname");
1212 				return (ARCHIVE_FATAL);
1213 			}
1214 			archive_set_error(&a->archive,
1215 			    ARCHIVE_ERRNO_FILE_FORMAT,
1216 			    "Pathname cannot be converted "
1217 			    "from %s to current locale.",
1218 			    archive_string_conversion_charset_name(
1219 			      iso9660->sconv_utf16be));
1220 
1221 			rd_r = ARCHIVE_WARN;
1222 		}
1223 	} else {
1224 		archive_string_empty(&iso9660->pathname);
1225 		archive_entry_set_pathname(entry,
1226 		    build_pathname(&iso9660->pathname, file));
1227 	}
1228 
1229 	iso9660->entry_bytes_remaining = file->size;
1230 	iso9660->entry_sparse_offset = 0; /* Offset for sparse-file-aware clients. */
1231 
1232 	if (file->offset + file->size > iso9660->volume_size) {
1233 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1234 		    "File is beyond end-of-media: %s",
1235 		    archive_entry_pathname(entry));
1236 		iso9660->entry_bytes_remaining = 0;
1237 		iso9660->entry_sparse_offset = 0;
1238 		return (ARCHIVE_WARN);
1239 	}
1240 
1241 	/* Set up the entry structure with information about this entry. */
1242 	archive_entry_set_mode(entry, file->mode);
1243 	archive_entry_set_uid(entry, file->uid);
1244 	archive_entry_set_gid(entry, file->gid);
1245 	archive_entry_set_nlink(entry, file->nlinks);
1246 	if (file->birthtime_is_set)
1247 		archive_entry_set_birthtime(entry, file->birthtime, 0);
1248 	else
1249 		archive_entry_unset_birthtime(entry);
1250 	archive_entry_set_mtime(entry, file->mtime, 0);
1251 	archive_entry_set_ctime(entry, file->ctime, 0);
1252 	archive_entry_set_atime(entry, file->atime, 0);
1253 	/* N.B.: Rock Ridge supports 64-bit device numbers. */
1254 	archive_entry_set_rdev(entry, (dev_t)file->rdev);
1255 	archive_entry_set_size(entry, iso9660->entry_bytes_remaining);
1256 	if (file->symlink.s != NULL)
1257 		archive_entry_copy_symlink(entry, file->symlink.s);
1258 
1259 	/* Note: If the input isn't seekable, we can't rewind to
1260 	 * return the same body again, so if the next entry refers to
1261 	 * the same data, we have to return it as a hardlink to the
1262 	 * original entry. */
1263 	if (file->number != -1 &&
1264 	    file->number == iso9660->previous_number) {
1265 		if (iso9660->seenJoliet) {
1266 			r = archive_entry_copy_hardlink_l(entry,
1267 			    (const char *)iso9660->utf16be_previous_path,
1268 			    iso9660->utf16be_previous_path_len,
1269 			    iso9660->sconv_utf16be);
1270 			if (r != 0) {
1271 				if (errno == ENOMEM) {
1272 					archive_set_error(&a->archive, ENOMEM,
1273 					    "No memory for Linkname");
1274 					return (ARCHIVE_FATAL);
1275 				}
1276 				archive_set_error(&a->archive,
1277 				    ARCHIVE_ERRNO_FILE_FORMAT,
1278 				    "Linkname cannot be converted "
1279 				    "from %s to current locale.",
1280 				    archive_string_conversion_charset_name(
1281 				      iso9660->sconv_utf16be));
1282 				rd_r = ARCHIVE_WARN;
1283 			}
1284 		} else
1285 			archive_entry_set_hardlink(entry,
1286 			    iso9660->previous_pathname.s);
1287 		archive_entry_unset_size(entry);
1288 		iso9660->entry_bytes_remaining = 0;
1289 		iso9660->entry_sparse_offset = 0;
1290 		return (rd_r);
1291 	}
1292 
1293 	/* Except for the hardlink case above, if the offset of the
1294 	 * next entry is before our current position, we can't seek
1295 	 * backwards to extract it, so issue a warning.  Note that
1296 	 * this can only happen if this entry was added to the heap
1297 	 * after we passed this offset, that is, only if the directory
1298 	 * mentioning this entry is later than the body of the entry.
1299 	 * Such layouts are very unusual; most ISO9660 writers lay out
1300 	 * and record all directory information first, then store
1301 	 * all file bodies. */
1302 	/* TODO: Someday, libarchive's I/O core will support optional
1303 	 * seeking.  When that day comes, this code should attempt to
1304 	 * seek and only return the error if the seek fails.  That
1305 	 * will give us support for whacky ISO images that require
1306 	 * seeking while retaining the ability to read almost all ISO
1307 	 * images in a streaming fashion. */
1308 	if ((file->mode & AE_IFMT) != AE_IFDIR &&
1309 	    file->offset < iso9660->current_position) {
1310 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1311 		    "Ignoring out-of-order file @%jx (%s) %jd < %jd",
1312 		    (intmax_t)file->number,
1313 		    iso9660->pathname.s,
1314 		    (intmax_t)file->offset,
1315 		    (intmax_t)iso9660->current_position);
1316 		iso9660->entry_bytes_remaining = 0;
1317 		iso9660->entry_sparse_offset = 0;
1318 		return (ARCHIVE_WARN);
1319 	}
1320 
1321 	/* Initialize zisofs variables. */
1322 	iso9660->entry_zisofs.pz = file->pz;
1323 	if (file->pz) {
1324 #ifdef HAVE_ZLIB_H
1325 		struct zisofs  *zisofs;
1326 
1327 		zisofs = &iso9660->entry_zisofs;
1328 		zisofs->initialized = 0;
1329 		zisofs->pz_log2_bs = file->pz_log2_bs;
1330 		zisofs->pz_uncompressed_size = file->pz_uncompressed_size;
1331 		zisofs->pz_offset = 0;
1332 		zisofs->header_avail = 0;
1333 		zisofs->header_passed = 0;
1334 		zisofs->block_pointers_avail = 0;
1335 #endif
1336 		archive_entry_set_size(entry, file->pz_uncompressed_size);
1337 	}
1338 
1339 	iso9660->previous_number = file->number;
1340 	if (iso9660->seenJoliet) {
1341 		memcpy(iso9660->utf16be_previous_path, iso9660->utf16be_path,
1342 		    iso9660->utf16be_path_len);
1343 		iso9660->utf16be_previous_path_len = iso9660->utf16be_path_len;
1344 	} else
1345 		archive_strcpy(
1346 		    &iso9660->previous_pathname, iso9660->pathname.s);
1347 
1348 	/* Reset entry_bytes_remaining if the file is multi extent. */
1349 	iso9660->entry_content = file->contents.first;
1350 	if (iso9660->entry_content != NULL)
1351 		iso9660->entry_bytes_remaining = iso9660->entry_content->size;
1352 
1353 	if (archive_entry_filetype(entry) == AE_IFDIR) {
1354 		/* Overwrite nlinks by proper link number which is
1355 		 * calculated from number of sub directories. */
1356 		archive_entry_set_nlink(entry, 2 + file->subdirs);
1357 		/* Directory data has been read completely. */
1358 		iso9660->entry_bytes_remaining = 0;
1359 		iso9660->entry_sparse_offset = 0;
1360 	}
1361 
1362 	if (rd_r != ARCHIVE_OK)
1363 		return (rd_r);
1364 	return (ARCHIVE_OK);
1365 }
1366 
1367 static int
1368 archive_read_format_iso9660_read_data_skip(struct archive_read *a)
1369 {
1370 	/* Because read_next_header always does an explicit skip
1371 	 * to the next entry, we don't need to do anything here. */
1372 	(void)a; /* UNUSED */
1373 	return (ARCHIVE_OK);
1374 }
1375 
1376 #ifdef HAVE_ZLIB_H
1377 
1378 static int
1379 zisofs_read_data(struct archive_read *a,
1380     const void **buff, size_t *size, int64_t *offset)
1381 {
1382 	struct iso9660 *iso9660;
1383 	struct zisofs  *zisofs;
1384 	const unsigned char *p;
1385 	size_t avail;
1386 	ssize_t bytes_read;
1387 	size_t uncompressed_size;
1388 	int r;
1389 
1390 	iso9660 = (struct iso9660 *)(a->format->data);
1391 	zisofs = &iso9660->entry_zisofs;
1392 
1393 	p = __archive_read_ahead(a, 1, &bytes_read);
1394 	if (bytes_read <= 0) {
1395 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1396 		    "Truncated zisofs file body");
1397 		return (ARCHIVE_FATAL);
1398 	}
1399 	if (bytes_read > iso9660->entry_bytes_remaining)
1400 		bytes_read = iso9660->entry_bytes_remaining;
1401 	avail = bytes_read;
1402 	uncompressed_size = 0;
1403 
1404 	if (!zisofs->initialized) {
1405 		size_t ceil, xsize;
1406 
1407 		/* Allocate block pointers buffer. */
1408 		ceil = (zisofs->pz_uncompressed_size +
1409 			(1LL << zisofs->pz_log2_bs) - 1)
1410 			>> zisofs->pz_log2_bs;
1411 		xsize = (ceil + 1) * 4;
1412 		if (zisofs->block_pointers_alloc < xsize) {
1413 			size_t alloc;
1414 
1415 			if (zisofs->block_pointers != NULL)
1416 				free(zisofs->block_pointers);
1417 			alloc = ((xsize >> 10) + 1) << 10;
1418 			zisofs->block_pointers = malloc(alloc);
1419 			if (zisofs->block_pointers == NULL) {
1420 				archive_set_error(&a->archive, ENOMEM,
1421 				    "No memory for zisofs decompression");
1422 				return (ARCHIVE_FATAL);
1423 			}
1424 			zisofs->block_pointers_alloc = alloc;
1425 		}
1426 		zisofs->block_pointers_size = xsize;
1427 
1428 		/* Allocate uncompressed data buffer. */
1429 		xsize = 1UL << zisofs->pz_log2_bs;
1430 		if (zisofs->uncompressed_buffer_size < xsize) {
1431 			if (zisofs->uncompressed_buffer != NULL)
1432 				free(zisofs->uncompressed_buffer);
1433 			zisofs->uncompressed_buffer = malloc(xsize);
1434 			if (zisofs->uncompressed_buffer == NULL) {
1435 				archive_set_error(&a->archive, ENOMEM,
1436 				    "No memory for zisofs decompression");
1437 				return (ARCHIVE_FATAL);
1438 			}
1439 		}
1440 		zisofs->uncompressed_buffer_size = xsize;
1441 
1442 		/*
1443 		 * Read the file header, and check the magic code of zisofs.
1444 		 */
1445 		if (zisofs->header_avail < sizeof(zisofs->header)) {
1446 			xsize = sizeof(zisofs->header) - zisofs->header_avail;
1447 			if (avail < xsize)
1448 				xsize = avail;
1449 			memcpy(zisofs->header + zisofs->header_avail, p, xsize);
1450 			zisofs->header_avail += xsize;
1451 			avail -= xsize;
1452 			p += xsize;
1453 		}
1454 		if (!zisofs->header_passed &&
1455 		    zisofs->header_avail == sizeof(zisofs->header)) {
1456 			int err = 0;
1457 
1458 			if (memcmp(zisofs->header, zisofs_magic,
1459 			    sizeof(zisofs_magic)) != 0)
1460 				err = 1;
1461 			if (archive_le32dec(zisofs->header + 8)
1462 			    != zisofs->pz_uncompressed_size)
1463 				err = 1;
1464 			if (zisofs->header[12] != 4)
1465 				err = 1;
1466 			if (zisofs->header[13] != zisofs->pz_log2_bs)
1467 				err = 1;
1468 			if (err) {
1469 				archive_set_error(&a->archive,
1470 				    ARCHIVE_ERRNO_FILE_FORMAT,
1471 				    "Illegal zisofs file body");
1472 				return (ARCHIVE_FATAL);
1473 			}
1474 			zisofs->header_passed = 1;
1475 		}
1476 		/*
1477 		 * Read block pointers.
1478 		 */
1479 		if (zisofs->header_passed &&
1480 		    zisofs->block_pointers_avail < zisofs->block_pointers_size) {
1481 			xsize = zisofs->block_pointers_size
1482 			    - zisofs->block_pointers_avail;
1483 			if (avail < xsize)
1484 				xsize = avail;
1485 			memcpy(zisofs->block_pointers
1486 			    + zisofs->block_pointers_avail, p, xsize);
1487 			zisofs->block_pointers_avail += xsize;
1488 			avail -= xsize;
1489 			p += xsize;
1490 		    	if (zisofs->block_pointers_avail
1491 			    == zisofs->block_pointers_size) {
1492 				/* We've got all block pointers and initialize
1493 				 * related variables.	*/
1494 				zisofs->block_off = 0;
1495 				zisofs->block_avail = 0;
1496 				/* Complete a initialization */
1497 				zisofs->initialized = 1;
1498 			}
1499 		}
1500 
1501 		if (!zisofs->initialized)
1502 			goto next_data; /* We need more data. */
1503 	}
1504 
1505 	/*
1506 	 * Get block offsets from block pointers.
1507 	 */
1508 	if (zisofs->block_avail == 0) {
1509 		uint32_t bst, bed;
1510 
1511 		if (zisofs->block_off + 4 >= zisofs->block_pointers_size) {
1512 			/* There isn't a pair of offsets. */
1513 			archive_set_error(&a->archive,
1514 			    ARCHIVE_ERRNO_FILE_FORMAT,
1515 			    "Illegal zisofs block pointers");
1516 			return (ARCHIVE_FATAL);
1517 		}
1518 		bst = archive_le32dec(
1519 		    zisofs->block_pointers + zisofs->block_off);
1520 		if (bst != zisofs->pz_offset + (bytes_read - avail)) {
1521 			/* TODO: Should we seek offset of current file
1522 			 * by bst ? */
1523 			archive_set_error(&a->archive,
1524 			    ARCHIVE_ERRNO_FILE_FORMAT,
1525 			    "Illegal zisofs block pointers(cannot seek)");
1526 			return (ARCHIVE_FATAL);
1527 		}
1528 		bed = archive_le32dec(
1529 		    zisofs->block_pointers + zisofs->block_off + 4);
1530 		if (bed < bst) {
1531 			archive_set_error(&a->archive,
1532 			    ARCHIVE_ERRNO_FILE_FORMAT,
1533 			    "Illegal zisofs block pointers");
1534 			return (ARCHIVE_FATAL);
1535 		}
1536 		zisofs->block_avail = bed - bst;
1537 		zisofs->block_off += 4;
1538 
1539 		/* Initialize compression library for new block. */
1540 		if (zisofs->stream_valid)
1541 			r = inflateReset(&zisofs->stream);
1542 		else
1543 			r = inflateInit(&zisofs->stream);
1544 		if (r != Z_OK) {
1545 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1546 			    "Can't initialize zisofs decompression.");
1547 			return (ARCHIVE_FATAL);
1548 		}
1549 		zisofs->stream_valid = 1;
1550 		zisofs->stream.total_in = 0;
1551 		zisofs->stream.total_out = 0;
1552 	}
1553 
1554 	/*
1555 	 * Make uncompressed data.
1556 	 */
1557 	if (zisofs->block_avail == 0) {
1558 		memset(zisofs->uncompressed_buffer, 0,
1559 		    zisofs->uncompressed_buffer_size);
1560 		uncompressed_size = zisofs->uncompressed_buffer_size;
1561 	} else {
1562 		zisofs->stream.next_in = (Bytef *)(uintptr_t)(const void *)p;
1563 		if (avail > zisofs->block_avail)
1564 			zisofs->stream.avail_in = zisofs->block_avail;
1565 		else
1566 			zisofs->stream.avail_in = avail;
1567 		zisofs->stream.next_out = zisofs->uncompressed_buffer;
1568 		zisofs->stream.avail_out = zisofs->uncompressed_buffer_size;
1569 
1570 		r = inflate(&zisofs->stream, 0);
1571 		switch (r) {
1572 		case Z_OK: /* Decompressor made some progress.*/
1573 		case Z_STREAM_END: /* Found end of stream. */
1574 			break;
1575 		default:
1576 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1577 			    "zisofs decompression failed (%d)", r);
1578 			return (ARCHIVE_FATAL);
1579 		}
1580 		uncompressed_size =
1581 		    zisofs->uncompressed_buffer_size - zisofs->stream.avail_out;
1582 		avail -= zisofs->stream.next_in - p;
1583 		zisofs->block_avail -= zisofs->stream.next_in - p;
1584 	}
1585 next_data:
1586 	bytes_read -= avail;
1587 	*buff = zisofs->uncompressed_buffer;
1588 	*size = uncompressed_size;
1589 	*offset = iso9660->entry_sparse_offset;
1590 	iso9660->entry_sparse_offset += uncompressed_size;
1591 	iso9660->entry_bytes_remaining -= bytes_read;
1592 	iso9660->current_position += bytes_read;
1593 	zisofs->pz_offset += bytes_read;
1594 	iso9660->entry_bytes_unconsumed += bytes_read;
1595 
1596 	return (ARCHIVE_OK);
1597 }
1598 
1599 #else /* HAVE_ZLIB_H */
1600 
1601 static int
1602 zisofs_read_data(struct archive_read *a,
1603     const void **buff, size_t *size, int64_t *offset)
1604 {
1605 
1606 	(void)buff;/* UNUSED */
1607 	(void)size;/* UNUSED */
1608 	(void)offset;/* UNUSED */
1609 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1610 	    "zisofs is not supported on this platform.");
1611 	return (ARCHIVE_FAILED);
1612 }
1613 
1614 #endif /* HAVE_ZLIB_H */
1615 
1616 static int
1617 archive_read_format_iso9660_read_data(struct archive_read *a,
1618     const void **buff, size_t *size, int64_t *offset)
1619 {
1620 	ssize_t bytes_read;
1621 	struct iso9660 *iso9660;
1622 
1623 	iso9660 = (struct iso9660 *)(a->format->data);
1624 
1625 	if (iso9660->entry_bytes_unconsumed) {
1626 		__archive_read_consume(a, iso9660->entry_bytes_unconsumed);
1627 		iso9660->entry_bytes_unconsumed = 0;
1628 	}
1629 
1630 	if (iso9660->entry_bytes_remaining <= 0) {
1631 		if (iso9660->entry_content != NULL)
1632 			iso9660->entry_content = iso9660->entry_content->next;
1633 		if (iso9660->entry_content == NULL) {
1634 			*buff = NULL;
1635 			*size = 0;
1636 			*offset = iso9660->entry_sparse_offset;
1637 			return (ARCHIVE_EOF);
1638 		}
1639 		/* Seek forward to the start of the entry. */
1640 		if (iso9660->current_position < iso9660->entry_content->offset) {
1641 			int64_t step;
1642 
1643 			step = iso9660->entry_content->offset -
1644 			    iso9660->current_position;
1645 			step = __archive_read_consume(a, step);
1646 			if (step < 0)
1647 				return ((int)step);
1648 			iso9660->current_position =
1649 			    iso9660->entry_content->offset;
1650 		}
1651 		if (iso9660->entry_content->offset < iso9660->current_position) {
1652 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1653 			    "Ignoring out-of-order file (%s) %jd < %jd",
1654 			    iso9660->pathname.s,
1655 			    (intmax_t)iso9660->entry_content->offset,
1656 			    (intmax_t)iso9660->current_position);
1657 			*buff = NULL;
1658 			*size = 0;
1659 			*offset = iso9660->entry_sparse_offset;
1660 			return (ARCHIVE_WARN);
1661 		}
1662 		iso9660->entry_bytes_remaining = iso9660->entry_content->size;
1663 	}
1664 	if (iso9660->entry_zisofs.pz)
1665 		return (zisofs_read_data(a, buff, size, offset));
1666 
1667 	*buff = __archive_read_ahead(a, 1, &bytes_read);
1668 	if (bytes_read == 0)
1669 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1670 		    "Truncated input file");
1671 	if (*buff == NULL)
1672 		return (ARCHIVE_FATAL);
1673 	if (bytes_read > iso9660->entry_bytes_remaining)
1674 		bytes_read = iso9660->entry_bytes_remaining;
1675 	*size = bytes_read;
1676 	*offset = iso9660->entry_sparse_offset;
1677 	iso9660->entry_sparse_offset += bytes_read;
1678 	iso9660->entry_bytes_remaining -= bytes_read;
1679 	iso9660->entry_bytes_unconsumed = bytes_read;
1680 	iso9660->current_position += bytes_read;
1681 	return (ARCHIVE_OK);
1682 }
1683 
1684 static int
1685 archive_read_format_iso9660_cleanup(struct archive_read *a)
1686 {
1687 	struct iso9660 *iso9660;
1688 	int r = ARCHIVE_OK;
1689 
1690 	iso9660 = (struct iso9660 *)(a->format->data);
1691 	release_files(iso9660);
1692 	free(iso9660->read_ce_req.reqs);
1693 	archive_string_free(&iso9660->pathname);
1694 	archive_string_free(&iso9660->previous_pathname);
1695 	if (iso9660->pending_files.files)
1696 		free(iso9660->pending_files.files);
1697 #ifdef HAVE_ZLIB_H
1698 	free(iso9660->entry_zisofs.uncompressed_buffer);
1699 	free(iso9660->entry_zisofs.block_pointers);
1700 	if (iso9660->entry_zisofs.stream_valid) {
1701 		if (inflateEnd(&iso9660->entry_zisofs.stream) != Z_OK) {
1702 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1703 			    "Failed to clean up zlib decompressor");
1704 			r = ARCHIVE_FATAL;
1705 		}
1706 	}
1707 #endif
1708 	free(iso9660->utf16be_path);
1709 	free(iso9660->utf16be_previous_path);
1710 	free(iso9660);
1711 	(a->format->data) = NULL;
1712 	return (r);
1713 }
1714 
1715 /*
1716  * This routine parses a single ISO directory record, makes sense
1717  * of any extensions, and stores the result in memory.
1718  */
1719 static struct file_info *
1720 parse_file_info(struct archive_read *a, struct file_info *parent,
1721     const unsigned char *isodirrec)
1722 {
1723 	struct iso9660 *iso9660;
1724 	struct file_info *file;
1725 	size_t name_len;
1726 	const unsigned char *rr_start, *rr_end;
1727 	const unsigned char *p;
1728 	size_t dr_len;
1729 	uint64_t fsize;
1730 	int32_t location;
1731 	int flags;
1732 
1733 	iso9660 = (struct iso9660 *)(a->format->data);
1734 
1735 	dr_len = (size_t)isodirrec[DR_length_offset];
1736 	name_len = (size_t)isodirrec[DR_name_len_offset];
1737 	location = archive_le32dec(isodirrec + DR_extent_offset);
1738 	fsize = toi(isodirrec + DR_size_offset, DR_size_size);
1739 	/* Sanity check that dr_len needs at least 34. */
1740 	if (dr_len < 34) {
1741 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1742 		    "Invalid length of directory record");
1743 		return (NULL);
1744 	}
1745 	/* Sanity check that name_len doesn't exceed dr_len. */
1746 	if (dr_len - 33 < name_len || name_len == 0) {
1747 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1748 		    "Invalid length of file identifier");
1749 		return (NULL);
1750 	}
1751 	/* Sanity check that location doesn't exceed volume block.
1752 	 * Don't check lower limit of location; it's possibility
1753 	 * the location has negative value when file type is symbolic
1754 	 * link or file size is zero. As far as I know latest mkisofs
1755 	 * do that.
1756 	 */
1757 	if (location > 0 &&
1758 	    (location + ((fsize + iso9660->logical_block_size -1)
1759 	       / iso9660->logical_block_size)) > iso9660->volume_block) {
1760 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1761 		    "Invalid location of extent of file");
1762 		return (NULL);
1763 	}
1764 	/* Sanity check that location doesn't have a negative value
1765 	 * when the file is not empty. it's too large. */
1766 	if (fsize != 0 && location < 0) {
1767 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1768 		    "Invalid location of extent of file");
1769 		return (NULL);
1770 	}
1771 
1772 	/* Create a new file entry and copy data from the ISO dir record. */
1773 	file = (struct file_info *)calloc(1, sizeof(*file));
1774 	if (file == NULL) {
1775 		archive_set_error(&a->archive, ENOMEM,
1776 		    "No memory for file entry");
1777 		return (NULL);
1778 	}
1779 	file->parent = parent;
1780 	file->offset = iso9660->logical_block_size * (uint64_t)location;
1781 	file->size = fsize;
1782 	file->mtime = isodate7(isodirrec + DR_date_offset);
1783 	file->ctime = file->atime = file->mtime;
1784 	file->rede_files.first = NULL;
1785 	file->rede_files.last = &(file->rede_files.first);
1786 
1787 	p = isodirrec + DR_name_offset;
1788 	/* Rockridge extensions (if any) follow name.  Compute this
1789 	 * before fidgeting the name_len below. */
1790 	rr_start = p + name_len + (name_len & 1 ? 0 : 1);
1791 	rr_end = isodirrec + dr_len;
1792 
1793 	if (iso9660->seenJoliet) {
1794 		/* Joliet names are max 64 chars (128 bytes) according to spec,
1795 		 * but genisoimage/mkisofs allows recording longer Joliet
1796 		 * names which are 103 UCS2 characters(206 bytes) by their
1797 		 * option '-joliet-long'.
1798 		 */
1799 		if (name_len > 206)
1800 			name_len = 206;
1801 		name_len &= ~1;
1802 
1803 		/* trim trailing first version and dot from filename.
1804 		 *
1805 		 * Remember we were in UTF-16BE land!
1806 		 * SEPARATOR 1 (.) and SEPARATOR 2 (;) are both
1807 		 * 16 bits big endian characters on Joliet.
1808 		 *
1809 		 * TODO: sanitize filename?
1810 		 *       Joliet allows any UCS-2 char except:
1811 		 *       *, /, :, ;, ? and \.
1812 		 */
1813 		/* Chop off trailing ';1' from files. */
1814 		if (name_len > 4 && p[name_len-4] == 0 && p[name_len-3] == ';'
1815 		    && p[name_len-2] == 0 && p[name_len-1] == '1')
1816 			name_len -= 4;
1817 #if 0 /* XXX: this somehow manages to strip of single-character file extensions, like '.c'. */
1818 		/* Chop off trailing '.' from filenames. */
1819 		if (name_len > 2 && p[name_len-2] == 0 && p[name_len-1] == '.')
1820 			name_len -= 2;
1821 #endif
1822 		if ((file->utf16be_name = malloc(name_len)) == NULL) {
1823 			archive_set_error(&a->archive, ENOMEM,
1824 			    "No memory for file name");
1825 			return (NULL);
1826 		}
1827 		memcpy(file->utf16be_name, p, name_len);
1828 		file->utf16be_bytes = name_len;
1829 	} else {
1830 		/* Chop off trailing ';1' from files. */
1831 		if (name_len > 2 && p[name_len - 2] == ';' &&
1832 				p[name_len - 1] == '1')
1833 			name_len -= 2;
1834 		/* Chop off trailing '.' from filenames. */
1835 		if (name_len > 1 && p[name_len - 1] == '.')
1836 			--name_len;
1837 
1838 		archive_strncpy(&file->name, (const char *)p, name_len);
1839 	}
1840 
1841 	flags = isodirrec[DR_flags_offset];
1842 	if (flags & 0x02)
1843 		file->mode = AE_IFDIR | 0700;
1844 	else
1845 		file->mode = AE_IFREG | 0400;
1846 	if (flags & 0x80)
1847 		file->multi_extent = 1;
1848 	else
1849 		file->multi_extent = 0;
1850 	/*
1851 	 * Use a location for the file number, which is treated as an inode
1852 	 * number to find out hardlink target. If Rockridge extensions is
1853 	 * being used, the file number will be overwritten by FILE SERIAL
1854 	 * NUMBER of RRIP "PX" extension.
1855 	 * Note: Old mkisofs did not record that FILE SERIAL NUMBER
1856 	 * in ISO images.
1857 	 * Note2: xorriso set 0 to the location of a symlink file.
1858 	 */
1859 	if (file->size == 0 && location >= 0) {
1860 		/* If file->size is zero, its location points wrong place,
1861 		 * and so we should not use it for the file number.
1862 		 * When the location has negative value, it can be used
1863 		 * for the file number.
1864 		 */
1865 		file->number = -1;
1866 		/* Do not appear before any directory entries. */
1867 		file->offset = -1;
1868 	} else
1869 		file->number = (int64_t)(uint32_t)location;
1870 
1871 	/* Rockridge extensions overwrite information from above. */
1872 	if (iso9660->opt_support_rockridge) {
1873 		if (parent == NULL && rr_end - rr_start >= 7) {
1874 			p = rr_start;
1875 			if (p[0] == 'S' && p[1] == 'P'
1876 			    && p[2] == 7 && p[3] == 1
1877 			    && p[4] == 0xBE && p[5] == 0xEF) {
1878 				/*
1879 				 * SP extension stores the suspOffset
1880 				 * (Number of bytes to skip between
1881 				 * filename and SUSP records.)
1882 				 * It is mandatory by the SUSP standard
1883 				 * (IEEE 1281).
1884 				 *
1885 				 * It allows SUSP to coexist with
1886 				 * non-SUSP uses of the System
1887 				 * Use Area by placing non-SUSP data
1888 				 * before SUSP data.
1889 				 *
1890 				 * SP extension must be in the root
1891 				 * directory entry, disable all SUSP
1892 				 * processing if not found.
1893 				 */
1894 				iso9660->suspOffset = p[6];
1895 				iso9660->seenSUSP = 1;
1896 				rr_start += 7;
1897 			}
1898 		}
1899 		if (iso9660->seenSUSP) {
1900 			int r;
1901 
1902 			file->name_continues = 0;
1903 			file->symlink_continues = 0;
1904 			rr_start += iso9660->suspOffset;
1905 			r = parse_rockridge(a, file, rr_start, rr_end);
1906 			if (r != ARCHIVE_OK) {
1907 				free(file);
1908 				return (NULL);
1909 			}
1910 		} else
1911 			/* If there isn't SUSP, disable parsing
1912 			 * rock ridge extensions. */
1913 			iso9660->opt_support_rockridge = 0;
1914 	}
1915 
1916 	file->nlinks = 1;/* Reset nlink. we'll calculate it later. */
1917 	/* Tell file's parent how many children that parent has. */
1918 	if (parent != NULL && (flags & 0x02))
1919 		parent->subdirs++;
1920 
1921 	if (iso9660->seenRockridge) {
1922 		if (parent != NULL && parent->parent == NULL &&
1923 		    (flags & 0x02) && iso9660->rr_moved == NULL &&
1924 		    (strcmp(file->name.s, "rr_moved") == 0 ||
1925 		     strcmp(file->name.s, ".rr_moved") == 0)) {
1926 			iso9660->rr_moved = file;
1927 			file->rr_moved = 1;
1928 			file->rr_moved_has_re_only = 1;
1929 			file->re = 0;
1930 			parent->subdirs--;
1931 		} else if (file->re) {
1932 			/*
1933 			 * Sanity check: file's parent is rr_moved.
1934 			 */
1935 			if (parent == NULL || parent->rr_moved == 0) {
1936 				archive_set_error(&a->archive,
1937 				    ARCHIVE_ERRNO_MISC,
1938 				    "Invalid Rockridge RE");
1939 				return (NULL);
1940 			}
1941 			/*
1942 			 * Sanity check: file does not have "CL" extension.
1943 			 */
1944 			if (file->cl_offset) {
1945 				archive_set_error(&a->archive,
1946 				    ARCHIVE_ERRNO_MISC,
1947 				    "Invalid Rockridge RE and CL");
1948 				return (NULL);
1949 			}
1950 			/*
1951 			 * Sanity check: The file type must be a directory.
1952 			 */
1953 			if ((flags & 0x02) == 0) {
1954 				archive_set_error(&a->archive,
1955 				    ARCHIVE_ERRNO_MISC,
1956 				    "Invalid Rockridge RE");
1957 				return (NULL);
1958 			}
1959 		} else if (parent != NULL && parent->rr_moved)
1960 			file->rr_moved_has_re_only = 0;
1961 		else if (parent != NULL && (flags & 0x02) &&
1962 		    (parent->re || parent->re_descendant))
1963 			file->re_descendant = 1;
1964 		if (file->cl_offset) {
1965 			struct file_info *r;
1966 
1967 			if (parent == NULL || parent->parent == NULL) {
1968 				archive_set_error(&a->archive,
1969 				    ARCHIVE_ERRNO_MISC,
1970 				    "Invalid Rockridge CL");
1971 				return (NULL);
1972 			}
1973 			/*
1974 			 * Sanity check: The file type must be a regular file.
1975 			 */
1976 			if ((flags & 0x02) != 0) {
1977 				archive_set_error(&a->archive,
1978 				    ARCHIVE_ERRNO_MISC,
1979 				    "Invalid Rockridge CL");
1980 				return (NULL);
1981 			}
1982 			parent->subdirs++;
1983 			/* Overwrite an offset and a number of this "CL" entry
1984 			 * to appear before other dirs. "+1" to those is to
1985 			 * make sure to appear after "RE" entry which this
1986 			 * "CL" entry should be connected with. */
1987 			file->offset = file->number = file->cl_offset + 1;
1988 
1989 			/*
1990 			 * Sanity check: cl_offset does not point at its
1991 			 * the parents or itself.
1992 			 */
1993 			for (r = parent; r; r = r->parent) {
1994 				if (r->offset == file->cl_offset) {
1995 					archive_set_error(&a->archive,
1996 					    ARCHIVE_ERRNO_MISC,
1997 					    "Invalid Rockridge CL");
1998 					return (NULL);
1999 				}
2000 			}
2001 			if (file->cl_offset == file->offset ||
2002 			    parent->rr_moved) {
2003 				archive_set_error(&a->archive,
2004 				    ARCHIVE_ERRNO_MISC,
2005 				    "Invalid Rockridge CL");
2006 				return (NULL);
2007 			}
2008 		}
2009 	}
2010 
2011 #if DEBUG
2012 	/* DEBUGGING: Warn about attributes I don't yet fully support. */
2013 	if ((flags & ~0x02) != 0) {
2014 		fprintf(stderr, "\n ** Unrecognized flag: ");
2015 		dump_isodirrec(stderr, isodirrec);
2016 		fprintf(stderr, "\n");
2017 	} else if (toi(isodirrec + DR_volume_sequence_number_offset, 2) != 1) {
2018 		fprintf(stderr, "\n ** Unrecognized sequence number: ");
2019 		dump_isodirrec(stderr, isodirrec);
2020 		fprintf(stderr, "\n");
2021 	} else if (*(isodirrec + DR_file_unit_size_offset) != 0) {
2022 		fprintf(stderr, "\n ** Unexpected file unit size: ");
2023 		dump_isodirrec(stderr, isodirrec);
2024 		fprintf(stderr, "\n");
2025 	} else if (*(isodirrec + DR_interleave_offset) != 0) {
2026 		fprintf(stderr, "\n ** Unexpected interleave: ");
2027 		dump_isodirrec(stderr, isodirrec);
2028 		fprintf(stderr, "\n");
2029 	} else if (*(isodirrec + DR_ext_attr_length_offset) != 0) {
2030 		fprintf(stderr, "\n ** Unexpected extended attribute length: ");
2031 		dump_isodirrec(stderr, isodirrec);
2032 		fprintf(stderr, "\n");
2033 	}
2034 #endif
2035 	register_file(iso9660, file);
2036 	return (file);
2037 }
2038 
2039 static int
2040 parse_rockridge(struct archive_read *a, struct file_info *file,
2041     const unsigned char *p, const unsigned char *end)
2042 {
2043 	struct iso9660 *iso9660;
2044 
2045 	iso9660 = (struct iso9660 *)(a->format->data);
2046 
2047 	while (p + 4 <= end  /* Enough space for another entry. */
2048 	    && p[0] >= 'A' && p[0] <= 'Z' /* Sanity-check 1st char of name. */
2049 	    && p[1] >= 'A' && p[1] <= 'Z' /* Sanity-check 2nd char of name. */
2050 	    && p[2] >= 4 /* Sanity-check length. */
2051 	    && p + p[2] <= end) { /* Sanity-check length. */
2052 		const unsigned char *data = p + 4;
2053 		int data_length = p[2] - 4;
2054 		int version = p[3];
2055 
2056 		/*
2057 		 * Yes, each 'if' here does test p[0] again.
2058 		 * Otherwise, the fall-through handling to catch
2059 		 * unsupported extensions doesn't work.
2060 		 */
2061 		switch(p[0]) {
2062 		case 'C':
2063 			if (p[0] == 'C' && p[1] == 'E') {
2064 				if (version == 1 && data_length == 24) {
2065 					/*
2066 					 * CE extension comprises:
2067 					 *   8 byte sector containing extension
2068 					 *   8 byte offset w/in above sector
2069 					 *   8 byte length of continuation
2070 					 */
2071 					int32_t location =
2072 					    archive_le32dec(data);
2073 					file->ce_offset =
2074 					    archive_le32dec(data+8);
2075 					file->ce_size =
2076 					    archive_le32dec(data+16);
2077 					if (register_CE(a, location, file)
2078 					    != ARCHIVE_OK)
2079 						return (ARCHIVE_FATAL);
2080 				}
2081 				break;
2082 			}
2083 			if (p[0] == 'C' && p[1] == 'L') {
2084 				if (version == 1 && data_length == 8) {
2085 					file->cl_offset = (uint64_t)
2086 					    iso9660->logical_block_size *
2087 					    (uint64_t)archive_le32dec(data);
2088 					iso9660->seenRockridge = 1;
2089 				}
2090 				break;
2091 			}
2092 			/* FALLTHROUGH */
2093 		case 'N':
2094 			if (p[0] == 'N' && p[1] == 'M') {
2095 				if (version == 1) {
2096 					parse_rockridge_NM1(file,
2097 					    data, data_length);
2098 					iso9660->seenRockridge = 1;
2099 				}
2100 				break;
2101 			}
2102 			/* FALLTHROUGH */
2103 		case 'P':
2104 			if (p[0] == 'P' && p[1] == 'D') {
2105 				/*
2106 				 * PD extension is padding;
2107 				 * contents are always ignored.
2108 				 */
2109 				break;
2110 			}
2111 			if (p[0] == 'P' && p[1] == 'L') {
2112 				/*
2113 				 * PL extension won't appear;
2114 				 * contents are always ignored.
2115 				 */
2116 				break;
2117 			}
2118 			if (p[0] == 'P' && p[1] == 'N') {
2119 				if (version == 1 && data_length == 16) {
2120 					file->rdev = toi(data,4);
2121 					file->rdev <<= 32;
2122 					file->rdev |= toi(data + 8, 4);
2123 					iso9660->seenRockridge = 1;
2124 				}
2125 				break;
2126 			}
2127 			if (p[0] == 'P' && p[1] == 'X') {
2128 				/*
2129 				 * PX extension comprises:
2130 				 *   8 bytes for mode,
2131 				 *   8 bytes for nlinks,
2132 				 *   8 bytes for uid,
2133 				 *   8 bytes for gid,
2134 				 *   8 bytes for inode.
2135 				 */
2136 				if (version == 1) {
2137 					if (data_length >= 8)
2138 						file->mode
2139 						    = toi(data, 4);
2140 					if (data_length >= 16)
2141 						file->nlinks
2142 						    = toi(data + 8, 4);
2143 					if (data_length >= 24)
2144 						file->uid
2145 						    = toi(data + 16, 4);
2146 					if (data_length >= 32)
2147 						file->gid
2148 						    = toi(data + 24, 4);
2149 					if (data_length >= 40)
2150 						file->number
2151 						    = toi(data + 32, 4);
2152 					iso9660->seenRockridge = 1;
2153 				}
2154 				break;
2155 			}
2156 			/* FALLTHROUGH */
2157 		case 'R':
2158 			if (p[0] == 'R' && p[1] == 'E' && version == 1) {
2159 				file->re = 1;
2160 				iso9660->seenRockridge = 1;
2161 				break;
2162 			}
2163 			if (p[0] == 'R' && p[1] == 'R' && version == 1) {
2164 				/*
2165 				 * RR extension comprises:
2166 				 *    one byte flag value
2167 				 * This extension is obsolete,
2168 				 * so contents are always ignored.
2169 				 */
2170 				break;
2171 			}
2172 			/* FALLTHROUGH */
2173 		case 'S':
2174 			if (p[0] == 'S' && p[1] == 'L') {
2175 				if (version == 1) {
2176 					parse_rockridge_SL1(file,
2177 					    data, data_length);
2178 					iso9660->seenRockridge = 1;
2179 				}
2180 				break;
2181 			}
2182 			if (p[0] == 'S' && p[1] == 'T'
2183 			    && data_length == 0 && version == 1) {
2184 				/*
2185 				 * ST extension marks end of this
2186 				 * block of SUSP entries.
2187 				 *
2188 				 * It allows SUSP to coexist with
2189 				 * non-SUSP uses of the System
2190 				 * Use Area by placing non-SUSP data
2191 				 * after SUSP data.
2192 				 */
2193 				iso9660->seenSUSP = 0;
2194 				iso9660->seenRockridge = 0;
2195 				return (ARCHIVE_OK);
2196 			}
2197 		case 'T':
2198 			if (p[0] == 'T' && p[1] == 'F') {
2199 				if (version == 1) {
2200 					parse_rockridge_TF1(file,
2201 					    data, data_length);
2202 					iso9660->seenRockridge = 1;
2203 				}
2204 				break;
2205 			}
2206 			/* FALLTHROUGH */
2207 		case 'Z':
2208 			if (p[0] == 'Z' && p[1] == 'F') {
2209 				if (version == 1)
2210 					parse_rockridge_ZF1(file,
2211 					    data, data_length);
2212 				break;
2213 			}
2214 			/* FALLTHROUGH */
2215 		default:
2216 			/* The FALLTHROUGHs above leave us here for
2217 			 * any unsupported extension. */
2218 			break;
2219 		}
2220 
2221 
2222 
2223 		p += p[2];
2224 	}
2225 	return (ARCHIVE_OK);
2226 }
2227 
2228 static int
2229 register_CE(struct archive_read *a, int32_t location,
2230     struct file_info *file)
2231 {
2232 	struct iso9660 *iso9660;
2233 	struct read_ce_queue *heap;
2234 	struct read_ce_req *p;
2235 	uint64_t offset, parent_offset;
2236 	int hole, parent;
2237 
2238 	iso9660 = (struct iso9660 *)(a->format->data);
2239 	offset = ((uint64_t)location) * (uint64_t)iso9660->logical_block_size;
2240 	if (((file->mode & AE_IFMT) == AE_IFREG &&
2241 	    offset >= file->offset) ||
2242 	    offset < iso9660->current_position ||
2243 	    (((uint64_t)file->ce_offset) + file->ce_size)
2244 	      > iso9660->logical_block_size ||
2245 	    offset + file->ce_offset + file->ce_size
2246 		  > iso9660->volume_size) {
2247 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2248 		    "Invalid parameter in SUSP \"CE\" extension");
2249 		return (ARCHIVE_FATAL);
2250 	}
2251 
2252 	/* Expand our CE list as necessary. */
2253 	heap = &(iso9660->read_ce_req);
2254 	if (heap->cnt >= heap->allocated) {
2255 		int new_size;
2256 
2257 		if (heap->allocated < 16)
2258 			new_size = 16;
2259 		else
2260 			new_size = heap->allocated * 2;
2261 		/* Overflow might keep us from growing the list. */
2262 		if (new_size <= heap->allocated) {
2263 			archive_set_error(&a->archive, ENOMEM, "Out of memory");
2264 			return (ARCHIVE_FATAL);
2265 		}
2266 		p = malloc(new_size * sizeof(p[0]));
2267 		if (p == NULL) {
2268 			archive_set_error(&a->archive, ENOMEM, "Out of memory");
2269 			return (ARCHIVE_FATAL);
2270 		}
2271 		if (heap->reqs != NULL) {
2272 			memcpy(p, heap->reqs, heap->cnt * sizeof(*p));
2273 			free(heap->reqs);
2274 		}
2275 		heap->reqs = p;
2276 		heap->allocated = new_size;
2277 	}
2278 
2279 	/*
2280 	 * Start with hole at end, walk it up tree to find insertion point.
2281 	 */
2282 	hole = heap->cnt++;
2283 	while (hole > 0) {
2284 		parent = (hole - 1)/2;
2285 		parent_offset = heap->reqs[parent].offset;
2286 		if (offset >= parent_offset) {
2287 			heap->reqs[hole].offset = offset;
2288 			heap->reqs[hole].file = file;
2289 			return (ARCHIVE_OK);
2290 		}
2291 		/* Move parent into hole <==> move hole up tree. */
2292 		heap->reqs[hole] = heap->reqs[parent];
2293 		hole = parent;
2294 	}
2295 	heap->reqs[0].offset = offset;
2296 	heap->reqs[0].file = file;
2297 	return (ARCHIVE_OK);
2298 }
2299 
2300 static void
2301 next_CE(struct read_ce_queue *heap)
2302 {
2303 	uint64_t a_offset, b_offset, c_offset;
2304 	int a, b, c;
2305 	struct read_ce_req tmp;
2306 
2307 	if (heap->cnt < 1)
2308 		return;
2309 
2310 	/*
2311 	 * Move the last item in the heap to the root of the tree
2312 	 */
2313 	heap->reqs[0] = heap->reqs[--(heap->cnt)];
2314 
2315 	/*
2316 	 * Rebalance the heap.
2317 	 */
2318 	a = 0; /* Starting element and its offset */
2319 	a_offset = heap->reqs[a].offset;
2320 	for (;;) {
2321 		b = a + a + 1; /* First child */
2322 		if (b >= heap->cnt)
2323 			return;
2324 		b_offset = heap->reqs[b].offset;
2325 		c = b + 1; /* Use second child if it is smaller. */
2326 		if (c < heap->cnt) {
2327 			c_offset = heap->reqs[c].offset;
2328 			if (c_offset < b_offset) {
2329 				b = c;
2330 				b_offset = c_offset;
2331 			}
2332 		}
2333 		if (a_offset <= b_offset)
2334 			return;
2335 		tmp = heap->reqs[a];
2336 		heap->reqs[a] = heap->reqs[b];
2337 		heap->reqs[b] = tmp;
2338 		a = b;
2339 	}
2340 }
2341 
2342 
2343 static int
2344 read_CE(struct archive_read *a, struct iso9660 *iso9660)
2345 {
2346 	struct read_ce_queue *heap;
2347 	const unsigned char *b, *p, *end;
2348 	struct file_info *file;
2349 	size_t step;
2350 	int r;
2351 
2352 	/* Read data which RRIP "CE" extension points. */
2353 	heap = &(iso9660->read_ce_req);
2354 	step = iso9660->logical_block_size;
2355 	while (heap->cnt &&
2356 	    heap->reqs[0].offset == iso9660->current_position) {
2357 		b = __archive_read_ahead(a, step, NULL);
2358 		if (b == NULL) {
2359 			archive_set_error(&a->archive,
2360 			    ARCHIVE_ERRNO_MISC,
2361 			    "Failed to read full block when scanning "
2362 			    "ISO9660 directory list");
2363 			return (ARCHIVE_FATAL);
2364 		}
2365 		do {
2366 			file = heap->reqs[0].file;
2367 			if (file->ce_offset + file->ce_size > step) {
2368 				archive_set_error(&a->archive,
2369 				    ARCHIVE_ERRNO_FILE_FORMAT,
2370 				    "Malformed CE information");
2371 				return (ARCHIVE_FATAL);
2372 			}
2373 			p = b + file->ce_offset;
2374 			end = p + file->ce_size;
2375 			next_CE(heap);
2376 			r = parse_rockridge(a, file, p, end);
2377 			if (r != ARCHIVE_OK)
2378 				return (ARCHIVE_FATAL);
2379 		} while (heap->cnt &&
2380 		    heap->reqs[0].offset == iso9660->current_position);
2381 		/* NOTE: Do not move this consume's code to fron of
2382 		 * do-while loop. Registration of nested CE extension
2383 		 * might cause error because of current position. */
2384 		__archive_read_consume(a, step);
2385 		iso9660->current_position += step;
2386 	}
2387 	return (ARCHIVE_OK);
2388 }
2389 
2390 static void
2391 parse_rockridge_NM1(struct file_info *file,
2392 		    const unsigned char *data, int data_length)
2393 {
2394 	if (!file->name_continues)
2395 		archive_string_empty(&file->name);
2396 	file->name_continues = 0;
2397 	if (data_length < 1)
2398 		return;
2399 	/*
2400 	 * NM version 1 extension comprises:
2401 	 *   1 byte flag, value is one of:
2402 	 *     = 0: remainder is name
2403 	 *     = 1: remainder is name, next NM entry continues name
2404 	 *     = 2: "."
2405 	 *     = 4: ".."
2406 	 *     = 32: Implementation specific
2407 	 *     All other values are reserved.
2408 	 */
2409 	switch(data[0]) {
2410 	case 0:
2411 		if (data_length < 2)
2412 			return;
2413 		archive_strncat(&file->name,
2414 		    (const char *)data + 1, data_length - 1);
2415 		break;
2416 	case 1:
2417 		if (data_length < 2)
2418 			return;
2419 		archive_strncat(&file->name,
2420 		    (const char *)data + 1, data_length - 1);
2421 		file->name_continues = 1;
2422 		break;
2423 	case 2:
2424 		archive_strcat(&file->name, ".");
2425 		break;
2426 	case 4:
2427 		archive_strcat(&file->name, "..");
2428 		break;
2429 	default:
2430 		return;
2431 	}
2432 
2433 }
2434 
2435 static void
2436 parse_rockridge_TF1(struct file_info *file, const unsigned char *data,
2437     int data_length)
2438 {
2439 	char flag;
2440 	/*
2441 	 * TF extension comprises:
2442 	 *   one byte flag
2443 	 *   create time (optional)
2444 	 *   modify time (optional)
2445 	 *   access time (optional)
2446 	 *   attribute time (optional)
2447 	 *  Time format and presence of fields
2448 	 *  is controlled by flag bits.
2449 	 */
2450 	if (data_length < 1)
2451 		return;
2452 	flag = data[0];
2453 	++data;
2454 	--data_length;
2455 	if (flag & 0x80) {
2456 		/* Use 17-byte time format. */
2457 		if ((flag & 1) && data_length >= 17) {
2458 			/* Create time. */
2459 			file->birthtime_is_set = 1;
2460 			file->birthtime = isodate17(data);
2461 			data += 17;
2462 			data_length -= 17;
2463 		}
2464 		if ((flag & 2) && data_length >= 17) {
2465 			/* Modify time. */
2466 			file->mtime = isodate17(data);
2467 			data += 17;
2468 			data_length -= 17;
2469 		}
2470 		if ((flag & 4) && data_length >= 17) {
2471 			/* Access time. */
2472 			file->atime = isodate17(data);
2473 			data += 17;
2474 			data_length -= 17;
2475 		}
2476 		if ((flag & 8) && data_length >= 17) {
2477 			/* Attribute change time. */
2478 			file->ctime = isodate17(data);
2479 		}
2480 	} else {
2481 		/* Use 7-byte time format. */
2482 		if ((flag & 1) && data_length >= 7) {
2483 			/* Create time. */
2484 			file->birthtime_is_set = 1;
2485 			file->birthtime = isodate7(data);
2486 			data += 7;
2487 			data_length -= 7;
2488 		}
2489 		if ((flag & 2) && data_length >= 7) {
2490 			/* Modify time. */
2491 			file->mtime = isodate7(data);
2492 			data += 7;
2493 			data_length -= 7;
2494 		}
2495 		if ((flag & 4) && data_length >= 7) {
2496 			/* Access time. */
2497 			file->atime = isodate7(data);
2498 			data += 7;
2499 			data_length -= 7;
2500 		}
2501 		if ((flag & 8) && data_length >= 7) {
2502 			/* Attribute change time. */
2503 			file->ctime = isodate7(data);
2504 		}
2505 	}
2506 }
2507 
2508 static void
2509 parse_rockridge_SL1(struct file_info *file, const unsigned char *data,
2510     int data_length)
2511 {
2512 	const char *separator = "";
2513 
2514 	if (!file->symlink_continues || file->symlink.length < 1)
2515 		archive_string_empty(&file->symlink);
2516 	else if (!file->symlink_continues &&
2517 	    file->symlink.s[file->symlink.length - 1] != '/')
2518 		separator = "/";
2519 	file->symlink_continues = 0;
2520 
2521 	/*
2522 	 * Defined flag values:
2523 	 *  0: This is the last SL record for this symbolic link
2524 	 *  1: this symbolic link field continues in next SL entry
2525 	 *  All other values are reserved.
2526 	 */
2527 	if (data_length < 1)
2528 		return;
2529 	switch(*data) {
2530 	case 0:
2531 		break;
2532 	case 1:
2533 		file->symlink_continues = 1;
2534 		break;
2535 	default:
2536 		return;
2537 	}
2538 	++data;  /* Skip flag byte. */
2539 	--data_length;
2540 
2541 	/*
2542 	 * SL extension body stores "components".
2543 	 * Basically, this is a complicated way of storing
2544 	 * a POSIX path.  It also interferes with using
2545 	 * symlinks for storing non-path data. <sigh>
2546 	 *
2547 	 * Each component is 2 bytes (flag and length)
2548 	 * possibly followed by name data.
2549 	 */
2550 	while (data_length >= 2) {
2551 		unsigned char flag = *data++;
2552 		unsigned char nlen = *data++;
2553 		data_length -= 2;
2554 
2555 		archive_strcat(&file->symlink, separator);
2556 		separator = "/";
2557 
2558 		switch(flag) {
2559 		case 0: /* Usual case, this is text. */
2560 			if (data_length < nlen)
2561 				return;
2562 			archive_strncat(&file->symlink,
2563 			    (const char *)data, nlen);
2564 			break;
2565 		case 0x01: /* Text continues in next component. */
2566 			if (data_length < nlen)
2567 				return;
2568 			archive_strncat(&file->symlink,
2569 			    (const char *)data, nlen);
2570 			separator = "";
2571 			break;
2572 		case 0x02: /* Current dir. */
2573 			archive_strcat(&file->symlink, ".");
2574 			break;
2575 		case 0x04: /* Parent dir. */
2576 			archive_strcat(&file->symlink, "..");
2577 			break;
2578 		case 0x08: /* Root of filesystem. */
2579 			archive_strcat(&file->symlink, "/");
2580 			separator = "";
2581 			break;
2582 		case 0x10: /* Undefined (historically "volume root" */
2583 			archive_string_empty(&file->symlink);
2584 			archive_strcat(&file->symlink, "ROOT");
2585 			break;
2586 		case 0x20: /* Undefined (historically "hostname") */
2587 			archive_strcat(&file->symlink, "hostname");
2588 			break;
2589 		default:
2590 			/* TODO: issue a warning ? */
2591 			return;
2592 		}
2593 		data += nlen;
2594 		data_length -= nlen;
2595 	}
2596 }
2597 
2598 static void
2599 parse_rockridge_ZF1(struct file_info *file, const unsigned char *data,
2600     int data_length)
2601 {
2602 
2603 	if (data[0] == 0x70 && data[1] == 0x7a && data_length == 12) {
2604 		/* paged zlib */
2605 		file->pz = 1;
2606 		file->pz_log2_bs = data[3];
2607 		file->pz_uncompressed_size = archive_le32dec(&data[4]);
2608 	}
2609 }
2610 
2611 static void
2612 register_file(struct iso9660 *iso9660, struct file_info *file)
2613 {
2614 
2615 	file->use_next = iso9660->use_files;
2616 	iso9660->use_files = file;
2617 }
2618 
2619 static void
2620 release_files(struct iso9660 *iso9660)
2621 {
2622 	struct content *con, *connext;
2623 	struct file_info *file;
2624 
2625 	file = iso9660->use_files;
2626 	while (file != NULL) {
2627 		struct file_info *next = file->use_next;
2628 
2629 		archive_string_free(&file->name);
2630 		archive_string_free(&file->symlink);
2631 		free(file->utf16be_name);
2632 		con = file->contents.first;
2633 		while (con != NULL) {
2634 			connext = con->next;
2635 			free(con);
2636 			con = connext;
2637 		}
2638 		free(file);
2639 		file = next;
2640 	}
2641 }
2642 
2643 static int
2644 next_entry_seek(struct archive_read *a, struct iso9660 *iso9660,
2645     struct file_info **pfile)
2646 {
2647 	struct file_info *file;
2648 	int r;
2649 
2650 	r = next_cache_entry(a, iso9660, pfile);
2651 	if (r != ARCHIVE_OK)
2652 		return (r);
2653 	file = *pfile;
2654 
2655 	/* Don't waste time seeking for zero-length bodies. */
2656 	if (file->size == 0)
2657 		file->offset = iso9660->current_position;
2658 
2659 	/* flush any remaining bytes from the last round to ensure
2660 	 * we're positioned */
2661 	if (iso9660->entry_bytes_unconsumed) {
2662 		__archive_read_consume(a, iso9660->entry_bytes_unconsumed);
2663 		iso9660->entry_bytes_unconsumed = 0;
2664 	}
2665 
2666 	/* Seek forward to the start of the entry. */
2667 	if (iso9660->current_position < file->offset) {
2668 		int64_t step;
2669 
2670 		step = file->offset - iso9660->current_position;
2671 		step = __archive_read_consume(a, step);
2672 		if (step < 0)
2673 			return ((int)step);
2674 		iso9660->current_position = file->offset;
2675 	}
2676 
2677 	/* We found body of file; handle it now. */
2678 	return (ARCHIVE_OK);
2679 }
2680 
2681 static int
2682 next_cache_entry(struct archive_read *a, struct iso9660 *iso9660,
2683     struct file_info **pfile)
2684 {
2685 	struct file_info *file;
2686 	struct {
2687 		struct file_info	*first;
2688 		struct file_info	**last;
2689 	}	empty_files;
2690 	int64_t number;
2691 	int count;
2692 
2693 	file = cache_get_entry(iso9660);
2694 	if (file != NULL) {
2695 		*pfile = file;
2696 		return (ARCHIVE_OK);
2697 	}
2698 
2699 	for (;;) {
2700 		struct file_info *re, *d;
2701 
2702 		*pfile = file = next_entry(iso9660);
2703 		if (file == NULL) {
2704 			/*
2705 			 * If directory entries all which are descendant of
2706 			 * rr_moved are stil remaning, expose their.
2707 			 */
2708 			if (iso9660->re_files.first != NULL &&
2709 			    iso9660->rr_moved != NULL &&
2710 			    iso9660->rr_moved->rr_moved_has_re_only)
2711 				/* Expose "rr_moved" entry. */
2712 				cache_add_entry(iso9660, iso9660->rr_moved);
2713 			while ((re = re_get_entry(iso9660)) != NULL) {
2714 				/* Expose its descendant dirs. */
2715 				while ((d = rede_get_entry(re)) != NULL)
2716 					cache_add_entry(iso9660, d);
2717 			}
2718 			if (iso9660->cache_files.first != NULL)
2719 				return (next_cache_entry(a, iso9660, pfile));
2720 			return (ARCHIVE_EOF);
2721 		}
2722 
2723 		if (file->cl_offset) {
2724 			struct file_info *first_re = NULL;
2725 			int nexted_re = 0;
2726 
2727 			/*
2728 			 * Find "RE" dir for the current file, which
2729 			 * has "CL" flag.
2730 			 */
2731 			while ((re = re_get_entry(iso9660))
2732 			    != first_re) {
2733 				if (first_re == NULL)
2734 					first_re = re;
2735 				if (re->offset == file->cl_offset) {
2736 					re->parent->subdirs--;
2737 					re->parent = file->parent;
2738 					re->re = 0;
2739 					if (re->parent->re_descendant) {
2740 						nexted_re = 1;
2741 						re->re_descendant = 1;
2742 						if (rede_add_entry(re) < 0)
2743 							goto fatal_rr;
2744 						/* Move a list of descendants
2745 						 * to a new ancestor. */
2746 						while ((d = rede_get_entry(
2747 						    re)) != NULL)
2748 							if (rede_add_entry(d)
2749 							    < 0)
2750 								goto fatal_rr;
2751 						break;
2752 					}
2753 					/* Replace the current file
2754 					 * with "RE" dir */
2755 					*pfile = file = re;
2756 					/* Expose its descendant */
2757 					while ((d = rede_get_entry(
2758 					    file)) != NULL)
2759 						cache_add_entry(
2760 						    iso9660, d);
2761 					break;
2762 				} else
2763 					re_add_entry(iso9660, re);
2764 			}
2765 			if (nexted_re) {
2766 				/*
2767 				 * Do not expose this at this time
2768 				 * because we have not gotten its full-path
2769 				 * name yet.
2770 				 */
2771 				continue;
2772 			}
2773 		} else if ((file->mode & AE_IFMT) == AE_IFDIR) {
2774 			int r;
2775 
2776 			/* Read file entries in this dir. */
2777 			r = read_children(a, file);
2778 			if (r != ARCHIVE_OK)
2779 				return (r);
2780 
2781 			/*
2782 			 * Handle a special dir of Rockridge extensions,
2783 			 * "rr_moved".
2784 			 */
2785 			if (file->rr_moved) {
2786 				/*
2787 				 * If this has only the subdirectories which
2788 				 * have "RE" flags, do not expose at this time.
2789 				 */
2790 				if (file->rr_moved_has_re_only)
2791 					continue;
2792 				/* Otherwise expose "rr_moved" entry. */
2793 			} else if (file->re) {
2794 				/*
2795 				 * Do not expose this at this time
2796 				 * because we have not gotten its full-path
2797 				 * name yet.
2798 				 */
2799 				re_add_entry(iso9660, file);
2800 				continue;
2801 			} else if (file->re_descendant) {
2802 				/*
2803 				 * If the top level "RE" entry of this entry
2804 				 * is not exposed, we, accordingly, should not
2805 				 * expose this entry at this time because
2806 				 * we cannot make its proper full-path name.
2807 				 */
2808 				if (rede_add_entry(file) == 0)
2809 					continue;
2810 				/* Otherwise we can expose this entry because
2811 				 * it seems its top level "RE" has already been
2812 				 * exposed. */
2813 			}
2814 		}
2815 		break;
2816 	}
2817 
2818 	if ((file->mode & AE_IFMT) != AE_IFREG || file->number == -1)
2819 		return (ARCHIVE_OK);
2820 
2821 	count = 0;
2822 	number = file->number;
2823 	iso9660->cache_files.first = NULL;
2824 	iso9660->cache_files.last = &(iso9660->cache_files.first);
2825 	empty_files.first = NULL;
2826 	empty_files.last = &empty_files.first;
2827 	/* Collect files which has the same file serial number.
2828 	 * Peek pending_files so that file which number is different
2829 	 * is not put bak. */
2830 	while (iso9660->pending_files.used > 0 &&
2831 	    (iso9660->pending_files.files[0]->number == -1 ||
2832 	     iso9660->pending_files.files[0]->number == number)) {
2833 		if (file->number == -1) {
2834 			/* This file has the same offset
2835 			 * but it's wrong offset which empty files
2836 			 * and symlink files have.
2837 			 * NOTE: This wrong offse was recorded by
2838 			 * old mkisofs utility. If ISO images is
2839 			 * created by latest mkisofs, this does not
2840 			 * happen.
2841 			 */
2842 			file->next = NULL;
2843 			*empty_files.last = file;
2844 			empty_files.last = &(file->next);
2845 		} else {
2846 			count++;
2847 			cache_add_entry(iso9660, file);
2848 		}
2849 		file = next_entry(iso9660);
2850 	}
2851 
2852 	if (count == 0) {
2853 		*pfile = file;
2854 		return ((file == NULL)?ARCHIVE_EOF:ARCHIVE_OK);
2855 	}
2856 	if (file->number == -1) {
2857 		file->next = NULL;
2858 		*empty_files.last = file;
2859 		empty_files.last = &(file->next);
2860 	} else {
2861 		count++;
2862 		cache_add_entry(iso9660, file);
2863 	}
2864 
2865 	if (count > 1) {
2866 		/* The count is the same as number of hardlink,
2867 		 * so much so that each nlinks of files in cache_file
2868 		 * is overwritten by value of the count.
2869 		 */
2870 		for (file = iso9660->cache_files.first;
2871 		    file != NULL; file = file->next)
2872 			file->nlinks = count;
2873 	}
2874 	/* If there are empty files, that files are added
2875 	 * to the tail of the cache_files. */
2876 	if (empty_files.first != NULL) {
2877 		*iso9660->cache_files.last = empty_files.first;
2878 		iso9660->cache_files.last = empty_files.last;
2879 	}
2880 	*pfile = cache_get_entry(iso9660);
2881 	return ((*pfile == NULL)?ARCHIVE_EOF:ARCHIVE_OK);
2882 
2883 fatal_rr:
2884 	archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2885 	    "Failed to connect 'CL' pointer to 'RE' rr_moved pointer of"
2886 	    "Rockridge extensions");
2887 	return (ARCHIVE_FATAL);
2888 }
2889 
2890 static inline void
2891 re_add_entry(struct iso9660 *iso9660, struct file_info *file)
2892 {
2893 	file->re_next = NULL;
2894 	*iso9660->re_files.last = file;
2895 	iso9660->re_files.last = &(file->re_next);
2896 }
2897 
2898 static inline struct file_info *
2899 re_get_entry(struct iso9660 *iso9660)
2900 {
2901 	struct file_info *file;
2902 
2903 	if ((file = iso9660->re_files.first) != NULL) {
2904 		iso9660->re_files.first = file->re_next;
2905 		if (iso9660->re_files.first == NULL)
2906 			iso9660->re_files.last =
2907 			    &(iso9660->re_files.first);
2908 	}
2909 	return (file);
2910 }
2911 
2912 static inline int
2913 rede_add_entry(struct file_info *file)
2914 {
2915 	struct file_info *re;
2916 
2917 	/*
2918 	 * Find "RE" entry.
2919 	 */
2920 	re = file->parent;
2921 	while (re != NULL && !re->re)
2922 		re = re->parent;
2923 	if (re == NULL)
2924 		return (-1);
2925 
2926 	file->re_next = NULL;
2927 	*re->rede_files.last = file;
2928 	re->rede_files.last = &(file->re_next);
2929 	return (0);
2930 }
2931 
2932 static inline struct file_info *
2933 rede_get_entry(struct file_info *re)
2934 {
2935 	struct file_info *file;
2936 
2937 	if ((file = re->rede_files.first) != NULL) {
2938 		re->rede_files.first = file->re_next;
2939 		if (re->rede_files.first == NULL)
2940 			re->rede_files.last =
2941 			    &(re->rede_files.first);
2942 	}
2943 	return (file);
2944 }
2945 
2946 static inline void
2947 cache_add_entry(struct iso9660 *iso9660, struct file_info *file)
2948 {
2949 	file->next = NULL;
2950 	*iso9660->cache_files.last = file;
2951 	iso9660->cache_files.last = &(file->next);
2952 }
2953 
2954 static inline struct file_info *
2955 cache_get_entry(struct iso9660 *iso9660)
2956 {
2957 	struct file_info *file;
2958 
2959 	if ((file = iso9660->cache_files.first) != NULL) {
2960 		iso9660->cache_files.first = file->next;
2961 		if (iso9660->cache_files.first == NULL)
2962 			iso9660->cache_files.last =
2963 			    &(iso9660->cache_files.first);
2964 	}
2965 	return (file);
2966 }
2967 
2968 static int
2969 heap_add_entry(struct archive_read *a, struct heap_queue *heap,
2970     struct file_info *file, uint64_t key)
2971 {
2972 	uint64_t file_key, parent_key;
2973 	int hole, parent;
2974 
2975 	/* Expand our pending files list as necessary. */
2976 	if (heap->used >= heap->allocated) {
2977 		struct file_info **new_pending_files;
2978 		int new_size = heap->allocated * 2;
2979 
2980 		if (heap->allocated < 1024)
2981 			new_size = 1024;
2982 		/* Overflow might keep us from growing the list. */
2983 		if (new_size <= heap->allocated) {
2984 			archive_set_error(&a->archive,
2985 			    ENOMEM, "Out of memory");
2986 			return (ARCHIVE_FATAL);
2987 		}
2988 		new_pending_files = (struct file_info **)
2989 		    malloc(new_size * sizeof(new_pending_files[0]));
2990 		if (new_pending_files == NULL) {
2991 			archive_set_error(&a->archive,
2992 			    ENOMEM, "Out of memory");
2993 			return (ARCHIVE_FATAL);
2994 		}
2995 		memcpy(new_pending_files, heap->files,
2996 		    heap->allocated * sizeof(new_pending_files[0]));
2997 		if (heap->files != NULL)
2998 			free(heap->files);
2999 		heap->files = new_pending_files;
3000 		heap->allocated = new_size;
3001 	}
3002 
3003 	file_key = file->key = key;
3004 
3005 	/*
3006 	 * Start with hole at end, walk it up tree to find insertion point.
3007 	 */
3008 	hole = heap->used++;
3009 	while (hole > 0) {
3010 		parent = (hole - 1)/2;
3011 		parent_key = heap->files[parent]->key;
3012 		if (file_key >= parent_key) {
3013 			heap->files[hole] = file;
3014 			return (ARCHIVE_OK);
3015 		}
3016 		/* Move parent into hole <==> move hole up tree. */
3017 		heap->files[hole] = heap->files[parent];
3018 		hole = parent;
3019 	}
3020 	heap->files[0] = file;
3021 
3022 	return (ARCHIVE_OK);
3023 }
3024 
3025 static struct file_info *
3026 heap_get_entry(struct heap_queue *heap)
3027 {
3028 	uint64_t a_key, b_key, c_key;
3029 	int a, b, c;
3030 	struct file_info *r, *tmp;
3031 
3032 	if (heap->used < 1)
3033 		return (NULL);
3034 
3035 	/*
3036 	 * The first file in the list is the earliest; we'll return this.
3037 	 */
3038 	r = heap->files[0];
3039 
3040 	/*
3041 	 * Move the last item in the heap to the root of the tree
3042 	 */
3043 	heap->files[0] = heap->files[--(heap->used)];
3044 
3045 	/*
3046 	 * Rebalance the heap.
3047 	 */
3048 	a = 0; /* Starting element and its heap key */
3049 	a_key = heap->files[a]->key;
3050 	for (;;) {
3051 		b = a + a + 1; /* First child */
3052 		if (b >= heap->used)
3053 			return (r);
3054 		b_key = heap->files[b]->key;
3055 		c = b + 1; /* Use second child if it is smaller. */
3056 		if (c < heap->used) {
3057 			c_key = heap->files[c]->key;
3058 			if (c_key < b_key) {
3059 				b = c;
3060 				b_key = c_key;
3061 			}
3062 		}
3063 		if (a_key <= b_key)
3064 			return (r);
3065 		tmp = heap->files[a];
3066 		heap->files[a] = heap->files[b];
3067 		heap->files[b] = tmp;
3068 		a = b;
3069 	}
3070 }
3071 
3072 static unsigned int
3073 toi(const void *p, int n)
3074 {
3075 	const unsigned char *v = (const unsigned char *)p;
3076 	if (n > 1)
3077 		return v[0] + 256 * toi(v + 1, n - 1);
3078 	if (n == 1)
3079 		return v[0];
3080 	return (0);
3081 }
3082 
3083 static time_t
3084 isodate7(const unsigned char *v)
3085 {
3086 	struct tm tm;
3087 	int offset;
3088 	memset(&tm, 0, sizeof(tm));
3089 	tm.tm_year = v[0];
3090 	tm.tm_mon = v[1] - 1;
3091 	tm.tm_mday = v[2];
3092 	tm.tm_hour = v[3];
3093 	tm.tm_min = v[4];
3094 	tm.tm_sec = v[5];
3095 	/* v[6] is the signed timezone offset, in 1/4-hour increments. */
3096 	offset = ((const signed char *)v)[6];
3097 	if (offset > -48 && offset < 52) {
3098 		tm.tm_hour -= offset / 4;
3099 		tm.tm_min -= (offset % 4) * 15;
3100 	}
3101 	return (time_from_tm(&tm));
3102 }
3103 
3104 static time_t
3105 isodate17(const unsigned char *v)
3106 {
3107 	struct tm tm;
3108 	int offset;
3109 	memset(&tm, 0, sizeof(tm));
3110 	tm.tm_year = (v[0] - '0') * 1000 + (v[1] - '0') * 100
3111 	    + (v[2] - '0') * 10 + (v[3] - '0')
3112 	    - 1900;
3113 	tm.tm_mon = (v[4] - '0') * 10 + (v[5] - '0');
3114 	tm.tm_mday = (v[6] - '0') * 10 + (v[7] - '0');
3115 	tm.tm_hour = (v[8] - '0') * 10 + (v[9] - '0');
3116 	tm.tm_min = (v[10] - '0') * 10 + (v[11] - '0');
3117 	tm.tm_sec = (v[12] - '0') * 10 + (v[13] - '0');
3118 	/* v[16] is the signed timezone offset, in 1/4-hour increments. */
3119 	offset = ((const signed char *)v)[16];
3120 	if (offset > -48 && offset < 52) {
3121 		tm.tm_hour -= offset / 4;
3122 		tm.tm_min -= (offset % 4) * 15;
3123 	}
3124 	return (time_from_tm(&tm));
3125 }
3126 
3127 static time_t
3128 time_from_tm(struct tm *t)
3129 {
3130 #if HAVE_TIMEGM
3131 	/* Use platform timegm() if available. */
3132 	return (timegm(t));
3133 #elif HAVE__MKGMTIME64
3134 	return (_mkgmtime64(t));
3135 #else
3136 	/* Else use direct calculation using POSIX assumptions. */
3137 	/* First, fix up tm_yday based on the year/month/day. */
3138 	mktime(t);
3139 	/* Then we can compute timegm() from first principles. */
3140 	return (t->tm_sec + t->tm_min * 60 + t->tm_hour * 3600
3141 	    + t->tm_yday * 86400 + (t->tm_year - 70) * 31536000
3142 	    + ((t->tm_year - 69) / 4) * 86400 -
3143 	    ((t->tm_year - 1) / 100) * 86400
3144 	    + ((t->tm_year + 299) / 400) * 86400);
3145 #endif
3146 }
3147 
3148 static const char *
3149 build_pathname(struct archive_string *as, struct file_info *file)
3150 {
3151 	if (file->parent != NULL && archive_strlen(&file->parent->name) > 0) {
3152 		build_pathname(as, file->parent);
3153 		archive_strcat(as, "/");
3154 	}
3155 	if (archive_strlen(&file->name) == 0)
3156 		archive_strcat(as, ".");
3157 	else
3158 		archive_string_concat(as, &file->name);
3159 	return (as->s);
3160 }
3161 
3162 static int
3163 build_pathname_utf16be(unsigned char *p, size_t max, size_t *len,
3164     struct file_info *file)
3165 {
3166 	if (file->parent != NULL && file->parent->utf16be_bytes > 0) {
3167 		if (build_pathname_utf16be(p, max, len, file->parent) != 0)
3168 			return (-1);
3169 		p[*len] = 0;
3170 		p[*len + 1] = '/';
3171 		*len += 2;
3172 	}
3173 	if (file->utf16be_bytes == 0) {
3174 		if (*len + 2 > max)
3175 			return (-1);/* Path is too long! */
3176 		p[*len] = 0;
3177 		p[*len + 1] = '.';
3178 		*len += 2;
3179 	} else {
3180 		if (*len + file->utf16be_bytes > max)
3181 			return (-1);/* Path is too long! */
3182 		memcpy(p + *len, file->utf16be_name, file->utf16be_bytes);
3183 		*len += file->utf16be_bytes;
3184 	}
3185 	return (0);
3186 }
3187 
3188 #if DEBUG
3189 static void
3190 dump_isodirrec(FILE *out, const unsigned char *isodirrec)
3191 {
3192 	fprintf(out, " l %d,",
3193 	    toi(isodirrec + DR_length_offset, DR_length_size));
3194 	fprintf(out, " a %d,",
3195 	    toi(isodirrec + DR_ext_attr_length_offset, DR_ext_attr_length_size));
3196 	fprintf(out, " ext 0x%x,",
3197 	    toi(isodirrec + DR_extent_offset, DR_extent_size));
3198 	fprintf(out, " s %d,",
3199 	    toi(isodirrec + DR_size_offset, DR_extent_size));
3200 	fprintf(out, " f 0x%x,",
3201 	    toi(isodirrec + DR_flags_offset, DR_flags_size));
3202 	fprintf(out, " u %d,",
3203 	    toi(isodirrec + DR_file_unit_size_offset, DR_file_unit_size_size));
3204 	fprintf(out, " ilv %d,",
3205 	    toi(isodirrec + DR_interleave_offset, DR_interleave_size));
3206 	fprintf(out, " seq %d,",
3207 	    toi(isodirrec + DR_volume_sequence_number_offset, DR_volume_sequence_number_size));
3208 	fprintf(out, " nl %d:",
3209 	    toi(isodirrec + DR_name_len_offset, DR_name_len_size));
3210 	fprintf(out, " `%.*s'",
3211 	    toi(isodirrec + DR_name_len_offset, DR_name_len_size), isodirrec + DR_name_offset);
3212 }
3213 #endif
3214