Import libarchive 2.4.0 which brings some performance enhancements.
[dragonfly.git] / contrib / libarchive-2 / libarchive / archive_read_support_format_iso9660.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "archive_platform.h"
27 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read_support_format_iso9660.c,v 1.23 2007/05/29 01:00:19 kientzle Exp $");
28
29 #ifdef HAVE_ERRNO_H
30 #include <errno.h>
31 #endif
32 /* #include <stdint.h> */ /* See archive_platform.h */
33 #include <stdio.h>
34 #ifdef HAVE_STDLIB_H
35 #include <stdlib.h>
36 #endif
37 #ifdef HAVE_STRING_H
38 #include <string.h>
39 #endif
40 #include <time.h>
41
42 #include "archive.h"
43 #include "archive_entry.h"
44 #include "archive_private.h"
45 #include "archive_read_private.h"
46 #include "archive_string.h"
47
48 /*
49  * An overview of ISO 9660 format:
50  *
51  * Each disk is laid out as follows:
52  *   * 32k reserved for private use
53  *   * Volume descriptor table.  Each volume descriptor
54  *     is 2k and specifies basic format information.
55  *     The "Primary Volume Descriptor" (PVD) is defined by the
56  *     standard and should always be present; other volume
57  *     descriptors include various vendor-specific extensions.
58  *   * Files and directories.  Each file/dir is specified by
59  *     an "extent" (starting sector and length in bytes).
60  *     Dirs are just files with directory records packed one
61  *     after another.  The PVD contains a single dir entry
62  *     specifying the location of the root directory.  Everything
63  *     else follows from there.
64  *
65  * This module works by first reading the volume descriptors, then
66  * building a list of directory entries, sorted by starting
67  * sector.  At each step, I look for the earliest dir entry that
68  * hasn't yet been read, seek forward to that location and read
69  * that entry.  If it's a dir, I slurp in the new dir entries and
70  * add them to the heap; if it's a regular file, I return the
71  * corresponding archive_entry and wait for the client to request
72  * the file body.  This strategy allows us to read most compliant
73  * CDs with a single pass through the data, as required by libarchive.
74  */
75
76 /* Structure of on-disk primary volume descriptor. */
77 #define PVD_type_offset 0
78 #define PVD_type_size 1
79 #define PVD_id_offset (PVD_type_offset + PVD_type_size)
80 #define PVD_id_size 5
81 #define PVD_version_offset (PVD_id_offset + PVD_id_size)
82 #define PVD_version_size 1
83 #define PVD_reserved1_offset (PVD_version_offset + PVD_version_size)
84 #define PVD_reserved1_size 1
85 #define PVD_system_id_offset (PVD_reserved1_offset + PVD_reserved1_size)
86 #define PVD_system_id_size 32
87 #define PVD_volume_id_offset (PVD_system_id_offset + PVD_system_id_size)
88 #define PVD_volume_id_size 32
89 #define PVD_reserved2_offset (PVD_volume_id_offset + PVD_volume_id_size)
90 #define PVD_reserved2_size 8
91 #define PVD_volume_space_size_offset (PVD_reserved2_offset + PVD_reserved2_size)
92 #define PVD_volume_space_size_size 8
93 #define PVD_reserved3_offset (PVD_volume_space_size_offset + PVD_volume_space_size_size)
94 #define PVD_reserved3_size 32
95 #define PVD_volume_set_size_offset (PVD_reserved3_offset + PVD_reserved3_size)
96 #define PVD_volume_set_size_size 4
97 #define PVD_volume_sequence_number_offset (PVD_volume_set_size_offset + PVD_volume_set_size_size)
98 #define PVD_volume_sequence_number_size 4
99 #define PVD_logical_block_size_offset (PVD_volume_sequence_number_offset + PVD_volume_sequence_number_size)
100 #define PVD_logical_block_size_size 4
101 #define PVD_path_table_size_offset (PVD_logical_block_size_offset + PVD_logical_block_size_size)
102 #define PVD_path_table_size_size 8
103 #define PVD_type_1_path_table_offset (PVD_path_table_size_offset + PVD_path_table_size_size)
104 #define PVD_type_1_path_table_size 4
105 #define PVD_opt_type_1_path_table_offset (PVD_type_1_path_table_offset + PVD_type_1_path_table_size)
106 #define PVD_opt_type_1_path_table_size 4
107 #define PVD_type_m_path_table_offset (PVD_opt_type_1_path_table_offset + PVD_opt_type_1_path_table_size)
108 #define PVD_type_m_path_table_size 4
109 #define PVD_opt_type_m_path_table_offset (PVD_type_m_path_table_offset + PVD_type_m_path_table_size)
110 #define PVD_opt_type_m_path_table_size 4
111 #define PVD_root_directory_record_offset (PVD_opt_type_m_path_table_offset + PVD_opt_type_m_path_table_size)
112 #define PVD_root_directory_record_size 34
113 #define PVD_volume_set_id_offset (PVD_root_directory_record_offset + PVD_root_directory_record_size)
114 #define PVD_volume_set_id_size 128
115 #define PVD_publisher_id_offset (PVD_volume_set_id_offset + PVD_volume_set_id_size)
116 #define PVD_publisher_id_size 128
117 #define PVD_preparer_id_offset (PVD_publisher_id_offset + PVD_publisher_id_size)
118 #define PVD_preparer_id_size 128
119 #define PVD_application_id_offset (PVD_preparer_id_offset + PVD_preparer_id_size)
120 #define PVD_application_id_size 128
121 #define PVD_copyright_file_id_offset (PVD_application_id_offset + PVD_application_id_size)
122 #define PVD_copyright_file_id_size 37
123 #define PVD_abstract_file_id_offset (PVD_copyright_file_id_offset + PVD_copyright_file_id_size)
124 #define PVD_abstract_file_id_size 37
125 #define PVD_bibliographic_file_id_offset (PVD_abstract_file_id_offset + PVD_abstract_file_id_size)
126 #define PVD_bibliographic_file_id_size 37
127 #define PVD_creation_date_offset (PVD_bibliographic_file_id_offset + PVD_bibliographic_file_id_size)
128 #define PVD_creation_date_size 17
129 #define PVD_modification_date_offset (PVD_creation_date_offset + PVD_creation_date_size)
130 #define PVD_modification_date_size 17
131 #define PVD_expiration_date_offset (PVD_modification_date_offset + PVD_modification_date_size)
132 #define PVD_expiration_date_size 17
133 #define PVD_effective_date_offset (PVD_expiration_date_offset + PVD_expiration_date_size)
134 #define PVD_effective_date_size 17
135 #define PVD_file_structure_version_offset (PVD_effective_date_offset + PVD_effective_date_size)
136 #define PVD_file_structure_version_size 1
137 #define PVD_reserved4_offset (PVD_file_structure_version_offset + PVD_file_structure_version_size)
138 #define PVD_reserved4_size 1
139 #define PVD_application_data_offset (PVD_reserved4_offset + PVD_reserved4_size)
140 #define PVD_application_data_size 512
141
142 /* Structure of an on-disk directory record. */
143 /* Note:  ISO9660 stores each multi-byte integer twice, once in
144  * each byte order.  The sizes here are the size of just one
145  * of the two integers.  (This is why the offset of a field isn't
146  * the same as the offset+size of the previous field.) */
147 #define DR_length_offset 0
148 #define DR_length_size 1
149 #define DR_ext_attr_length_offset 1
150 #define DR_ext_attr_length_size 1
151 #define DR_extent_offset 2
152 #define DR_extent_size 4
153 #define DR_size_offset 10
154 #define DR_size_size 4
155 #define DR_date_offset 18
156 #define DR_date_size 7
157 #define DR_flags_offset 25
158 #define DR_flags_size 1
159 #define DR_file_unit_size_offset 26
160 #define DR_file_unit_size_size 1
161 #define DR_interleave_offset 27
162 #define DR_interleave_size 1
163 #define DR_volume_sequence_number_offset 28
164 #define DR_volume_sequence_number_size 2
165 #define DR_name_len_offset 32
166 #define DR_name_len_size 1
167 #define DR_name_offset 33
168
169 /*
170  * Our private data.
171  */
172
173 /* In-memory storage for a directory record. */
174 struct file_info {
175         struct file_info        *parent;
176         int              refcount;
177         uint64_t         offset;  /* Offset on disk. */
178         uint64_t         size;  /* File size in bytes. */
179         uint64_t         ce_offset; /* Offset of CE */
180         uint64_t         ce_size; /* Size of CE */
181         time_t           mtime; /* File last modified time. */
182         time_t           atime; /* File last accessed time. */
183         time_t           ctime; /* File creation time. */
184         mode_t           mode;
185         uid_t            uid;
186         gid_t            gid;
187         ino_t            inode;
188         int              nlinks;
189         char            *name; /* Null-terminated filename. */
190         struct archive_string symlink;
191 };
192
193
194 struct iso9660 {
195         int     magic;
196 #define ISO9660_MAGIC   0x96609660
197         struct archive_string pathname;
198         char    seenRockridge; /* Set true if RR extensions are used. */
199         unsigned char   suspOffset;
200
201         uint64_t        previous_offset;
202         uint64_t        previous_size;
203         struct archive_string previous_pathname;
204
205         /* TODO: Make this a heap for fast inserts and deletions. */
206         struct file_info **pending_files;
207         int     pending_files_allocated;
208         int     pending_files_used;
209
210         uint64_t current_position;
211         ssize_t logical_block_size;
212
213         off_t   entry_sparse_offset;
214         int64_t entry_bytes_remaining;
215 };
216
217 static void     add_entry(struct iso9660 *iso9660, struct file_info *file);
218 static int      archive_read_format_iso9660_bid(struct archive_read *);
219 static int      archive_read_format_iso9660_cleanup(struct archive_read *);
220 static int      archive_read_format_iso9660_read_data(struct archive_read *,
221                     const void **, size_t *, off_t *);
222 static int      archive_read_format_iso9660_read_data_skip(struct archive_read *);
223 static int      archive_read_format_iso9660_read_header(struct archive_read *,
224                     struct archive_entry *);
225 static const char *build_pathname(struct archive_string *, struct file_info *);
226 static void     dump_isodirrec(FILE *, const unsigned char *isodirrec);
227 static time_t   time_from_tm(struct tm *);
228 static time_t   isodate17(const unsigned char *);
229 static time_t   isodate7(const unsigned char *);
230 static int      isPVD(struct iso9660 *, const unsigned char *);
231 static struct file_info *next_entry(struct iso9660 *);
232 static int      next_entry_seek(struct archive_read *a, struct iso9660 *iso9660,
233                     struct file_info **pfile);
234 static struct file_info *
235                 parse_file_info(struct iso9660 *iso9660,
236                     struct file_info *parent, const unsigned char *isodirrec);
237 static void     parse_rockridge(struct iso9660 *iso9660,
238                     struct file_info *file, const unsigned char *start,
239                     const unsigned char *end);
240 static void     release_file(struct iso9660 *, struct file_info *);
241 static unsigned toi(const void *p, int n);
242
243 int
244 archive_read_support_format_iso9660(struct archive *_a)
245 {
246         struct archive_read *a = (struct archive_read *)_a;
247         struct iso9660 *iso9660;
248         int r;
249
250         iso9660 = (struct iso9660 *)malloc(sizeof(*iso9660));
251         if (iso9660 == NULL) {
252                 archive_set_error(&a->archive, ENOMEM, "Can't allocate iso9660 data");
253                 return (ARCHIVE_FATAL);
254         }
255         memset(iso9660, 0, sizeof(*iso9660));
256         iso9660->magic = ISO9660_MAGIC;
257
258         r = __archive_read_register_format(a,
259             iso9660,
260             archive_read_format_iso9660_bid,
261             archive_read_format_iso9660_read_header,
262             archive_read_format_iso9660_read_data,
263             archive_read_format_iso9660_read_data_skip,
264             archive_read_format_iso9660_cleanup);
265
266         if (r != ARCHIVE_OK) {
267                 free(iso9660);
268                 return (r);
269         }
270         return (ARCHIVE_OK);
271 }
272
273
274 static int
275 archive_read_format_iso9660_bid(struct archive_read *a)
276 {
277         struct iso9660 *iso9660;
278         ssize_t bytes_read;
279         const void *h;
280         const unsigned char *p;
281         int bid;
282
283         iso9660 = (struct iso9660 *)(a->format->data);
284
285         /*
286          * Skip the first 32k (reserved area) and get the first
287          * 8 sectors of the volume descriptor table.  Of course,
288          * if the I/O layer gives us more, we'll take it.
289          */
290         bytes_read = (a->decompressor->read_ahead)(a, &h, 32768 + 8*2048);
291         if (bytes_read < 32768 + 8*2048)
292             return (-1);
293         p = (const unsigned char *)h;
294
295         /* Skip the reserved area. */
296         bytes_read -= 32768;
297         p += 32768;
298
299         /* Check each volume descriptor to locate the PVD. */
300         for (; bytes_read > 2048; bytes_read -= 2048, p += 2048) {
301                 bid = isPVD(iso9660, p);
302                 if (bid > 0)
303                         return (bid);
304                 if (*p == '\177') /* End-of-volume-descriptor marker. */
305                         break;
306         }
307
308         /* We didn't find a valid PVD; return a bid of zero. */
309         return (0);
310 }
311
312 static int
313 isPVD(struct iso9660 *iso9660, const unsigned char *h)
314 {
315         struct file_info *file;
316
317         if (h[0] != 1)
318                 return (0);
319         if (memcmp(h+1, "CD001", 5) != 0)
320                 return (0);
321
322         iso9660->logical_block_size = toi(h + PVD_logical_block_size_offset, 2);
323
324         /* Store the root directory in the pending list. */
325         file = parse_file_info(iso9660, NULL, h + PVD_root_directory_record_offset);
326         add_entry(iso9660, file);
327         return (48);
328 }
329
330 static int
331 archive_read_format_iso9660_read_header(struct archive_read *a,
332     struct archive_entry *entry)
333 {
334         struct iso9660 *iso9660;
335         struct file_info *file;
336         ssize_t bytes_read;
337         int r;
338
339         iso9660 = (struct iso9660 *)(a->format->data);
340
341         if (!a->archive.archive_format) {
342                 a->archive.archive_format = ARCHIVE_FORMAT_ISO9660;
343                 a->archive.archive_format_name = "ISO9660";
344         }
345
346         /* Get the next entry that appears after the current offset. */
347         r = next_entry_seek(a, iso9660, &file);
348         if (r != ARCHIVE_OK)
349                 return (r);
350
351         iso9660->entry_bytes_remaining = file->size;
352         iso9660->entry_sparse_offset = 0; /* Offset for sparse-file-aware clients. */
353
354         /* Set up the entry structure with information about this entry. */
355         archive_entry_set_mode(entry, file->mode);
356         archive_entry_set_uid(entry, file->uid);
357         archive_entry_set_gid(entry, file->gid);
358         archive_entry_set_nlink(entry, file->nlinks);
359         archive_entry_set_ino(entry, file->inode);
360         archive_entry_set_mtime(entry, file->mtime, 0);
361         archive_entry_set_ctime(entry, file->ctime, 0);
362         archive_entry_set_atime(entry, file->atime, 0);
363         archive_entry_set_size(entry, iso9660->entry_bytes_remaining);
364         archive_string_empty(&iso9660->pathname);
365         archive_entry_set_pathname(entry,
366             build_pathname(&iso9660->pathname, file));
367         if (file->symlink.s != NULL)
368                 archive_entry_copy_symlink(entry, file->symlink.s);
369
370         /* If this entry points to the same data as the previous
371          * entry, convert this into a hardlink to that entry.
372          * But don't bother for zero-length files. */
373         if (file->offset == iso9660->previous_offset
374             && file->size == iso9660->previous_size
375             && file->size > 0) {
376                 archive_entry_set_hardlink(entry,
377                     iso9660->previous_pathname.s);
378                 iso9660->entry_bytes_remaining = 0;
379                 iso9660->entry_sparse_offset = 0;
380                 release_file(iso9660, file);
381                 return (ARCHIVE_OK);
382         }
383
384         /* If the offset is before our current position, we can't
385          * seek backwards to extract it, so issue a warning. */
386         if (file->offset < iso9660->current_position) {
387                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
388                     "Ignoring out-of-order file");
389                 iso9660->entry_bytes_remaining = 0;
390                 iso9660->entry_sparse_offset = 0;
391                 release_file(iso9660, file);
392                 return (ARCHIVE_WARN);
393         }
394
395         iso9660->previous_size = file->size;
396         iso9660->previous_offset = file->offset;
397         archive_strcpy(&iso9660->previous_pathname, iso9660->pathname.s);
398
399         /* If this is a directory, read in all of the entries right now. */
400         if (archive_entry_filetype(entry) == AE_IFDIR) {
401                 while (iso9660->entry_bytes_remaining > 0) {
402                         const void *block;
403                         const unsigned char *p;
404                         ssize_t step = iso9660->logical_block_size;
405                         if (step > iso9660->entry_bytes_remaining)
406                                 step = iso9660->entry_bytes_remaining;
407                         bytes_read = (a->decompressor->read_ahead)(a, &block, step);
408                         if (bytes_read < step) {
409                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
410             "Failed to read full block when scanning ISO9660 directory list");
411                                 release_file(iso9660, file);
412                                 return (ARCHIVE_FATAL);
413                         }
414                         if (bytes_read > step)
415                                 bytes_read = step;
416                         (a->decompressor->consume)(a, bytes_read);
417                         iso9660->current_position += bytes_read;
418                         iso9660->entry_bytes_remaining -= bytes_read;
419                         for (p = (const unsigned char *)block;
420                              *p != 0 && p < (const unsigned char *)block + bytes_read;
421                              p += *p) {
422                                 struct file_info *child;
423
424                                 /* Skip '.' entry. */
425                                 if (*(p + DR_name_len_offset) == 1
426                                     && *(p + DR_name_offset) == '\0')
427                                         continue;
428                                 /* Skip '..' entry. */
429                                 if (*(p + DR_name_len_offset) == 1
430                                     && *(p + DR_name_offset) == '\001')
431                                         continue;
432                                 child = parse_file_info(iso9660, file, p);
433                                 add_entry(iso9660, child);
434                                 if (iso9660->seenRockridge) {
435                                         a->archive.archive_format =
436                                             ARCHIVE_FORMAT_ISO9660_ROCKRIDGE;
437                                         a->archive.archive_format_name =
438                                             "ISO9660 with Rockridge extensions";
439                                 }
440                         }
441                 }
442         }
443
444         release_file(iso9660, file);
445         return (ARCHIVE_OK);
446 }
447
448 static int
449 archive_read_format_iso9660_read_data_skip(struct archive_read *a)
450 {
451         /* Because read_next_header always does an explicit skip
452          * to the next entry, we don't need to do anything here. */
453         (void)a; /* UNUSED */
454         return (ARCHIVE_OK);
455 }
456
457 static int
458 archive_read_format_iso9660_read_data(struct archive_read *a,
459     const void **buff, size_t *size, off_t *offset)
460 {
461         ssize_t bytes_read;
462         struct iso9660 *iso9660;
463
464         iso9660 = (struct iso9660 *)(a->format->data);
465         if (iso9660->entry_bytes_remaining <= 0) {
466                 *buff = NULL;
467                 *size = 0;
468                 *offset = iso9660->entry_sparse_offset;
469                 return (ARCHIVE_EOF);
470         }
471
472         bytes_read = (a->decompressor->read_ahead)(a, buff, 1);
473         if (bytes_read == 0)
474                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
475                     "Truncated input file");
476         if (bytes_read <= 0)
477                 return (ARCHIVE_FATAL);
478         if (bytes_read > iso9660->entry_bytes_remaining)
479                 bytes_read = iso9660->entry_bytes_remaining;
480         *size = bytes_read;
481         *offset = iso9660->entry_sparse_offset;
482         iso9660->entry_sparse_offset += bytes_read;
483         iso9660->entry_bytes_remaining -= bytes_read;
484         iso9660->current_position += bytes_read;
485         (a->decompressor->consume)(a, bytes_read);
486         return (ARCHIVE_OK);
487 }
488
489 static int
490 archive_read_format_iso9660_cleanup(struct archive_read *a)
491 {
492         struct iso9660 *iso9660;
493         struct file_info *file;
494
495         iso9660 = (struct iso9660 *)(a->format->data);
496         while ((file = next_entry(iso9660)) != NULL)
497                 release_file(iso9660, file);
498         archive_string_free(&iso9660->pathname);
499         archive_string_free(&iso9660->previous_pathname);
500         if (iso9660->pending_files)
501                 free(iso9660->pending_files);
502         free(iso9660);
503         (a->format->data) = NULL;
504         return (ARCHIVE_OK);
505 }
506
507 /*
508  * This routine parses a single ISO directory record, makes sense
509  * of any extensions, and stores the result in memory.
510  */
511 static struct file_info *
512 parse_file_info(struct iso9660 *iso9660, struct file_info *parent,
513     const unsigned char *isodirrec)
514 {
515         struct file_info *file;
516         size_t name_len;
517         int flags;
518
519         /* TODO: Sanity check that name_len doesn't exceed length, etc. */
520
521         /* Create a new file entry and copy data from the ISO dir record. */
522         file = (struct file_info *)malloc(sizeof(*file));
523         if (file == NULL)
524                 return (NULL);
525         memset(file, 0, sizeof(*file));
526         file->parent = parent;
527         if (parent != NULL)
528                 parent->refcount++;
529         file->offset = toi(isodirrec + DR_extent_offset, DR_extent_size)
530             * iso9660->logical_block_size;
531         file->size = toi(isodirrec + DR_size_offset, DR_size_size);
532         file->mtime = isodate7(isodirrec + DR_date_offset);
533         file->ctime = file->atime = file->mtime;
534         name_len = (size_t)*(const unsigned char *)(isodirrec + DR_name_len_offset);
535         file->name = (char *)malloc(name_len + 1);
536         if (file->name == NULL) {
537                 free(file);
538                 return (NULL);
539         }
540         memcpy(file->name, isodirrec + DR_name_offset, name_len);
541         file->name[name_len] = '\0';
542         flags = *(isodirrec + DR_flags_offset);
543         if (flags & 0x02)
544                 file->mode = AE_IFDIR | 0700;
545         else
546                 file->mode = AE_IFREG | 0400;
547
548         /* Rockridge extensions overwrite information from above. */
549         {
550                 const unsigned char *rr_start, *rr_end;
551                 rr_end = (const unsigned char *)isodirrec
552                     + *(isodirrec + DR_length_offset);
553                 rr_start = (const unsigned char *)(isodirrec + DR_name_offset
554                     + name_len);
555                 if ((name_len & 1) == 0)
556                         rr_start++;
557                 rr_start += iso9660->suspOffset;
558                 parse_rockridge(iso9660, file, rr_start, rr_end);
559         }
560
561         /* DEBUGGING: Warn about attributes I don't yet fully support. */
562         if ((flags & ~0x02) != 0) {
563                 fprintf(stderr, "\n ** Unrecognized flag: ");
564                 dump_isodirrec(stderr, isodirrec);
565                 fprintf(stderr, "\n");
566         } else if (toi(isodirrec + DR_volume_sequence_number_offset, 2) != 1) {
567                 fprintf(stderr, "\n ** Unrecognized sequence number: ");
568                 dump_isodirrec(stderr, isodirrec);
569                 fprintf(stderr, "\n");
570         } else if (*(isodirrec + DR_file_unit_size_offset) != 0) {
571                 fprintf(stderr, "\n ** Unexpected file unit size: ");
572                 dump_isodirrec(stderr, isodirrec);
573                 fprintf(stderr, "\n");
574         } else if (*(isodirrec + DR_interleave_offset) != 0) {
575                 fprintf(stderr, "\n ** Unexpected interleave: ");
576                 dump_isodirrec(stderr, isodirrec);
577                 fprintf(stderr, "\n");
578         } else if (*(isodirrec + DR_ext_attr_length_offset) != 0) {
579                 fprintf(stderr, "\n ** Unexpected extended attribute length: ");
580                 dump_isodirrec(stderr, isodirrec);
581                 fprintf(stderr, "\n");
582         }
583
584         return (file);
585 }
586
587 static void
588 add_entry(struct iso9660 *iso9660, struct file_info *file)
589 {
590         /* Expand our pending files list as necessary. */
591         if (iso9660->pending_files_used >= iso9660->pending_files_allocated) {
592                 struct file_info **new_pending_files;
593                 int new_size = iso9660->pending_files_allocated * 2;
594
595                 if (new_size < 1024)
596                         new_size = 1024;
597                 new_pending_files = (struct file_info **)malloc(new_size * sizeof(new_pending_files[0]));
598                 if (new_pending_files == NULL)
599                         __archive_errx(1, "Out of memory");
600                 memcpy(new_pending_files, iso9660->pending_files,
601                     iso9660->pending_files_allocated * sizeof(new_pending_files[0]));
602                 if (iso9660->pending_files != NULL)
603                         free(iso9660->pending_files);
604                 iso9660->pending_files = new_pending_files;
605                 iso9660->pending_files_allocated = new_size;
606         }
607
608         iso9660->pending_files[iso9660->pending_files_used++] = file;
609 }
610
611 static void
612 parse_rockridge(struct iso9660 *iso9660, struct file_info *file,
613     const unsigned char *p, const unsigned char *end)
614 {
615         (void)iso9660; /* UNUSED */
616
617         while (p + 4 < end  /* Enough space for another entry. */
618             && p[0] >= 'A' && p[0] <= 'Z' /* Sanity-check 1st char of name. */
619             && p[1] >= 'A' && p[1] <= 'Z' /* Sanity-check 2nd char of name. */
620             && p + p[2] <= end) { /* Sanity-check length. */
621                 const unsigned char *data = p + 4;
622                 int data_length = p[2] - 4;
623                 int version = p[3];
624
625                 /*
626                  * Yes, each 'if' here does test p[0] again.
627                  * Otherwise, the fall-through handling to catch
628                  * unsupported extensions doesn't work.
629                  */
630                 switch(p[0]) {
631                 case 'C':
632                         if (p[0] == 'C' && p[1] == 'E' && version == 1) {
633                                 /*
634                                  * CE extension comprises:
635                                  *   8 byte sector containing extension
636                                  *   8 byte offset w/in above sector
637                                  *   8 byte length of continuation
638                                  */
639                                 file->ce_offset = toi(data, 4)
640                                     * iso9660->logical_block_size
641                                     + toi(data + 8, 4);
642                                 file->ce_size = toi(data + 16, 4);
643                                 break;
644                         }
645                         /* FALLTHROUGH */
646                 case 'N':
647                         if (p[0] == 'N' && p[1] == 'M' && version == 1
648                                 && *data == 0) {
649                                 /* NM extension with flag byte == 0 */
650                                 /*
651                                  * NM extension comprises:
652                                  *   one byte flag
653                                  *   rest is long name
654                                  */
655                                 /* TODO: Obey flags. */
656                                 char *old_name = file->name;
657
658                                 data++;  /* Skip flag byte. */
659                                 data_length--;
660                                 file->name = (char *)malloc(data_length + 1);
661                                 if (file->name != NULL) {
662                                         free(old_name);
663                                         memcpy(file->name, data, data_length);
664                                         file->name[data_length] = '\0';
665                                 } else
666                                         file->name = old_name;
667                                 break;
668                         }
669                         /* FALLTHROUGH */
670                 case 'P':
671                         if (p[0] == 'P' && p[1] == 'D' && version == 1) {
672                                 /*
673                                  * PD extension is padding;
674                                  * contents are always ignored.
675                                  */
676                                 break;
677                         }
678                         if (p[0] == 'P' && p[1] == 'X' && version == 1) {
679                                 /*
680                                  * PX extension comprises:
681                                  *   8 bytes for mode,
682                                  *   8 bytes for nlinks,
683                                  *   8 bytes for uid,
684                                  *   8 bytes for gid,
685                                  *   8 bytes for inode.
686                                  */
687                                 if (data_length == 32) {
688                                         file->mode = toi(data, 4);
689                                         file->nlinks = toi(data + 8, 4);
690                                         file->uid = toi(data + 16, 4);
691                                         file->gid = toi(data + 24, 4);
692                                         file->inode = toi(data + 32, 4);
693                                 }
694                                 break;
695                         }
696                         /* FALLTHROUGH */
697                 case 'R':
698                         if (p[0] == 'R' && p[1] == 'R' && version == 1) {
699                                 iso9660->seenRockridge = 1;
700                                 /*
701                                  * RR extension comprises:
702                                  *    one byte flag value
703                                  */
704                                 /* TODO: Handle RR extension. */
705                                 break;
706                         }
707                         /* FALLTHROUGH */
708                 case 'S':
709                         if (p[0] == 'S' && p[1] == 'L' && version == 1
710                             && *data == 0) {
711                                 int cont = 1;
712                                 /* SL extension with flags == 0 */
713                                 /* TODO: handle non-zero flag values. */
714                                 data++;  /* Skip flag byte. */
715                                 data_length--;
716                                 while (data_length > 0) {
717                                         unsigned char flag = *data++;
718                                         unsigned char nlen = *data++;
719                                         data_length -= 2;
720
721                                         if (cont == 0)
722                                                 archive_strcat(&file->symlink, "/");
723                                         cont = 0;
724
725                                         switch(flag) {
726                                         case 0x01: /* Continue */
727                                                 archive_strncat(&file->symlink,
728                                                     (const char *)data, nlen);
729                                                 cont = 1;
730                                                 break;
731                                         case 0x02: /* Current */
732                                                 archive_strcat(&file->symlink, ".");
733                                                 break;
734                                         case 0x04: /* Parent */
735                                                 archive_strcat(&file->symlink, "..");
736                                                 break;
737                                         case 0x08: /* Root */
738                                         case 0x10: /* Volume root */
739                                                 archive_string_empty(&file->symlink);
740                                                 break;
741                                         case 0x20: /* Hostname */
742                                                 archive_strcat(&file->symlink, "hostname");
743                                                 break;
744                                         case 0:
745                                                 archive_strncat(&file->symlink,
746                                                     (const char *)data, nlen);
747                                                 break;
748                                         default:
749                                                 /* TODO: issue a warning ? */
750                                                 break;
751                                         }
752                                         data += nlen;
753                                         data_length -= nlen;
754                                 }
755                                 break;
756                         }
757                         if (p[0] == 'S' && p[1] == 'P'
758                             && version == 1 && data_length == 7
759                             && data[0] == (unsigned char)'\xbe'
760                             && data[1] == (unsigned char)'\xef') {
761                                 /*
762                                  * SP extension stores the suspOffset
763                                  * (Number of bytes to skip between
764                                  * filename and SUSP records.)
765                                  * It is mandatory by the SUSP standard
766                                  * (IEEE 1281).
767                                  *
768                                  * It allows SUSP to coexist with
769                                  * non-SUSP uses of the System
770                                  * Use Area by placing non-SUSP data
771                                  * before SUSP data.
772                                  *
773                                  * TODO: Add a check for 'SP' in
774                                  * first directory entry, disable all SUSP
775                                  * processing if not found.
776                                  */
777                                 iso9660->suspOffset = data[2];
778                                 break;
779                         }
780                         if (p[0] == 'S' && p[1] == 'T'
781                             && data_length == 0 && version == 1) {
782                                 /*
783                                  * ST extension marks end of this
784                                  * block of SUSP entries.
785                                  *
786                                  * It allows SUSP to coexist with
787                                  * non-SUSP uses of the System
788                                  * Use Area by placing non-SUSP data
789                                  * after SUSP data.
790                                  */
791                                 return;
792                         }
793                 case 'T':
794                         if (p[0] == 'T' && p[1] == 'F' && version == 1) {
795                                 char flag = data[0];
796                                 /*
797                                  * TF extension comprises:
798                                  *   one byte flag
799                                  *   create time (optional)
800                                  *   modify time (optional)
801                                  *   access time (optional)
802                                  *   attribute time (optional)
803                                  *  Time format and presence of fields
804                                  *  is controlled by flag bits.
805                                  */
806                                 data++;
807                                 if (flag & 0x80) {
808                                         /* Use 17-byte time format. */
809                                         if (flag & 1) /* Create time. */
810                                                 data += 17;
811                                         if (flag & 2) { /* Modify time. */
812                                                 file->mtime = isodate17(data);
813                                                 data += 17;
814                                         }
815                                         if (flag & 4) { /* Access time. */
816                                                 file->atime = isodate17(data);
817                                                 data += 17;
818                                         }
819                                         if (flag & 8) { /* Attribute time. */
820                                                 file->ctime = isodate17(data);
821                                                 data += 17;
822                                         }
823                                 } else {
824                                         /* Use 7-byte time format. */
825                                         if (flag & 1) /* Create time. */
826                                                 data += 7;
827                                         if (flag & 2) { /* Modify time. */
828                                                 file->mtime = isodate7(data);
829                                                 data += 7;
830                                         }
831                                         if (flag & 4) { /* Access time. */
832                                                 file->atime = isodate7(data);
833                                                 data += 7;
834                                         }
835                                         if (flag & 8) { /* Attribute time. */
836                                                 file->ctime = isodate7(data);
837                                                 data += 7;
838                                         }
839                                 }
840                                 break;
841                         }
842                         /* FALLTHROUGH */
843                 default:
844                         /* The FALLTHROUGHs above leave us here for
845                          * any unsupported extension. */
846                         {
847                                 const unsigned char *t;
848                                 fprintf(stderr, "\nUnsupported RRIP extension for %s\n", file->name);
849                                 fprintf(stderr, " %c%c(%d):", p[0], p[1], data_length);
850                                 for (t = data; t < data + data_length && t < data + 16; t++)
851                                         fprintf(stderr, " %02x", *t);
852                                 fprintf(stderr, "\n");
853                         }
854                 }
855
856
857
858                 p += p[2];
859         }
860 }
861
862 static void
863 release_file(struct iso9660 *iso9660, struct file_info *file)
864 {
865         struct file_info *parent;
866
867         if (file->refcount == 0) {
868                 parent = file->parent;
869                 if (file->name)
870                         free(file->name);
871                 archive_string_free(&file->symlink);
872                 free(file);
873                 if (parent != NULL) {
874                         parent->refcount--;
875                         release_file(iso9660, parent);
876                 }
877         }
878 }
879
880 static int
881 next_entry_seek(struct archive_read *a, struct iso9660 *iso9660,
882     struct file_info **pfile)
883 {
884         struct file_info *file;
885         uint64_t offset;
886
887         *pfile = NULL;
888         for (;;) {
889                 *pfile = file = next_entry(iso9660);
890                 if (file == NULL)
891                         return (ARCHIVE_EOF);
892
893                 /* CE area precedes actual file data? Ignore it. */
894                 if (file->ce_offset > file->offset) {
895 fprintf(stderr, " *** Discarding CE data.\n");
896                         file->ce_offset = 0;
897                         file->ce_size = 0;
898                 }
899
900                 /* If CE exists, find and read it now. */
901                 if (file->ce_offset > 0)
902                         offset = file->ce_offset;
903                 else
904                         offset = file->offset;
905
906                 /* Seek forward to the start of the entry. */
907                 if (iso9660->current_position < offset) {
908                         off_t step = offset - iso9660->current_position;
909                         off_t bytes_read;
910                         bytes_read = (a->decompressor->skip)(a, step);
911                         if (bytes_read < 0)
912                                 return (bytes_read);
913                         iso9660->current_position = offset;
914                 }
915
916                 /* We found body of file; handle it now. */
917                 if (offset == file->offset)
918                         return (ARCHIVE_OK);
919
920                 /* Found CE?  Process it and push the file back onto list. */
921                 if (offset == file->ce_offset) {
922                         const void *p;
923                         ssize_t size = file->ce_size;
924                         ssize_t bytes_read;
925                         const unsigned char *rr_start;
926
927                         file->ce_offset = 0;
928                         file->ce_size = 0;
929                         bytes_read = (a->decompressor->read_ahead)(a, &p, size);
930                         if (bytes_read > size)
931                                 bytes_read = size;
932                         rr_start = (const unsigned char *)p;
933                         parse_rockridge(iso9660, file, rr_start,
934                             rr_start + bytes_read);
935                         (a->decompressor->consume)(a, bytes_read);
936                         iso9660->current_position += bytes_read;
937                         add_entry(iso9660, file);
938                 }
939         }
940 }
941
942 static struct file_info *
943 next_entry(struct iso9660 *iso9660)
944 {
945         int least_index;
946         uint64_t least_end_offset;
947         int i;
948         struct file_info *r;
949
950         if (iso9660->pending_files_used < 1)
951                 return (NULL);
952
953         /* Assume the first file in the list is the earliest on disk. */
954         least_index = 0;
955         least_end_offset = iso9660->pending_files[0]->offset
956             + iso9660->pending_files[0]->size;
957
958         /* Now, try to find an earlier one. */
959         for (i = 0; i < iso9660->pending_files_used; i++) {
960                 /* Use the position of the file *end* as our comparison. */
961                 uint64_t end_offset = iso9660->pending_files[i]->offset
962                     + iso9660->pending_files[i]->size;
963                 if (iso9660->pending_files[i]->ce_offset > 0
964                     && iso9660->pending_files[i]->ce_offset < iso9660->pending_files[i]->offset)
965                         end_offset = iso9660->pending_files[i]->ce_offset
966                     + iso9660->pending_files[i]->ce_size;
967                 if (least_end_offset > end_offset) {
968                         least_index = i;
969                         least_end_offset = end_offset;
970                 }
971         }
972         r = iso9660->pending_files[least_index];
973         iso9660->pending_files[least_index]
974             = iso9660->pending_files[--iso9660->pending_files_used];
975         return (r);
976 }
977
978 static unsigned int
979 toi(const void *p, int n)
980 {
981         const unsigned char *v = (const unsigned char *)p;
982         if (n > 1)
983                 return v[0] + 256 * toi(v + 1, n - 1);
984         if (n == 1)
985                 return v[0];
986         return (0);
987 }
988
989 static time_t
990 isodate7(const unsigned char *v)
991 {
992         struct tm tm;
993         int offset;
994         memset(&tm, 0, sizeof(tm));
995         tm.tm_year = v[0];
996         tm.tm_mon = v[1] - 1;
997         tm.tm_mday = v[2];
998         tm.tm_hour = v[3];
999         tm.tm_min = v[4];
1000         tm.tm_sec = v[5];
1001         /* v[6] is the signed timezone offset, in 1/4-hour increments. */
1002         offset = ((const signed char *)v)[6];
1003         if (offset > -48 && offset < 52) {
1004                 tm.tm_hour -= offset / 4;
1005                 tm.tm_min -= (offset % 4) * 15;
1006         }
1007         return (time_from_tm(&tm));
1008 }
1009
1010 static time_t
1011 isodate17(const unsigned char *v)
1012 {
1013         struct tm tm;
1014         int offset;
1015         memset(&tm, 0, sizeof(tm));
1016         tm.tm_year = (v[0] - '0') * 1000 + (v[1] - '0') * 100
1017             + (v[2] - '0') * 10 + (v[3] - '0')
1018             - 1900;
1019         tm.tm_mon = (v[4] - '0') * 10 + (v[5] - '0');
1020         tm.tm_mday = (v[6] - '0') * 10 + (v[7] - '0');
1021         tm.tm_hour = (v[8] - '0') * 10 + (v[9] - '0');
1022         tm.tm_min = (v[10] - '0') * 10 + (v[11] - '0');
1023         tm.tm_sec = (v[12] - '0') * 10 + (v[13] - '0');
1024         /* v[16] is the signed timezone offset, in 1/4-hour increments. */
1025         offset = ((const signed char *)v)[16];
1026         if (offset > -48 && offset < 52) {
1027                 tm.tm_hour -= offset / 4;
1028                 tm.tm_min -= (offset % 4) * 15;
1029         }
1030         return (time_from_tm(&tm));
1031 }
1032
1033 /*
1034  * timegm() converts a struct tm to a time_t, except it isn't standard,
1035  * so I provide my own function here that (ideally) is just a wrapper
1036  * for timegm().
1037  */
1038 static time_t
1039 time_from_tm(struct tm *t)
1040 {
1041 #if HAVE_TIMEGM
1042         return (timegm(t));
1043 #elif HAVE_STRUCT_TM_TM_GMTOFF
1044         /*
1045          * Unfortunately, timegm() isn't standard.  The standard
1046          * mktime() function is a close match, except that it uses
1047          * local timezone instead of GMT.  You can compensate for
1048          * this by adding the timezone and DST offsets back in, at
1049          * the cost of two calls to mktime().
1050          */
1051         mktime(t); /* Normalize the time and get the TZ offset. */
1052         t->tm_sec += t->tm_gmtoff; /* Try to adjust for the timezone and DST.*/
1053         if (t->tm_isdst)
1054                 t->tm_hour -= 1;
1055         return (mktime(t)); /* Re-convert. */
1056 #else
1057         /*
1058          * If you don't have tm_gmtoff, let's try resetting the timezone
1059          * (yecch!).
1060          */
1061         time_t ret;
1062         char *tz;
1063
1064         tz = getenv("TZ");
1065         setenv("TZ", "UTC 0", 1);
1066         tzset();
1067         ret = mktime(t);
1068         if (tz)
1069             setenv("TZ", tz, 1);
1070         else
1071             unsetenv("TZ");
1072         tzset();
1073         return ret;
1074 #endif
1075 }
1076
1077 static const char *
1078 build_pathname(struct archive_string *as, struct file_info *file)
1079 {
1080         if (file->parent != NULL && file->parent->name[0] != '\0') {
1081                 build_pathname(as, file->parent);
1082                 archive_strcat(as, "/");
1083         }
1084         if (file->name[0] == '\0')
1085                 archive_strcat(as, ".");
1086         else
1087                 archive_strcat(as, file->name);
1088         return (as->s);
1089 }
1090
1091 static void
1092 dump_isodirrec(FILE *out, const unsigned char *isodirrec)
1093 {
1094         fprintf(out, " l %d,",
1095             toi(isodirrec + DR_length_offset, DR_length_size));
1096         fprintf(out, " a %d,",
1097             toi(isodirrec + DR_ext_attr_length_offset, DR_ext_attr_length_size));
1098         fprintf(out, " ext 0x%x,",
1099             toi(isodirrec + DR_extent_offset, DR_extent_size));
1100         fprintf(out, " s %d,",
1101             toi(isodirrec + DR_size_offset, DR_extent_size));
1102         fprintf(out, " f 0x%02x,",
1103             toi(isodirrec + DR_flags_offset, DR_flags_size));
1104         fprintf(out, " u %d,",
1105             toi(isodirrec + DR_file_unit_size_offset, DR_file_unit_size_size));
1106         fprintf(out, " ilv %d,",
1107             toi(isodirrec + DR_interleave_offset, DR_interleave_size));
1108         fprintf(out, " seq %d,",
1109             toi(isodirrec + DR_volume_sequence_number_offset, DR_volume_sequence_number_size));
1110         fprintf(out, " nl %d:",
1111             toi(isodirrec + DR_name_len_offset, DR_name_len_size));
1112         fprintf(out, " `%.*s'",
1113             toi(isodirrec + DR_name_len_offset, DR_name_len_size), isodirrec + DR_name_offset);
1114 }