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