]> CyberLeo.Net >> Repos - FreeBSD/releng/8.1.git/blob - lib/libarchive/archive_read_support_format_iso9660.c
Copy stable/8 to releng/8.1 in preparation for 8.1-RC1.
[FreeBSD/releng/8.1.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  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD$");
29
30 #ifdef HAVE_ERRNO_H
31 #include <errno.h>
32 #endif
33 /* #include <stdint.h> */ /* See archive_platform.h */
34 #include <stdio.h>
35 #ifdef HAVE_STDLIB_H
36 #include <stdlib.h>
37 #endif
38 #ifdef HAVE_STRING_H
39 #include <string.h>
40 #endif
41 #include <time.h>
42
43 #include "archive.h"
44 #include "archive_entry.h"
45 #include "archive_private.h"
46 #include "archive_read_private.h"
47 #include "archive_string.h"
48
49 /*
50  * An overview of ISO 9660 format:
51  *
52  * Each disk is laid out as follows:
53  *   * 32k reserved for private use
54  *   * Volume descriptor table.  Each volume descriptor
55  *     is 2k and specifies basic format information.
56  *     The "Primary Volume Descriptor" (PVD) is defined by the
57  *     standard and should always be present; other volume
58  *     descriptors include various vendor-specific extensions.
59  *   * Files and directories.  Each file/dir is specified by
60  *     an "extent" (starting sector and length in bytes).
61  *     Dirs are just files with directory records packed one
62  *     after another.  The PVD contains a single dir entry
63  *     specifying the location of the root directory.  Everything
64  *     else follows from there.
65  *
66  * This module works by first reading the volume descriptors, then
67  * building a list of directory entries, sorted by starting
68  * sector.  At each step, I look for the earliest dir entry that
69  * hasn't yet been read, seek forward to that location and read
70  * that entry.  If it's a dir, I slurp in the new dir entries and
71  * add them to the heap; if it's a regular file, I return the
72  * corresponding archive_entry and wait for the client to request
73  * the file body.  This strategy allows us to read most compliant
74  * CDs with a single pass through the data, as required by libarchive.
75  */
76
77 /* Structure of on-disk primary volume descriptor. */
78 #define PVD_type_offset 0
79 #define PVD_type_size 1
80 #define PVD_id_offset (PVD_type_offset + PVD_type_size)
81 #define PVD_id_size 5
82 #define PVD_version_offset (PVD_id_offset + PVD_id_size)
83 #define PVD_version_size 1
84 #define PVD_reserved1_offset (PVD_version_offset + PVD_version_size)
85 #define PVD_reserved1_size 1
86 #define PVD_system_id_offset (PVD_reserved1_offset + PVD_reserved1_size)
87 #define PVD_system_id_size 32
88 #define PVD_volume_id_offset (PVD_system_id_offset + PVD_system_id_size)
89 #define PVD_volume_id_size 32
90 #define PVD_reserved2_offset (PVD_volume_id_offset + PVD_volume_id_size)
91 #define PVD_reserved2_size 8
92 #define PVD_volume_space_size_offset (PVD_reserved2_offset + PVD_reserved2_size)
93 #define PVD_volume_space_size_size 8
94 #define PVD_reserved3_offset (PVD_volume_space_size_offset + PVD_volume_space_size_size)
95 #define PVD_reserved3_size 32
96 #define PVD_volume_set_size_offset (PVD_reserved3_offset + PVD_reserved3_size)
97 #define PVD_volume_set_size_size 4
98 #define PVD_volume_sequence_number_offset (PVD_volume_set_size_offset + PVD_volume_set_size_size)
99 #define PVD_volume_sequence_number_size 4
100 #define PVD_logical_block_size_offset (PVD_volume_sequence_number_offset + PVD_volume_sequence_number_size)
101 #define PVD_logical_block_size_size 4
102 #define PVD_path_table_size_offset (PVD_logical_block_size_offset + PVD_logical_block_size_size)
103 #define PVD_path_table_size_size 8
104 #define PVD_type_1_path_table_offset (PVD_path_table_size_offset + PVD_path_table_size_size)
105 #define PVD_type_1_path_table_size 4
106 #define PVD_opt_type_1_path_table_offset (PVD_type_1_path_table_offset + PVD_type_1_path_table_size)
107 #define PVD_opt_type_1_path_table_size 4
108 #define PVD_type_m_path_table_offset (PVD_opt_type_1_path_table_offset + PVD_opt_type_1_path_table_size)
109 #define PVD_type_m_path_table_size 4
110 #define PVD_opt_type_m_path_table_offset (PVD_type_m_path_table_offset + PVD_type_m_path_table_size)
111 #define PVD_opt_type_m_path_table_size 4
112 #define PVD_root_directory_record_offset (PVD_opt_type_m_path_table_offset + PVD_opt_type_m_path_table_size)
113 #define PVD_root_directory_record_size 34
114 #define PVD_volume_set_id_offset (PVD_root_directory_record_offset + PVD_root_directory_record_size)
115 #define PVD_volume_set_id_size 128
116 #define PVD_publisher_id_offset (PVD_volume_set_id_offset + PVD_volume_set_id_size)
117 #define PVD_publisher_id_size 128
118 #define PVD_preparer_id_offset (PVD_publisher_id_offset + PVD_publisher_id_size)
119 #define PVD_preparer_id_size 128
120 #define PVD_application_id_offset (PVD_preparer_id_offset + PVD_preparer_id_size)
121 #define PVD_application_id_size 128
122 #define PVD_copyright_file_id_offset (PVD_application_id_offset + PVD_application_id_size)
123 #define PVD_copyright_file_id_size 37
124 #define PVD_abstract_file_id_offset (PVD_copyright_file_id_offset + PVD_copyright_file_id_size)
125 #define PVD_abstract_file_id_size 37
126 #define PVD_bibliographic_file_id_offset (PVD_abstract_file_id_offset + PVD_abstract_file_id_size)
127 #define PVD_bibliographic_file_id_size 37
128 #define PVD_creation_date_offset (PVD_bibliographic_file_id_offset + PVD_bibliographic_file_id_size)
129 #define PVD_creation_date_size 17
130 #define PVD_modification_date_offset (PVD_creation_date_offset + PVD_creation_date_size)
131 #define PVD_modification_date_size 17
132 #define PVD_expiration_date_offset (PVD_modification_date_offset + PVD_modification_date_size)
133 #define PVD_expiration_date_size 17
134 #define PVD_effective_date_offset (PVD_expiration_date_offset + PVD_expiration_date_size)
135 #define PVD_effective_date_size 17
136 #define PVD_file_structure_version_offset (PVD_effective_date_offset + PVD_effective_date_size)
137 #define PVD_file_structure_version_size 1
138 #define PVD_reserved4_offset (PVD_file_structure_version_offset + PVD_file_structure_version_size)
139 #define PVD_reserved4_size 1
140 #define PVD_application_data_offset (PVD_reserved4_offset + PVD_reserved4_size)
141 #define PVD_application_data_size 512
142 #define PVD_reserved5_offset (PVD_application_data_offset + PVD_application_data_size)
143 #define PVD_reserved5_size (2048 - PVD_reserved5_offset)
144
145 /* TODO: It would make future maintenance easier to just hardcode the
146  * above values.  In particular, ECMA119 states the offsets as part of
147  * the standard.  That would eliminate the need for the following check.*/
148 #if PVD_reserved5_offset != 1395
149 #error PVD offset and size definitions are wrong.
150 #endif
151
152
153 /* Structure of optional on-disk supplementary volume descriptor. */
154 #define SVD_type_offset 0
155 #define SVD_type_size 1
156 #define SVD_id_offset (SVD_type_offset + SVD_type_size)
157 #define SVD_id_size 5
158 #define SVD_version_offset (SVD_id_offset + SVD_id_size)
159 #define SVD_version_size 1
160 /* ... */
161 #define SVD_volume_space_size_offset 80
162 #define SVD_volume_space_size_size 8
163 #define SVD_escape_sequences_offset (SVD_volume_space_size_offset + SVD_volume_space_size_size)
164 #define SVD_escape_sequences_size 32
165 /* ... */
166 #define SVD_logical_block_size_offset 128
167 #define SVD_logical_block_size_size 4
168 /* ... */
169 #define SVD_root_directory_record_offset 156
170 #define SVD_root_directory_record_size 34
171 /* ... */
172 /* FIXME: validate correctness of last SVD entry offset. */
173
174 /* Structure of an on-disk directory record. */
175 /* Note:  ISO9660 stores each multi-byte integer twice, once in
176  * each byte order.  The sizes here are the size of just one
177  * of the two integers.  (This is why the offset of a field isn't
178  * the same as the offset+size of the previous field.) */
179 #define DR_length_offset 0
180 #define DR_length_size 1
181 #define DR_ext_attr_length_offset 1
182 #define DR_ext_attr_length_size 1
183 #define DR_extent_offset 2
184 #define DR_extent_size 4
185 #define DR_size_offset 10
186 #define DR_size_size 4
187 #define DR_date_offset 18
188 #define DR_date_size 7
189 #define DR_flags_offset 25
190 #define DR_flags_size 1
191 #define DR_file_unit_size_offset 26
192 #define DR_file_unit_size_size 1
193 #define DR_interleave_offset 27
194 #define DR_interleave_size 1
195 #define DR_volume_sequence_number_offset 28
196 #define DR_volume_sequence_number_size 2
197 #define DR_name_len_offset 32
198 #define DR_name_len_size 1
199 #define DR_name_offset 33
200
201 /* In-memory storage for a directory record. */
202 struct file_info {
203         struct file_info        *parent;
204         int              refcount;
205         uint64_t         offset;  /* Offset on disk. */
206         uint64_t         size;  /* File size in bytes. */
207         uint64_t         ce_offset; /* Offset of CE */
208         uint64_t         ce_size; /* Size of CE */
209         time_t           birthtime; /* File created time. */
210         time_t           mtime; /* File last modified time. */
211         time_t           atime; /* File last accessed time. */
212         time_t           ctime; /* File attribute change time. */
213         uint64_t         rdev; /* Device number */
214         mode_t           mode;
215         uid_t            uid;
216         gid_t            gid;
217         ino_t            inode;
218         int              nlinks;
219         struct archive_string name; /* Pathname */
220         char             name_continues; /* Non-zero if name continues */
221         struct archive_string symlink;
222         char             symlink_continues; /* Non-zero if link continues */
223 };
224
225
226 struct iso9660 {
227         int     magic;
228 #define ISO9660_MAGIC   0x96609660
229
230         int option_ignore_joliet;
231
232         struct archive_string pathname;
233         char    seenRockridge; /* Set true if RR extensions are used. */
234         unsigned char   suspOffset;
235         char    seenJoliet;
236
237         uint64_t        previous_offset;
238         uint64_t        previous_size;
239         struct archive_string previous_pathname;
240
241         /* TODO: Make this a heap for fast inserts and deletions. */
242         struct file_info **pending_files;
243         int     pending_files_allocated;
244         int     pending_files_used;
245
246         uint64_t current_position;
247         ssize_t logical_block_size;
248         uint64_t volume_size; /* Total size of volume in bytes. */
249
250         off_t   entry_sparse_offset;
251         int64_t entry_bytes_remaining;
252 };
253
254 static void     add_entry(struct iso9660 *iso9660, struct file_info *file);
255 static int      archive_read_format_iso9660_bid(struct archive_read *);
256 static int      archive_read_format_iso9660_options(struct archive_read *,
257                     const char *, const char *);
258 static int      archive_read_format_iso9660_cleanup(struct archive_read *);
259 static int      archive_read_format_iso9660_read_data(struct archive_read *,
260                     const void **, size_t *, off_t *);
261 static int      archive_read_format_iso9660_read_data_skip(struct archive_read *);
262 static int      archive_read_format_iso9660_read_header(struct archive_read *,
263                     struct archive_entry *);
264 static const char *build_pathname(struct archive_string *, struct file_info *);
265 #if DEBUG
266 static void     dump_isodirrec(FILE *, const unsigned char *isodirrec);
267 #endif
268 static time_t   time_from_tm(struct tm *);
269 static time_t   isodate17(const unsigned char *);
270 static time_t   isodate7(const unsigned char *);
271 static int      isJolietSVD(struct iso9660 *, const unsigned char *);
272 static int      isPVD(struct iso9660 *, const unsigned char *);
273 static struct file_info *next_entry(struct iso9660 *);
274 static int      next_entry_seek(struct archive_read *a, struct iso9660 *iso9660,
275                     struct file_info **pfile);
276 static struct file_info *
277                 parse_file_info(struct iso9660 *iso9660,
278                     struct file_info *parent, const unsigned char *isodirrec);
279 static void     parse_rockridge(struct iso9660 *iso9660,
280                     struct file_info *file, const unsigned char *start,
281                     const unsigned char *end);
282 static void     parse_rockridge_NM1(struct file_info *,
283                     const unsigned char *, int);
284 static void     parse_rockridge_SL1(struct file_info *,
285                     const unsigned char *, int);
286 static void     parse_rockridge_TF1(struct file_info *,
287                     const unsigned char *, int);
288 static void     release_file(struct iso9660 *, struct file_info *);
289 static unsigned toi(const void *p, int n);
290
291 int
292 archive_read_support_format_iso9660(struct archive *_a)
293 {
294         struct archive_read *a = (struct archive_read *)_a;
295         struct iso9660 *iso9660;
296         int r;
297
298         iso9660 = (struct iso9660 *)malloc(sizeof(*iso9660));
299         if (iso9660 == NULL) {
300                 archive_set_error(&a->archive, ENOMEM, "Can't allocate iso9660 data");
301                 return (ARCHIVE_FATAL);
302         }
303         memset(iso9660, 0, sizeof(*iso9660));
304         iso9660->magic = ISO9660_MAGIC;
305
306         r = __archive_read_register_format(a,
307             iso9660,
308             "iso9660",
309             archive_read_format_iso9660_bid,
310             archive_read_format_iso9660_options,
311             archive_read_format_iso9660_read_header,
312             archive_read_format_iso9660_read_data,
313             archive_read_format_iso9660_read_data_skip,
314             archive_read_format_iso9660_cleanup);
315
316         if (r != ARCHIVE_OK) {
317                 free(iso9660);
318                 return (r);
319         }
320         return (ARCHIVE_OK);
321 }
322
323
324 static int
325 archive_read_format_iso9660_bid(struct archive_read *a)
326 {
327         struct iso9660 *iso9660;
328         ssize_t bytes_read, brsvd;
329         const void *h;
330         const unsigned char *p, *psvd;
331         int bid;
332
333         iso9660 = (struct iso9660 *)(a->format->data);
334
335         /*
336          * Skip the first 32k (reserved area) and get the first
337          * 8 sectors of the volume descriptor table.  Of course,
338          * if the I/O layer gives us more, we'll take it.
339          */
340         h = __archive_read_ahead(a, 32768 + 8*2048, &bytes_read);
341         if (h == NULL)
342             return (-1);
343         p = (const unsigned char *)h;
344
345         /* Skip the reserved area. */
346         bytes_read -= 32768;
347         p += 32768;
348
349         /* Check each volume descriptor to locate possible SVD with Joliet. */
350         for (brsvd = bytes_read, psvd = p;
351                         !iso9660->option_ignore_joliet && brsvd > 2048;
352                         brsvd -= 2048, psvd += 2048) {
353                 bid = isJolietSVD(iso9660, psvd);
354                 if (bid > 0)
355                         return (bid);
356                 if (*p == '\177') /* End-of-volume-descriptor marker. */
357                         break;
358         }
359
360         /* Check each volume descriptor to locate the PVD. */
361         for (; bytes_read > 2048; bytes_read -= 2048, p += 2048) {
362                 bid = isPVD(iso9660, p);
363                 if (bid > 0)
364                         return (bid);
365                 if (*p == '\177') /* End-of-volume-descriptor marker. */
366                         break;
367         }
368
369         /* We didn't find a valid PVD; return a bid of zero. */
370         return (0);
371 }
372
373 static int
374 archive_read_format_iso9660_options(struct archive_read *a,
375                 const char *key, const char *val)
376 {
377         struct iso9660 *iso9660;
378
379         iso9660 = (struct iso9660 *)(a->format->data);
380
381         if (strcmp(key, "joliet") == 0) {
382                 if (val == NULL || strcmp(val, "off") == 0 ||
383                                 strcmp(val, "ignore") == 0 ||
384                                 strcmp(val, "disable") == 0 ||
385                                 strcmp(val, "0") == 0)
386                         iso9660->option_ignore_joliet = 1;
387                 else
388                         iso9660->option_ignore_joliet = 0;
389                 return (ARCHIVE_OK);
390         }
391
392         /* Note: The "warn" return is just to inform the options
393          * supervisor that we didn't handle it.  It will generate
394          * a suitable error if noone used this option. */
395         return (ARCHIVE_WARN);
396 }
397
398 static int
399 isJolietSVD(struct iso9660 *iso9660, const unsigned char *h)
400 {
401         struct file_info *file;
402         const unsigned char *p;
403
404         /* Type 2 means it's a SVD. */
405         if (h[SVD_type_offset] != 2)
406                 return (0);
407
408         /* ID must be "CD001" */
409         if (memcmp(h + SVD_id_offset, "CD001", 5) != 0)
410                 return (0);
411
412         /* FIXME: do more validations according to joliet spec. */
413
414         /* check if this SVD contains joliet extension! */
415         p = h + SVD_escape_sequences_offset;
416         /* N.B. Joliet spec says p[1] == '\\', but.... */
417         if (p[0] == '%' && p[1] == '/') {
418                 int level = 0;
419
420                 if (p[2] == '@')
421                         level = 1;
422                 else if (p[2] == 'C')
423                         level = 2;
424                 else if (p[2] == 'E')
425                         level = 3;
426                 else /* not joliet */
427                         return (0);
428
429                 iso9660->seenJoliet = level;
430
431         } else /* not joliet */
432                 return (0);
433
434         iso9660->logical_block_size = toi(h + SVD_logical_block_size_offset, 2);
435         if (iso9660->logical_block_size <= 0)
436                 return (0);
437
438         iso9660->volume_size = iso9660->logical_block_size
439             * (uint64_t)toi(h + SVD_volume_space_size_offset, 4);
440
441 #if DEBUG
442         fprintf(stderr, "Joliet UCS-2 level %d with "
443                         "logical block size:%d, volume size:%d\n",
444                         iso9660->seenJoliet,
445                         iso9660->logical_block_size, iso9660->volume_size);
446 #endif
447
448         /* Store the root directory in the pending list. */
449         file = parse_file_info(iso9660, NULL, h + SVD_root_directory_record_offset);
450         add_entry(iso9660, file);
451
452         return (48);
453 }
454
455 static int
456 isPVD(struct iso9660 *iso9660, const unsigned char *h)
457 {
458         struct file_info *file;
459         int i;
460
461         /* Type of the Primary Volume Descriptor must be 1. */
462         if (h[PVD_type_offset] != 1)
463                 return (0);
464
465         /* ID must be "CD001" */
466         if (memcmp(h + PVD_id_offset, "CD001", 5) != 0)
467                 return (0);
468
469         /* PVD version must be 1. */
470         if (h[PVD_version_offset] != 1)
471                 return (0);
472
473         /* Reserved field must be 0. */
474         if (h[PVD_reserved1_offset] != 0)
475                 return (0);
476
477         /* Reserved field must be 0. */
478         for (i = 0; i < PVD_reserved2_size; ++i)
479                 if (h[PVD_reserved2_offset + i] != 0)
480                         return (0);
481
482         /* Reserved field must be 0. */
483         for (i = 0; i < PVD_reserved3_size; ++i)
484                 if (h[PVD_reserved3_offset + i] != 0)
485                         return (0);
486
487         /* Logical block size must be > 0. */
488         /* I've looked at Ecma 119 and can't find any stronger
489          * restriction on this field. */
490         iso9660->logical_block_size = toi(h + PVD_logical_block_size_offset, 2);
491         if (iso9660->logical_block_size <= 0)
492                 return (0);
493
494         iso9660->volume_size = iso9660->logical_block_size
495             * (uint64_t)toi(h + PVD_volume_space_size_offset, 4);
496
497         /* File structure version must be 1 for ISO9660/ECMA119. */
498         if (h[PVD_file_structure_version_offset] != 1)
499                 return (0);
500
501
502         /* Reserved field must be 0. */
503         for (i = 0; i < PVD_reserved4_size; ++i)
504                 if (h[PVD_reserved4_offset + i] != 0)
505                         return (0);
506
507         /* Reserved field must be 0. */
508         for (i = 0; i < PVD_reserved5_size; ++i)
509                 if (h[PVD_reserved5_offset + i] != 0)
510                         return (0);
511
512         /* XXX TODO: Check other values for sanity; reject more
513          * malformed PVDs. XXX */
514
515         /* Store the root directory in the pending list. */
516         file = parse_file_info(iso9660, NULL, h + PVD_root_directory_record_offset);
517         add_entry(iso9660, file);
518         return (48);
519 }
520
521 static int
522 archive_read_format_iso9660_read_header(struct archive_read *a,
523     struct archive_entry *entry)
524 {
525         struct iso9660 *iso9660;
526         struct file_info *file;
527         int r;
528
529         iso9660 = (struct iso9660 *)(a->format->data);
530
531         if (!a->archive.archive_format) {
532                 a->archive.archive_format = ARCHIVE_FORMAT_ISO9660;
533                 a->archive.archive_format_name = "ISO9660";
534         }
535
536         /* Get the next entry that appears after the current offset. */
537         r = next_entry_seek(a, iso9660, &file);
538         if (r != ARCHIVE_OK) {
539                 release_file(iso9660, file);
540                 return (r);
541         }
542
543         iso9660->entry_bytes_remaining = file->size;
544         iso9660->entry_sparse_offset = 0; /* Offset for sparse-file-aware clients. */
545
546         if (file->offset + file->size > iso9660->volume_size) {
547                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
548                     "File is beyond end-of-media: %s", file->name);
549                 iso9660->entry_bytes_remaining = 0;
550                 iso9660->entry_sparse_offset = 0;
551                 release_file(iso9660, file);
552                 return (ARCHIVE_WARN);
553         }
554
555         /* Set up the entry structure with information about this entry. */
556         archive_entry_set_mode(entry, file->mode);
557         archive_entry_set_uid(entry, file->uid);
558         archive_entry_set_gid(entry, file->gid);
559         archive_entry_set_nlink(entry, file->nlinks);
560         archive_entry_set_ino(entry, file->inode);
561         archive_entry_set_birthtime(entry, file->birthtime, 0);
562         archive_entry_set_mtime(entry, file->mtime, 0);
563         archive_entry_set_ctime(entry, file->ctime, 0);
564         archive_entry_set_atime(entry, file->atime, 0);
565         /* N.B.: Rock Ridge supports 64-bit device numbers. */
566         archive_entry_set_rdev(entry, (dev_t)file->rdev);
567         archive_entry_set_size(entry, iso9660->entry_bytes_remaining);
568         archive_string_empty(&iso9660->pathname);
569         archive_entry_set_pathname(entry,
570             build_pathname(&iso9660->pathname, file));
571         if (file->symlink.s != NULL)
572                 archive_entry_copy_symlink(entry, file->symlink.s);
573
574         /* If this entry points to the same data as the previous
575          * entry, convert this into a hardlink to that entry.
576          * But don't bother for zero-length files. */
577         if (file->offset == iso9660->previous_offset
578             && file->size == iso9660->previous_size
579             && file->size > 0) {
580                 archive_entry_set_hardlink(entry,
581                     iso9660->previous_pathname.s);
582                 archive_entry_unset_size(entry);
583                 iso9660->entry_bytes_remaining = 0;
584                 iso9660->entry_sparse_offset = 0;
585                 release_file(iso9660, file);
586                 return (ARCHIVE_OK);
587         }
588
589         /* If the offset is before our current position, we can't
590          * seek backwards to extract it, so issue a warning. */
591         if (file->offset < iso9660->current_position) {
592                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
593                     "Ignoring out-of-order file @%x (%s) %jd < %jd",
594                     file,
595                     iso9660->pathname.s,
596                     file->offset, iso9660->current_position);
597                 iso9660->entry_bytes_remaining = 0;
598                 iso9660->entry_sparse_offset = 0;
599                 release_file(iso9660, file);
600                 return (ARCHIVE_WARN);
601         }
602
603         iso9660->previous_size = file->size;
604         iso9660->previous_offset = file->offset;
605         archive_strcpy(&iso9660->previous_pathname, iso9660->pathname.s);
606
607         /* If this is a directory, read in all of the entries right now. */
608         if (archive_entry_filetype(entry) == AE_IFDIR) {
609                 while (iso9660->entry_bytes_remaining > 0) {
610                         const void *block;
611                         const unsigned char *p;
612                         ssize_t step = iso9660->logical_block_size;
613                         if (step > iso9660->entry_bytes_remaining)
614                                 step = iso9660->entry_bytes_remaining;
615                         block = __archive_read_ahead(a, step, NULL);
616                         if (block == NULL) {
617                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
618             "Failed to read full block when scanning ISO9660 directory list");
619                                 release_file(iso9660, file);
620                                 return (ARCHIVE_FATAL);
621                         }
622                         __archive_read_consume(a, step);
623                         iso9660->current_position += step;
624                         iso9660->entry_bytes_remaining -= step;
625                         for (p = (const unsigned char *)block;
626                              *p != 0 && p < (const unsigned char *)block + step;
627                              p += *p) {
628                                 struct file_info *child;
629
630                                 /* N.B.: these special directory identifiers
631                                  * are 8 bit "values" even on a 
632                                  * Joliet CD with UCS-2 (16bit) encoding.
633                                  */
634
635                                 /* Skip '.' entry. */
636                                 if (*(p + DR_name_len_offset) == 1
637                                     && *(p + DR_name_offset) == '\0')
638                                         continue;
639                                 /* Skip '..' entry. */
640                                 if (*(p + DR_name_len_offset) == 1
641                                     && *(p + DR_name_offset) == '\001')
642                                         continue;
643                                 child = parse_file_info(iso9660, file, p);
644                                 add_entry(iso9660, child);
645                                 if (iso9660->seenRockridge) {
646                                         a->archive.archive_format =
647                                             ARCHIVE_FORMAT_ISO9660_ROCKRIDGE;
648                                         a->archive.archive_format_name =
649                                             "ISO9660 with Rockridge extensions";
650                                 }
651                         }
652                 }
653         }
654
655         release_file(iso9660, file);
656         return (ARCHIVE_OK);
657 }
658
659 static int
660 archive_read_format_iso9660_read_data_skip(struct archive_read *a)
661 {
662         /* Because read_next_header always does an explicit skip
663          * to the next entry, we don't need to do anything here. */
664         (void)a; /* UNUSED */
665         return (ARCHIVE_OK);
666 }
667
668 static int
669 archive_read_format_iso9660_read_data(struct archive_read *a,
670     const void **buff, size_t *size, off_t *offset)
671 {
672         ssize_t bytes_read;
673         struct iso9660 *iso9660;
674
675         iso9660 = (struct iso9660 *)(a->format->data);
676         if (iso9660->entry_bytes_remaining <= 0) {
677                 *buff = NULL;
678                 *size = 0;
679                 *offset = iso9660->entry_sparse_offset;
680                 return (ARCHIVE_EOF);
681         }
682
683         *buff = __archive_read_ahead(a, 1, &bytes_read);
684         if (bytes_read == 0)
685                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
686                     "Truncated input file");
687         if (*buff == NULL)
688                 return (ARCHIVE_FATAL);
689         if (bytes_read > iso9660->entry_bytes_remaining)
690                 bytes_read = iso9660->entry_bytes_remaining;
691         *size = bytes_read;
692         *offset = iso9660->entry_sparse_offset;
693         iso9660->entry_sparse_offset += bytes_read;
694         iso9660->entry_bytes_remaining -= bytes_read;
695         iso9660->current_position += bytes_read;
696         __archive_read_consume(a, bytes_read);
697         return (ARCHIVE_OK);
698 }
699
700 static int
701 archive_read_format_iso9660_cleanup(struct archive_read *a)
702 {
703         struct iso9660 *iso9660;
704         struct file_info *file;
705
706         iso9660 = (struct iso9660 *)(a->format->data);
707         while ((file = next_entry(iso9660)) != NULL)
708                 release_file(iso9660, file);
709         archive_string_free(&iso9660->pathname);
710         archive_string_free(&iso9660->previous_pathname);
711         if (iso9660->pending_files)
712                 free(iso9660->pending_files);
713         free(iso9660);
714         (a->format->data) = NULL;
715         return (ARCHIVE_OK);
716 }
717
718 /*
719  * This routine parses a single ISO directory record, makes sense
720  * of any extensions, and stores the result in memory.
721  */
722 static struct file_info *
723 parse_file_info(struct iso9660 *iso9660, struct file_info *parent,
724     const unsigned char *isodirrec)
725 {
726         struct file_info *file;
727         size_t name_len;
728         const unsigned char *rr_start, *rr_end;
729         const unsigned char *p;
730         int flags;
731
732         /* TODO: Sanity check that name_len doesn't exceed length, etc. */
733
734         /* Create a new file entry and copy data from the ISO dir record. */
735         file = (struct file_info *)malloc(sizeof(*file));
736         if (file == NULL)
737                 return (NULL);
738         memset(file, 0, sizeof(*file));
739         file->parent = parent;
740         if (parent != NULL)
741                 parent->refcount++;
742         file->offset = (uint64_t)toi(isodirrec + DR_extent_offset, DR_extent_size)
743             * iso9660->logical_block_size;
744         file->size = toi(isodirrec + DR_size_offset, DR_size_size);
745         file->mtime = isodate7(isodirrec + DR_date_offset);
746         file->ctime = file->atime = file->mtime;
747
748         name_len = (size_t)isodirrec[DR_name_len_offset];
749         p = isodirrec + DR_name_offset;
750         /* Rockridge extensions (if any) follow name.  Compute this
751          * before fidgeting the name_len below. */
752         rr_start = p + name_len + (name_len & 1 ? 0 : 1) + iso9660->suspOffset;
753         rr_end = isodirrec + isodirrec[DR_length_offset];
754
755         if (iso9660->seenJoliet) {
756                 /* Joliet names are max 64 chars (128 bytes) according to spec,
757                  * but genisoimage (and others?) will allow you to have more.
758                  */
759                 wchar_t wbuff[64+1], *wp;
760                 const unsigned char *c;
761
762                 /* TODO: warn when name_len > 128 ? */
763
764                 /* convert BE UTF-16 to wchar_t */
765                 for (c = p, wp = wbuff;
766                                 c < (p + name_len) &&
767                                 wp < (wbuff + sizeof(wbuff)/sizeof(*wbuff) - 1);
768                                 c += 2) {
769                         *wp++ = (((255 & (int)c[0]) << 8) | (255 & (int)c[1]));
770                 }
771                 *wp = L'\0';
772
773 #if 0 /* untested code, is it at all useful on Joliet? */
774                 /* trim trailing first version and dot from filename.
775                  *
776                  * Remember we where in UTF-16BE land!
777                  * SEPARATOR 1 (.) and SEPARATOR 2 (;) are both
778                  * 16 bits big endian characters on Joliet.
779                  *
780                  * TODO: sanitize filename?
781                  *       Joliet allows any UCS-2 char except:
782                  *       *, /, :, ;, ? and \.
783                  */
784                 /* Chop off trailing ';1' from files. */
785                 if (*(wp-2) == ';' && *(wp-1) == '1') {
786                         wp-=2;
787                         *wp = L'\0';
788                 }
789
790                 /* Chop off trailing '.' from filenames. */
791                 if (*(wp-1) == '.')
792                         *(--wp) = L'\0';
793 #endif
794
795                 /* store the result in the file name field. */
796                 archive_strappend_w_utf8(&file->name, wbuff);
797         } else {
798                 /* Chop off trailing ';1' from files. */
799                 if (name_len > 2 && p[name_len - 2] == ';' &&
800                                 p[name_len - 1] == '1')
801                         name_len -= 2;
802                 /* Chop off trailing '.' from filenames. */
803                 if (name_len > 1 && p[name_len - 1] == '.')
804                         --name_len;
805
806                 archive_strncpy(&file->name, (const char *)p, name_len);
807         }
808
809         flags = isodirrec[DR_flags_offset];
810         if (flags & 0x02)
811                 file->mode = AE_IFDIR | 0700;
812         else
813                 file->mode = AE_IFREG | 0400;
814
815         /* Rockridge extensions overwrite information from above. */
816         parse_rockridge(iso9660, file, rr_start, rr_end);
817
818 #if DEBUG
819         /* DEBUGGING: Warn about attributes I don't yet fully support. */
820         if ((flags & ~0x02) != 0) {
821                 fprintf(stderr, "\n ** Unrecognized flag: ");
822                 dump_isodirrec(stderr, isodirrec);
823                 fprintf(stderr, "\n");
824         } else if (toi(isodirrec + DR_volume_sequence_number_offset, 2) != 1) {
825                 fprintf(stderr, "\n ** Unrecognized sequence number: ");
826                 dump_isodirrec(stderr, isodirrec);
827                 fprintf(stderr, "\n");
828         } else if (*(isodirrec + DR_file_unit_size_offset) != 0) {
829                 fprintf(stderr, "\n ** Unexpected file unit size: ");
830                 dump_isodirrec(stderr, isodirrec);
831                 fprintf(stderr, "\n");
832         } else if (*(isodirrec + DR_interleave_offset) != 0) {
833                 fprintf(stderr, "\n ** Unexpected interleave: ");
834                 dump_isodirrec(stderr, isodirrec);
835                 fprintf(stderr, "\n");
836         } else if (*(isodirrec + DR_ext_attr_length_offset) != 0) {
837                 fprintf(stderr, "\n ** Unexpected extended attribute length: ");
838                 dump_isodirrec(stderr, isodirrec);
839                 fprintf(stderr, "\n");
840         }
841 #endif
842         return (file);
843 }
844
845 static void
846 add_entry(struct iso9660 *iso9660, struct file_info *file)
847 {
848         /* Expand our pending files list as necessary. */
849         if (iso9660->pending_files_used >= iso9660->pending_files_allocated) {
850                 struct file_info **new_pending_files;
851                 int new_size = iso9660->pending_files_allocated * 2;
852
853                 if (iso9660->pending_files_allocated < 1024)
854                         new_size = 1024;
855                 /* Overflow might keep us from growing the list. */
856                 if (new_size <= iso9660->pending_files_allocated)
857                         __archive_errx(1, "Out of memory");
858                 new_pending_files = (struct file_info **)malloc(new_size * sizeof(new_pending_files[0]));
859                 if (new_pending_files == NULL)
860                         __archive_errx(1, "Out of memory");
861                 memcpy(new_pending_files, iso9660->pending_files,
862                     iso9660->pending_files_allocated * sizeof(new_pending_files[0]));
863                 if (iso9660->pending_files != NULL)
864                         free(iso9660->pending_files);
865                 iso9660->pending_files = new_pending_files;
866                 iso9660->pending_files_allocated = new_size;
867         }
868
869         iso9660->pending_files[iso9660->pending_files_used++] = file;
870 }
871
872 static void
873 parse_rockridge(struct iso9660 *iso9660, struct file_info *file,
874     const unsigned char *p, const unsigned char *end)
875 {
876         (void)iso9660; /* UNUSED */
877         file->name_continues = 0;
878         file->symlink_continues = 0;
879
880         while (p + 4 < end  /* Enough space for another entry. */
881             && p[0] >= 'A' && p[0] <= 'Z' /* Sanity-check 1st char of name. */
882             && p[1] >= 'A' && p[1] <= 'Z' /* Sanity-check 2nd char of name. */
883             && p[2] >= 4 /* Sanity-check length. */
884             && p + p[2] <= end) { /* Sanity-check length. */
885                 const unsigned char *data = p + 4;
886                 int data_length = p[2] - 4;
887                 int version = p[3];
888
889                 /*
890                  * Yes, each 'if' here does test p[0] again.
891                  * Otherwise, the fall-through handling to catch
892                  * unsupported extensions doesn't work.
893                  */
894                 switch(p[0]) {
895                 case 'C':
896                         if (p[0] == 'C' && p[1] == 'E') {
897                                 if (version == 1 && data_length == 24) {
898                                         /*
899                                          * CE extension comprises:
900                                          *   8 byte sector containing extension
901                                          *   8 byte offset w/in above sector
902                                          *   8 byte length of continuation
903                                          */
904                                         file->ce_offset = (uint64_t)toi(data, 4)
905                                             * iso9660->logical_block_size
906                                             + toi(data + 8, 4);
907                                         file->ce_size = toi(data + 16, 4);
908                                         /* If the result is rediculous,
909                                          * ignore it. */
910                                         if (file->ce_offset + file->ce_size
911                                             > iso9660->volume_size) {
912                                                 file->ce_offset = 0;
913                                                 file->ce_size = 0;
914                                         }
915                                 }
916                                 break;
917                         }
918                         /* FALLTHROUGH */
919                 case 'N':
920                         if (p[0] == 'N' && p[1] == 'M') {
921                                 if (version == 1)
922                                         parse_rockridge_NM1(file,
923                                             data, data_length);
924                                 break;
925                         }
926                         /* FALLTHROUGH */
927                 case 'P':
928                         if (p[0] == 'P' && p[1] == 'D') {
929                                 /*
930                                  * PD extension is padding;
931                                  * contents are always ignored.
932                                  */
933                                 break;
934                         }
935                         if (p[0] == 'P' && p[1] == 'N') {
936                                 if (version == 1 && data_length == 16) {
937                                         file->rdev = toi(data,4);
938                                         file->rdev <<= 32;
939                                         file->rdev |= toi(data + 8, 4);
940                                 }
941                                 break;
942                         }
943                         if (p[0] == 'P' && p[1] == 'X') {
944                                 /*
945                                  * PX extension comprises:
946                                  *   8 bytes for mode,
947                                  *   8 bytes for nlinks,
948                                  *   8 bytes for uid,
949                                  *   8 bytes for gid,
950                                  *   8 bytes for inode.
951                                  */
952                                 if (version == 1) {
953                                         if (data_length >= 8)
954                                                 file->mode
955                                                     = toi(data, 4);
956                                         if (data_length >= 16)
957                                                 file->nlinks
958                                                     = toi(data + 8, 4);
959                                         if (data_length >= 24)
960                                                 file->uid
961                                                     = toi(data + 16, 4);
962                                         if (data_length >= 32)
963                                                 file->gid
964                                                     = toi(data + 24, 4);
965                                         if (data_length >= 40)
966                                                 file->inode
967                                                     = toi(data + 32, 4);
968                                 }
969                                 break;
970                         }
971                         /* FALLTHROUGH */
972                 case 'R':
973                         if (p[0] == 'R' && p[1] == 'R' && version == 1) {
974                                 iso9660->seenRockridge = 1;
975                                 /*
976                                  * RR extension comprises:
977                                  *    one byte flag value
978                                  */
979                                 /* TODO: Handle RR extension. */
980                                 break;
981                         }
982                         /* FALLTHROUGH */
983                 case 'S':
984                         if (p[0] == 'S' && p[1] == 'L') {
985                                 if (version == 1)
986                                         parse_rockridge_SL1(file,
987                                             data, data_length);
988                                 break;
989                         }
990                         if (p[0] == 'S' && p[1] == 'P'
991                             && version == 1 && data_length == 3
992                             && data[0] == (unsigned char)'\xbe'
993                             && data[1] == (unsigned char)'\xef') {
994                                 /*
995                                  * SP extension stores the suspOffset
996                                  * (Number of bytes to skip between
997                                  * filename and SUSP records.)
998                                  * It is mandatory by the SUSP standard
999                                  * (IEEE 1281).
1000                                  *
1001                                  * It allows SUSP to coexist with
1002                                  * non-SUSP uses of the System
1003                                  * Use Area by placing non-SUSP data
1004                                  * before SUSP data.
1005                                  *
1006                                  * TODO: Add a check for 'SP' in
1007                                  * first directory entry, disable all SUSP
1008                                  * processing if not found.
1009                                  */
1010                                 iso9660->suspOffset = data[2];
1011                                 break;
1012                         }
1013                         if (p[0] == 'S' && p[1] == 'T'
1014                             && data_length == 0 && version == 1) {
1015                                 /*
1016                                  * ST extension marks end of this
1017                                  * block of SUSP entries.
1018                                  *
1019                                  * It allows SUSP to coexist with
1020                                  * non-SUSP uses of the System
1021                                  * Use Area by placing non-SUSP data
1022                                  * after SUSP data.
1023                                  */
1024                                 return;
1025                         }
1026                 case 'T':
1027                         if (p[0] == 'T' && p[1] == 'F') {
1028                                 if (version == 1)
1029                                         parse_rockridge_TF1(file,
1030                                             data, data_length);
1031                                 break;
1032                         }
1033                         /* FALLTHROUGH */
1034                 default:
1035                         /* The FALLTHROUGHs above leave us here for
1036                          * any unsupported extension. */
1037 #if DEBUG
1038                         {
1039                                 const unsigned char *t;
1040                                 fprintf(stderr, "\nUnsupported RRIP extension for %s\n", file->name.s);
1041                                 fprintf(stderr, " %c%c(%d):", p[0], p[1], data_length);
1042                                 for (t = data; t < data + data_length && t < data + 16; t++)
1043                                         fprintf(stderr, " %02x", *t);
1044                                 fprintf(stderr, "\n");
1045                         }
1046 #endif
1047                         break;
1048                 }
1049
1050
1051
1052                 p += p[2];
1053         }
1054 }
1055
1056 static void
1057 parse_rockridge_NM1(struct file_info *file,
1058                     const unsigned char *data, int data_length)
1059 {
1060         if (!file->name_continues)
1061                 archive_string_empty(&file->name);
1062         file->name_continues = 0;
1063         if (data_length < 1)
1064                 return;
1065         /*
1066          * NM version 1 extension comprises:
1067          *   1 byte flag, value is one of:
1068          *     = 0: remainder is name
1069          *     = 1: remainder is name, next NM entry continues name
1070          *     = 2: "."
1071          *     = 4: ".."
1072          *     = 32: Implementation specific
1073          *     All other values are reserved.
1074          */
1075         switch(data[0]) {
1076         case 0:
1077                 if (data_length < 2)
1078                         return;
1079                 archive_strncat(&file->name, (const char *)data + 1, data_length - 1);
1080                 break;
1081         case 1:
1082                 if (data_length < 2)
1083                         return;
1084                 archive_strncat(&file->name, (const char *)data + 1, data_length - 1);
1085                 file->name_continues = 1;
1086                 break;
1087         case 2:
1088                 archive_strcat(&file->name, ".");
1089                 break;
1090         case 4:
1091                 archive_strcat(&file->name, "..");
1092                 break;
1093         default:
1094                 return;
1095         }
1096
1097 }
1098
1099 static void
1100 parse_rockridge_TF1(struct file_info *file, const unsigned char *data,
1101     int data_length)
1102 {
1103         char flag;
1104         /*
1105          * TF extension comprises:
1106          *   one byte flag
1107          *   create time (optional)
1108          *   modify time (optional)
1109          *   access time (optional)
1110          *   attribute time (optional)
1111          *  Time format and presence of fields
1112          *  is controlled by flag bits.
1113          */
1114         if (data_length < 1)
1115                 return;
1116         flag = data[0];
1117         ++data;
1118         --data_length;
1119         if (flag & 0x80) {
1120                 /* Use 17-byte time format. */
1121                 if ((flag & 1) && data_length >= 17) {
1122                         /* Create time. */
1123                         file->birthtime = isodate17(data);
1124                         data += 17;
1125                         data_length -= 17;
1126                 }
1127                 if ((flag & 2) && data_length >= 17) {
1128                         /* Modify time. */
1129                         file->mtime = isodate17(data);
1130                         data += 17;
1131                         data_length -= 17;
1132                 }
1133                 if ((flag & 4) && data_length >= 17) {
1134                         /* Access time. */
1135                         file->atime = isodate17(data);
1136                         data += 17;
1137                         data_length -= 17;
1138                 }
1139                 if ((flag & 8) && data_length >= 17) {
1140                         /* Attribute change time. */
1141                         file->ctime = isodate17(data);
1142                         data += 17;
1143                         data_length -= 17;
1144                 }
1145         } else {
1146                 /* Use 7-byte time format. */
1147                 if ((flag & 1) && data_length >= 7) {
1148                         /* Create time. */
1149                         file->birthtime = isodate17(data);
1150                         data += 7;
1151                         data_length -= 7;
1152                 }
1153                 if ((flag & 2) && data_length >= 7) {
1154                         /* Modify time. */
1155                         file->mtime = isodate7(data);
1156                         data += 7;
1157                         data_length -= 7;
1158                 }
1159                 if ((flag & 4) && data_length >= 7) {
1160                         /* Access time. */
1161                         file->atime = isodate7(data);
1162                         data += 7;
1163                         data_length -= 7;
1164                 }
1165                 if ((flag & 8) && data_length >= 7) {
1166                         /* Attribute change time. */
1167                         file->ctime = isodate7(data);
1168                         data += 7;
1169                         data_length -= 7;
1170                 }
1171         }
1172 }
1173
1174 static void
1175 parse_rockridge_SL1(struct file_info *file, const unsigned char *data,
1176     int data_length)
1177 {
1178         const char *separator = "";
1179
1180         if (!file->symlink_continues || file->symlink.length < 1)
1181                 archive_string_empty(&file->symlink);
1182         else if (file->symlink.s[file->symlink.length - 1] != '/')
1183                 separator = "/";
1184         file->symlink_continues = 0;
1185
1186         /*
1187          * Defined flag values:
1188          *  0: This is the last SL record for this symbolic link
1189          *  1: this symbolic link field continues in next SL entry
1190          *  All other values are reserved.
1191          */
1192         if (data_length < 1)
1193                 return;
1194         switch(*data) {
1195         case 0:
1196                 break;
1197         case 1:
1198                 file->symlink_continues = 1;
1199                 break;
1200         default:
1201                 return;
1202         }
1203         ++data;  /* Skip flag byte. */
1204         --data_length;
1205
1206         /*
1207          * SL extension body stores "components".
1208          * Basically, this is a complicated way of storing
1209          * a POSIX path.  It also interferes with using
1210          * symlinks for storing non-path data. <sigh>
1211          *
1212          * Each component is 2 bytes (flag and length)
1213          * possibly followed by name data.
1214          */
1215         while (data_length >= 2) {
1216                 unsigned char flag = *data++;
1217                 unsigned char nlen = *data++;
1218                 data_length -= 2;
1219
1220                 archive_strcat(&file->symlink, separator);
1221                 separator = "/";
1222
1223                 switch(flag) {
1224                 case 0: /* Usual case, this is text. */
1225                         if (data_length < nlen)
1226                                 return;
1227                         archive_strncat(&file->symlink,
1228                             (const char *)data, nlen);
1229                         break;
1230                 case 0x01: /* Text continues in next component. */
1231                         if (data_length < nlen)
1232                                 return;
1233                         archive_strncat(&file->symlink,
1234                             (const char *)data, nlen);
1235                         separator = "";
1236                         break;
1237                 case 0x02: /* Current dir. */
1238                         archive_strcat(&file->symlink, ".");
1239                         break;
1240                 case 0x04: /* Parent dir. */
1241                         archive_strcat(&file->symlink, "..");
1242                         break;
1243                 case 0x08: /* Root of filesystem. */
1244                         archive_string_empty(&file->symlink);
1245                         archive_strcat(&file->symlink, "/");
1246                         separator = "";
1247                         break;
1248                 case 0x10: /* Undefined (historically "volume root" */
1249                         archive_string_empty(&file->symlink);
1250                         archive_strcat(&file->symlink, "ROOT");
1251                         break;
1252                 case 0x20: /* Undefined (historically "hostname") */
1253                         archive_strcat(&file->symlink, "hostname");
1254                         break;
1255                 default:
1256                         /* TODO: issue a warning ? */
1257                         return;
1258                 }
1259                 data += nlen;
1260                 data_length -= nlen;
1261         }
1262 }
1263
1264
1265 static void
1266 release_file(struct iso9660 *iso9660, struct file_info *file)
1267 {
1268         struct file_info *parent;
1269
1270         if (file == NULL)
1271                 return;
1272
1273         if (file->refcount == 0) {
1274                 parent = file->parent;
1275                 archive_string_free(&file->name);
1276                 archive_string_free(&file->symlink);
1277                 free(file);
1278                 if (parent != NULL) {
1279                         parent->refcount--;
1280                         release_file(iso9660, parent);
1281                 }
1282         }
1283 }
1284
1285 static int
1286 next_entry_seek(struct archive_read *a, struct iso9660 *iso9660,
1287     struct file_info **pfile)
1288 {
1289         struct file_info *file;
1290         uint64_t offset;
1291
1292         *pfile = NULL;
1293         for (;;) {
1294                 *pfile = file = next_entry(iso9660);
1295                 if (file == NULL)
1296                         return (ARCHIVE_EOF);
1297
1298                 /* CE area precedes actual file data? Ignore it. */
1299                 if (file->ce_offset > file->offset) {
1300                         /* fprintf(stderr, " *** Discarding CE data.\n"); */
1301                         file->ce_offset = 0;
1302                         file->ce_size = 0;
1303                 }
1304
1305                 /* Don't waste time seeking for zero-length bodies. */
1306                 if (file->size == 0) {
1307                         file->offset = iso9660->current_position;
1308                 }
1309
1310                 /* If CE exists, find and read it now. */
1311                 if (file->ce_offset > 0)
1312                         offset = file->ce_offset;
1313                 else
1314                         offset = file->offset;
1315
1316                 /* Seek forward to the start of the entry. */
1317                 if (iso9660->current_position < offset) {
1318                         off_t step = offset - iso9660->current_position;
1319                         off_t bytes_read;
1320                         bytes_read = __archive_read_skip(a, step);
1321                         if (bytes_read < 0)
1322                                 return (bytes_read);
1323                         iso9660->current_position = offset;
1324                 }
1325
1326                 /* We found body of file; handle it now. */
1327                 if (offset == file->offset)
1328                         return (ARCHIVE_OK);
1329
1330                 /* Found CE?  Process it and push the file back onto list. */
1331                 if (offset == file->ce_offset) {
1332                         const void *p;
1333                         ssize_t size = file->ce_size;
1334                         const unsigned char *rr_start;
1335
1336                         file->ce_offset = 0;
1337                         file->ce_size = 0;
1338                         p = __archive_read_ahead(a, size, NULL);
1339                         if (p == NULL)
1340                                 return (ARCHIVE_FATAL);
1341                         rr_start = (const unsigned char *)p;
1342                         parse_rockridge(iso9660, file, rr_start,
1343                             rr_start + size);
1344                         __archive_read_consume(a, size);
1345                         iso9660->current_position += size;
1346                         add_entry(iso9660, file);
1347                 }
1348         }
1349 }
1350
1351 static struct file_info *
1352 next_entry(struct iso9660 *iso9660)
1353 {
1354         int least_index;
1355         uint64_t least_end_offset;
1356         int i;
1357         struct file_info *r;
1358
1359         if (iso9660->pending_files_used < 1)
1360                 return (NULL);
1361
1362         /* Assume the first file in the list is the earliest on disk. */
1363         least_index = 0;
1364         least_end_offset = iso9660->pending_files[0]->offset
1365             + iso9660->pending_files[0]->size;
1366
1367         /* Now, try to find an earlier one. */
1368         for (i = 0; i < iso9660->pending_files_used; i++) {
1369                 /* Use the position of the file *end* as our comparison. */
1370                 uint64_t end_offset = iso9660->pending_files[i]->offset
1371                     + iso9660->pending_files[i]->size;
1372                 if (iso9660->pending_files[i]->ce_offset > 0
1373                     && iso9660->pending_files[i]->ce_offset < iso9660->pending_files[i]->offset)
1374                         end_offset = iso9660->pending_files[i]->ce_offset
1375                     + iso9660->pending_files[i]->ce_size;
1376                 if (least_end_offset > end_offset) {
1377                         least_index = i;
1378                         least_end_offset = end_offset;
1379                 }
1380         }
1381         r = iso9660->pending_files[least_index];
1382         iso9660->pending_files[least_index]
1383             = iso9660->pending_files[--iso9660->pending_files_used];
1384         return (r);
1385 }
1386
1387 static unsigned int
1388 toi(const void *p, int n)
1389 {
1390         const unsigned char *v = (const unsigned char *)p;
1391         if (n > 1)
1392                 return v[0] + 256 * toi(v + 1, n - 1);
1393         if (n == 1)
1394                 return v[0];
1395         return (0);
1396 }
1397
1398 static time_t
1399 isodate7(const unsigned char *v)
1400 {
1401         struct tm tm;
1402         int offset;
1403         memset(&tm, 0, sizeof(tm));
1404         tm.tm_year = v[0];
1405         tm.tm_mon = v[1] - 1;
1406         tm.tm_mday = v[2];
1407         tm.tm_hour = v[3];
1408         tm.tm_min = v[4];
1409         tm.tm_sec = v[5];
1410         /* v[6] is the signed timezone offset, in 1/4-hour increments. */
1411         offset = ((const signed char *)v)[6];
1412         if (offset > -48 && offset < 52) {
1413                 tm.tm_hour -= offset / 4;
1414                 tm.tm_min -= (offset % 4) * 15;
1415         }
1416         return (time_from_tm(&tm));
1417 }
1418
1419 static time_t
1420 isodate17(const unsigned char *v)
1421 {
1422         struct tm tm;
1423         int offset;
1424         memset(&tm, 0, sizeof(tm));
1425         tm.tm_year = (v[0] - '0') * 1000 + (v[1] - '0') * 100
1426             + (v[2] - '0') * 10 + (v[3] - '0')
1427             - 1900;
1428         tm.tm_mon = (v[4] - '0') * 10 + (v[5] - '0');
1429         tm.tm_mday = (v[6] - '0') * 10 + (v[7] - '0');
1430         tm.tm_hour = (v[8] - '0') * 10 + (v[9] - '0');
1431         tm.tm_min = (v[10] - '0') * 10 + (v[11] - '0');
1432         tm.tm_sec = (v[12] - '0') * 10 + (v[13] - '0');
1433         /* v[16] is the signed timezone offset, in 1/4-hour increments. */
1434         offset = ((const signed char *)v)[16];
1435         if (offset > -48 && offset < 52) {
1436                 tm.tm_hour -= offset / 4;
1437                 tm.tm_min -= (offset % 4) * 15;
1438         }
1439         return (time_from_tm(&tm));
1440 }
1441
1442 static time_t
1443 time_from_tm(struct tm *t)
1444 {
1445 #if HAVE_TIMEGM
1446         /* Use platform timegm() if available. */
1447         return (timegm(t));
1448 #else
1449         /* Else use direct calculation using POSIX assumptions. */
1450         /* First, fix up tm_yday based on the year/month/day. */
1451         mktime(t);
1452         /* Then we can compute timegm() from first principles. */
1453         return (t->tm_sec + t->tm_min * 60 + t->tm_hour * 3600
1454             + t->tm_yday * 86400 + (t->tm_year - 70) * 31536000
1455             + ((t->tm_year - 69) / 4) * 86400 -
1456             ((t->tm_year - 1) / 100) * 86400
1457             + ((t->tm_year + 299) / 400) * 86400);
1458 #endif
1459 }
1460
1461 static const char *
1462 build_pathname(struct archive_string *as, struct file_info *file)
1463 {
1464         if (file->parent != NULL && archive_strlen(&file->parent->name) > 0) {
1465                 build_pathname(as, file->parent);
1466                 archive_strcat(as, "/");
1467         }
1468         if (archive_strlen(&file->name) == 0)
1469                 archive_strcat(as, ".");
1470         else
1471                 archive_string_concat(as, &file->name);
1472         return (as->s);
1473 }
1474
1475 #if DEBUG
1476 static void
1477 dump_isodirrec(FILE *out, const unsigned char *isodirrec)
1478 {
1479         fprintf(out, " l %d,",
1480             toi(isodirrec + DR_length_offset, DR_length_size));
1481         fprintf(out, " a %d,",
1482             toi(isodirrec + DR_ext_attr_length_offset, DR_ext_attr_length_size));
1483         fprintf(out, " ext 0x%x,",
1484             toi(isodirrec + DR_extent_offset, DR_extent_size));
1485         fprintf(out, " s %d,",
1486             toi(isodirrec + DR_size_offset, DR_extent_size));
1487         fprintf(out, " f 0x%02x,",
1488             toi(isodirrec + DR_flags_offset, DR_flags_size));
1489         fprintf(out, " u %d,",
1490             toi(isodirrec + DR_file_unit_size_offset, DR_file_unit_size_size));
1491         fprintf(out, " ilv %d,",
1492             toi(isodirrec + DR_interleave_offset, DR_interleave_size));
1493         fprintf(out, " seq %d,",
1494             toi(isodirrec + DR_volume_sequence_number_offset, DR_volume_sequence_number_size));
1495         fprintf(out, " nl %d:",
1496             toi(isodirrec + DR_name_len_offset, DR_name_len_size));
1497         fprintf(out, " `%.*s'",
1498             toi(isodirrec + DR_name_len_offset, DR_name_len_size), isodirrec + DR_name_offset);
1499 }
1500 #endif