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