1/*-
2 * Copyright (c) 2003-2007 Tim Kientzle
3 * Copyright (c) 2010-2012 Michihiro NAKAJIMA
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
29#ifdef HAVE_ERRNO_H
30#include <errno.h>
31#endif
32/* #include <stdint.h> */ /* See archive_platform.h */
33#ifdef HAVE_STDLIB_H
34#include <stdlib.h>
35#endif
36#ifdef HAVE_STRING_H
37#include <string.h>
38#endif
39
40#include "archive.h"
41#include "archive_entry.h"
42#include "archive_entry_locale.h"
43#include "archive_private.h"
44#include "archive_read_private.h"
45
46#define	bin_magic_offset 0
47#define	bin_magic_size 2
48#define	bin_dev_offset 2
49#define	bin_dev_size 2
50#define	bin_ino_offset 4
51#define	bin_ino_size 2
52#define	bin_mode_offset 6
53#define	bin_mode_size 2
54#define	bin_uid_offset 8
55#define	bin_uid_size 2
56#define	bin_gid_offset 10
57#define	bin_gid_size 2
58#define	bin_nlink_offset 12
59#define	bin_nlink_size 2
60#define	bin_rdev_offset 14
61#define	bin_rdev_size 2
62#define	bin_mtime_offset 16
63#define	bin_mtime_size 4
64#define	bin_namesize_offset 20
65#define	bin_namesize_size 2
66#define	bin_filesize_offset 22
67#define	bin_filesize_size 4
68#define	bin_header_size 26
69
70#define	odc_magic_offset 0
71#define	odc_magic_size 6
72#define	odc_dev_offset 6
73#define	odc_dev_size 6
74#define	odc_ino_offset 12
75#define	odc_ino_size 6
76#define	odc_mode_offset 18
77#define	odc_mode_size 6
78#define	odc_uid_offset 24
79#define	odc_uid_size 6
80#define	odc_gid_offset 30
81#define	odc_gid_size 6
82#define	odc_nlink_offset 36
83#define	odc_nlink_size 6
84#define	odc_rdev_offset 42
85#define	odc_rdev_size 6
86#define	odc_mtime_offset 48
87#define	odc_mtime_size 11
88#define	odc_namesize_offset 59
89#define	odc_namesize_size 6
90#define	odc_filesize_offset 65
91#define	odc_filesize_size 11
92#define	odc_header_size 76
93
94#define	newc_magic_offset 0
95#define	newc_magic_size 6
96#define	newc_ino_offset 6
97#define	newc_ino_size 8
98#define	newc_mode_offset 14
99#define	newc_mode_size 8
100#define	newc_uid_offset 22
101#define	newc_uid_size 8
102#define	newc_gid_offset 30
103#define	newc_gid_size 8
104#define	newc_nlink_offset 38
105#define	newc_nlink_size 8
106#define	newc_mtime_offset 46
107#define	newc_mtime_size 8
108#define	newc_filesize_offset 54
109#define	newc_filesize_size 8
110#define	newc_devmajor_offset 62
111#define	newc_devmajor_size 8
112#define	newc_devminor_offset 70
113#define	newc_devminor_size 8
114#define	newc_rdevmajor_offset 78
115#define	newc_rdevmajor_size 8
116#define	newc_rdevminor_offset 86
117#define	newc_rdevminor_size 8
118#define	newc_namesize_offset 94
119#define	newc_namesize_size 8
120#define	newc_checksum_offset 102
121#define	newc_checksum_size 8
122#define	newc_header_size 110
123
124/*
125 * An afio large ASCII header, which they named itself.
126 * afio utility uses this header, if a file size is larger than 2G bytes
127 * or inode/uid/gid is bigger than 65535(0xFFFF) or mtime is bigger than
128 * 0x7fffffff, which we cannot record to odc header because of its limit.
129 * If not, uses odc header.
130 */
131#define	afiol_magic_offset 0
132#define	afiol_magic_size 6
133#define	afiol_dev_offset 6
134#define	afiol_dev_size 8	/* hex */
135#define	afiol_ino_offset 14
136#define	afiol_ino_size 16	/* hex */
137#define	afiol_ino_m_offset 30	/* 'm' */
138#define	afiol_mode_offset 31
139#define	afiol_mode_size 6	/* oct */
140#define	afiol_uid_offset 37
141#define	afiol_uid_size 8	/* hex */
142#define	afiol_gid_offset 45
143#define	afiol_gid_size 8	/* hex */
144#define	afiol_nlink_offset 53
145#define	afiol_nlink_size 8	/* hex */
146#define	afiol_rdev_offset 61
147#define	afiol_rdev_size 8	/* hex */
148#define	afiol_mtime_offset 69
149#define	afiol_mtime_size 16	/* hex */
150#define	afiol_mtime_n_offset 85	/* 'n' */
151#define	afiol_namesize_offset 86
152#define	afiol_namesize_size 4	/* hex */
153#define	afiol_flag_offset 90
154#define	afiol_flag_size 4	/* hex */
155#define	afiol_xsize_offset 94
156#define	afiol_xsize_size 4	/* hex */
157#define	afiol_xsize_s_offset 98	/* 's' */
158#define	afiol_filesize_offset 99
159#define	afiol_filesize_size 16	/* hex */
160#define	afiol_filesize_c_offset 115	/* ':' */
161#define afiol_header_size 116
162
163
164struct links_entry {
165        struct links_entry      *next;
166        struct links_entry      *previous;
167        unsigned int             links;
168        dev_t                    dev;
169        int64_t                  ino;
170        char                    *name;
171};
172
173#define	CPIO_MAGIC   0x13141516
174struct cpio {
175	int			  magic;
176	int			(*read_header)(struct archive_read *, struct cpio *,
177				     struct archive_entry *, size_t *, size_t *);
178	struct links_entry	 *links_head;
179	int64_t			  entry_bytes_remaining;
180	int64_t			  entry_bytes_unconsumed;
181	int64_t			  entry_offset;
182	int64_t			  entry_padding;
183
184	struct archive_string_conv *opt_sconv;
185	struct archive_string_conv *sconv_default;
186	int			  init_default_conversion;
187
188	int			  option_pwb;
189};
190
191static int64_t	atol16(const char *, unsigned);
192static int64_t	atol8(const char *, unsigned);
193static int	archive_read_format_cpio_bid(struct archive_read *, int);
194static int	archive_read_format_cpio_options(struct archive_read *,
195		    const char *, const char *);
196static int	archive_read_format_cpio_cleanup(struct archive_read *);
197static int	archive_read_format_cpio_read_data(struct archive_read *,
198		    const void **, size_t *, int64_t *);
199static int	archive_read_format_cpio_read_header(struct archive_read *,
200		    struct archive_entry *);
201static int	archive_read_format_cpio_skip(struct archive_read *);
202static int64_t	be4(const unsigned char *);
203static int	find_odc_header(struct archive_read *);
204static int	find_newc_header(struct archive_read *);
205static int	header_bin_be(struct archive_read *, struct cpio *,
206		    struct archive_entry *, size_t *, size_t *);
207static int	header_bin_le(struct archive_read *, struct cpio *,
208		    struct archive_entry *, size_t *, size_t *);
209static int	header_newc(struct archive_read *, struct cpio *,
210		    struct archive_entry *, size_t *, size_t *);
211static int	header_odc(struct archive_read *, struct cpio *,
212		    struct archive_entry *, size_t *, size_t *);
213static int	header_afiol(struct archive_read *, struct cpio *,
214		    struct archive_entry *, size_t *, size_t *);
215static int	is_octal(const char *, size_t);
216static int	is_hex(const char *, size_t);
217static int64_t	le4(const unsigned char *);
218static int	record_hardlink(struct archive_read *a,
219		    struct cpio *cpio, struct archive_entry *entry);
220
221int
222archive_read_support_format_cpio(struct archive *_a)
223{
224	struct archive_read *a = (struct archive_read *)_a;
225	struct cpio *cpio;
226	int r;
227
228	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
229	    ARCHIVE_STATE_NEW, "archive_read_support_format_cpio");
230
231	cpio = (struct cpio *)calloc(1, sizeof(*cpio));
232	if (cpio == NULL) {
233		archive_set_error(&a->archive, ENOMEM, "Can't allocate cpio data");
234		return (ARCHIVE_FATAL);
235	}
236	cpio->magic = CPIO_MAGIC;
237
238	r = __archive_read_register_format(a,
239	    cpio,
240	    "cpio",
241	    archive_read_format_cpio_bid,
242	    archive_read_format_cpio_options,
243	    archive_read_format_cpio_read_header,
244	    archive_read_format_cpio_read_data,
245	    archive_read_format_cpio_skip,
246	    NULL,
247	    archive_read_format_cpio_cleanup,
248	    NULL,
249	    NULL);
250
251	if (r != ARCHIVE_OK)
252		free(cpio);
253	return (ARCHIVE_OK);
254}
255
256
257static int
258archive_read_format_cpio_bid(struct archive_read *a, int best_bid)
259{
260	const unsigned char *p;
261	struct cpio *cpio;
262	int bid;
263
264	(void)best_bid; /* UNUSED */
265
266	cpio = (struct cpio *)(a->format->data);
267
268	if ((p = __archive_read_ahead(a, 6, NULL)) == NULL)
269		return (-1);
270
271	bid = 0;
272	if (memcmp(p, "070707", 6) == 0) {
273		/* ASCII cpio archive (odc, POSIX.1) */
274		cpio->read_header = header_odc;
275		bid += 48;
276		/*
277		 * XXX TODO:  More verification; Could check that only octal
278		 * digits appear in appropriate header locations. XXX
279		 */
280	} else if (memcmp(p, "070727", 6) == 0) {
281		/* afio large ASCII cpio archive */
282		cpio->read_header = header_odc;
283		bid += 48;
284		/*
285		 * XXX TODO:  More verification; Could check that almost hex
286		 * digits appear in appropriate header locations. XXX
287		 */
288	} else if (memcmp(p, "070701", 6) == 0) {
289		/* ASCII cpio archive (SVR4 without CRC) */
290		cpio->read_header = header_newc;
291		bid += 48;
292		/*
293		 * XXX TODO:  More verification; Could check that only hex
294		 * digits appear in appropriate header locations. XXX
295		 */
296	} else if (memcmp(p, "070702", 6) == 0) {
297		/* ASCII cpio archive (SVR4 with CRC) */
298		/* XXX TODO: Flag that we should check the CRC. XXX */
299		cpio->read_header = header_newc;
300		bid += 48;
301		/*
302		 * XXX TODO:  More verification; Could check that only hex
303		 * digits appear in appropriate header locations. XXX
304		 */
305	} else if (p[0] * 256 + p[1] == 070707) {
306		/* big-endian binary cpio archives */
307		cpio->read_header = header_bin_be;
308		bid += 16;
309		/* Is more verification possible here? */
310	} else if (p[0] + p[1] * 256 == 070707) {
311		/* little-endian binary cpio archives */
312		cpio->read_header = header_bin_le;
313		bid += 16;
314		/* Is more verification possible here? */
315	} else
316		return (ARCHIVE_WARN);
317
318	return (bid);
319}
320
321static int
322archive_read_format_cpio_options(struct archive_read *a,
323    const char *key, const char *val)
324{
325	struct cpio *cpio;
326	int ret = ARCHIVE_FAILED;
327
328	cpio = (struct cpio *)(a->format->data);
329	if (strcmp(key, "compat-2x")  == 0) {
330		/* Handle filenames as libarchive 2.x */
331		cpio->init_default_conversion = (val != NULL)?1:0;
332		return (ARCHIVE_OK);
333	} else if (strcmp(key, "hdrcharset")  == 0) {
334		if (val == NULL || val[0] == 0)
335			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
336			    "cpio: hdrcharset option needs a character-set name");
337		else {
338			cpio->opt_sconv =
339			    archive_string_conversion_from_charset(
340				&a->archive, val, 0);
341			if (cpio->opt_sconv != NULL)
342				ret = ARCHIVE_OK;
343			else
344				ret = ARCHIVE_FATAL;
345		}
346		return (ret);
347	} else if (strcmp(key, "pwb")  == 0) {
348		if (val != NULL && val[0] != 0)
349			cpio->option_pwb = 1;
350		return (ARCHIVE_OK);
351	}
352
353	/* Note: The "warn" return is just to inform the options
354	 * supervisor that we didn't handle it.  It will generate
355	 * a suitable error if no one used this option. */
356	return (ARCHIVE_WARN);
357}
358
359static int
360archive_read_format_cpio_read_header(struct archive_read *a,
361    struct archive_entry *entry)
362{
363	struct cpio *cpio;
364	const void *h, *hl;
365	struct archive_string_conv *sconv;
366	size_t namelength;
367	size_t name_pad;
368	int r;
369
370	cpio = (struct cpio *)(a->format->data);
371	sconv = cpio->opt_sconv;
372	if (sconv == NULL) {
373		if (!cpio->init_default_conversion) {
374			cpio->sconv_default =
375			    archive_string_default_conversion_for_read(
376			      &(a->archive));
377			cpio->init_default_conversion = 1;
378		}
379		sconv = cpio->sconv_default;
380	}
381
382	r = (cpio->read_header(a, cpio, entry, &namelength, &name_pad));
383
384	if (r < ARCHIVE_WARN)
385		return (r);
386
387	/* Read name from buffer. */
388	h = __archive_read_ahead(a, namelength + name_pad, NULL);
389	if (h == NULL)
390	    return (ARCHIVE_FATAL);
391	if (archive_entry_copy_pathname_l(entry,
392	    (const char *)h, namelength, sconv) != 0) {
393		if (errno == ENOMEM) {
394			archive_set_error(&a->archive, ENOMEM,
395			    "Can't allocate memory for Pathname");
396			return (ARCHIVE_FATAL);
397		}
398		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
399		    "Pathname can't be converted from %s to current locale.",
400		    archive_string_conversion_charset_name(sconv));
401		r = ARCHIVE_WARN;
402	}
403	cpio->entry_offset = 0;
404
405	__archive_read_consume(a, namelength + name_pad);
406
407	/* If this is a symlink, read the link contents. */
408	if (archive_entry_filetype(entry) == AE_IFLNK) {
409		if (cpio->entry_bytes_remaining > 1024 * 1024) {
410			archive_set_error(&a->archive, ENOMEM,
411			    "Rejecting malformed cpio archive: symlink contents exceed 1 megabyte");
412			return (ARCHIVE_FATAL);
413		}
414		hl = __archive_read_ahead(a,
415			(size_t)cpio->entry_bytes_remaining, NULL);
416		if (hl == NULL)
417			return (ARCHIVE_FATAL);
418		if (archive_entry_copy_symlink_l(entry, (const char *)hl,
419		    (size_t)cpio->entry_bytes_remaining, sconv) != 0) {
420			if (errno == ENOMEM) {
421				archive_set_error(&a->archive, ENOMEM,
422				    "Can't allocate memory for Linkname");
423				return (ARCHIVE_FATAL);
424			}
425			archive_set_error(&a->archive,
426			    ARCHIVE_ERRNO_FILE_FORMAT,
427			    "Linkname can't be converted from %s to "
428			    "current locale.",
429			    archive_string_conversion_charset_name(sconv));
430			r = ARCHIVE_WARN;
431		}
432		__archive_read_consume(a, cpio->entry_bytes_remaining);
433		cpio->entry_bytes_remaining = 0;
434	}
435
436	/* XXX TODO: If the full mode is 0160200, then this is a Solaris
437	 * ACL description for the following entry.  Read this body
438	 * and parse it as a Solaris-style ACL, then read the next
439	 * header.  XXX */
440
441	/* Compare name to "TRAILER!!!" to test for end-of-archive. */
442	if (namelength == 11 && strncmp((const char *)h, "TRAILER!!!",
443	    10) == 0) {
444		/* TODO: Store file location of start of block. */
445		archive_clear_error(&a->archive);
446		return (ARCHIVE_EOF);
447	}
448
449	/* Detect and record hardlinks to previously-extracted entries. */
450	if (record_hardlink(a, cpio, entry) != ARCHIVE_OK) {
451		return (ARCHIVE_FATAL);
452	}
453
454	return (r);
455}
456
457static int
458archive_read_format_cpio_read_data(struct archive_read *a,
459    const void **buff, size_t *size, int64_t *offset)
460{
461	ssize_t bytes_read;
462	struct cpio *cpio;
463
464	cpio = (struct cpio *)(a->format->data);
465
466	if (cpio->entry_bytes_unconsumed) {
467		__archive_read_consume(a, cpio->entry_bytes_unconsumed);
468		cpio->entry_bytes_unconsumed = 0;
469	}
470
471	if (cpio->entry_bytes_remaining > 0) {
472		*buff = __archive_read_ahead(a, 1, &bytes_read);
473		if (bytes_read <= 0)
474			return (ARCHIVE_FATAL);
475		if (bytes_read > cpio->entry_bytes_remaining)
476			bytes_read = (ssize_t)cpio->entry_bytes_remaining;
477		*size = bytes_read;
478		cpio->entry_bytes_unconsumed = bytes_read;
479		*offset = cpio->entry_offset;
480		cpio->entry_offset += bytes_read;
481		cpio->entry_bytes_remaining -= bytes_read;
482		return (ARCHIVE_OK);
483	} else {
484		if (cpio->entry_padding !=
485			__archive_read_consume(a, cpio->entry_padding)) {
486			return (ARCHIVE_FATAL);
487		}
488		cpio->entry_padding = 0;
489		*buff = NULL;
490		*size = 0;
491		*offset = cpio->entry_offset;
492		return (ARCHIVE_EOF);
493	}
494}
495
496static int
497archive_read_format_cpio_skip(struct archive_read *a)
498{
499	struct cpio *cpio = (struct cpio *)(a->format->data);
500	int64_t to_skip = cpio->entry_bytes_remaining + cpio->entry_padding +
501		cpio->entry_bytes_unconsumed;
502
503	if (to_skip != __archive_read_consume(a, to_skip)) {
504		return (ARCHIVE_FATAL);
505	}
506	cpio->entry_bytes_remaining = 0;
507	cpio->entry_padding = 0;
508	cpio->entry_bytes_unconsumed = 0;
509	return (ARCHIVE_OK);
510}
511
512/*
513 * Skip forward to the next cpio newc header by searching for the
514 * 07070[12] string.  This should be generalized and merged with
515 * find_odc_header below.
516 */
517static int
518is_hex(const char *p, size_t len)
519{
520	while (len-- > 0) {
521		if ((*p >= '0' && *p <= '9')
522		    || (*p >= 'a' && *p <= 'f')
523		    || (*p >= 'A' && *p <= 'F'))
524			++p;
525		else
526			return (0);
527	}
528	return (1);
529}
530
531static int
532find_newc_header(struct archive_read *a)
533{
534	const void *h;
535	const char *p, *q;
536	size_t skip, skipped = 0;
537	ssize_t bytes;
538
539	for (;;) {
540		h = __archive_read_ahead(a, newc_header_size, &bytes);
541		if (h == NULL)
542			return (ARCHIVE_FATAL);
543		p = h;
544		q = p + bytes;
545
546		/* Try the typical case first, then go into the slow search.*/
547		if (memcmp("07070", p, 5) == 0
548		    && (p[5] == '1' || p[5] == '2')
549		    && is_hex(p, newc_header_size))
550			return (ARCHIVE_OK);
551
552		/*
553		 * Scan ahead until we find something that looks
554		 * like a newc header.
555		 */
556		while (p + newc_header_size <= q) {
557			switch (p[5]) {
558			case '1':
559			case '2':
560				if (memcmp("07070", p, 5) == 0
561				    && is_hex(p, newc_header_size)) {
562					skip = p - (const char *)h;
563					__archive_read_consume(a, skip);
564					skipped += skip;
565					if (skipped > 0) {
566						archive_set_error(&a->archive,
567						    0,
568						    "Skipped %d bytes before "
569						    "finding valid header",
570						    (int)skipped);
571						return (ARCHIVE_WARN);
572					}
573					return (ARCHIVE_OK);
574				}
575				p += 2;
576				break;
577			case '0':
578				p++;
579				break;
580			default:
581				p += 6;
582				break;
583			}
584		}
585		skip = p - (const char *)h;
586		__archive_read_consume(a, skip);
587		skipped += skip;
588	}
589}
590
591static int
592header_newc(struct archive_read *a, struct cpio *cpio,
593    struct archive_entry *entry, size_t *namelength, size_t *name_pad)
594{
595	const void *h;
596	const char *header;
597	int r;
598
599	r = find_newc_header(a);
600	if (r < ARCHIVE_WARN)
601		return (r);
602
603	/* Read fixed-size portion of header. */
604	h = __archive_read_ahead(a, newc_header_size, NULL);
605	if (h == NULL)
606	    return (ARCHIVE_FATAL);
607
608	/* Parse out hex fields. */
609	header = (const char *)h;
610
611	if (memcmp(header + newc_magic_offset, "070701", 6) == 0) {
612		a->archive.archive_format = ARCHIVE_FORMAT_CPIO_SVR4_NOCRC;
613		a->archive.archive_format_name = "ASCII cpio (SVR4 with no CRC)";
614	} else if (memcmp(header + newc_magic_offset, "070702", 6) == 0) {
615		a->archive.archive_format = ARCHIVE_FORMAT_CPIO_SVR4_CRC;
616		a->archive.archive_format_name = "ASCII cpio (SVR4 with CRC)";
617	} else {
618		/* TODO: Abort here? */
619	}
620
621	archive_entry_set_devmajor(entry,
622		(dev_t)atol16(header + newc_devmajor_offset, newc_devmajor_size));
623	archive_entry_set_devminor(entry,
624		(dev_t)atol16(header + newc_devminor_offset, newc_devminor_size));
625	archive_entry_set_ino(entry, atol16(header + newc_ino_offset, newc_ino_size));
626	archive_entry_set_mode(entry,
627		(mode_t)atol16(header + newc_mode_offset, newc_mode_size));
628	archive_entry_set_uid(entry, atol16(header + newc_uid_offset, newc_uid_size));
629	archive_entry_set_gid(entry, atol16(header + newc_gid_offset, newc_gid_size));
630	archive_entry_set_nlink(entry,
631		(unsigned int)atol16(header + newc_nlink_offset, newc_nlink_size));
632	archive_entry_set_rdevmajor(entry,
633		(dev_t)atol16(header + newc_rdevmajor_offset, newc_rdevmajor_size));
634	archive_entry_set_rdevminor(entry,
635		(dev_t)atol16(header + newc_rdevminor_offset, newc_rdevminor_size));
636	archive_entry_set_mtime(entry, atol16(header + newc_mtime_offset, newc_mtime_size), 0);
637	*namelength = (size_t)atol16(header + newc_namesize_offset, newc_namesize_size);
638	/* Pad name to 2 more than a multiple of 4. */
639	*name_pad = (2 - *namelength) & 3;
640
641	/* Make sure that the padded name length fits into size_t. */
642	if (*name_pad > SIZE_MAX - *namelength) {
643		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
644		    "cpio archive has invalid namelength");
645		return (ARCHIVE_FATAL);
646	}
647
648	/*
649	 * Note: entry_bytes_remaining is at least 64 bits and
650	 * therefore guaranteed to be big enough for a 33-bit file
651	 * size.
652	 */
653	cpio->entry_bytes_remaining =
654	    atol16(header + newc_filesize_offset, newc_filesize_size);
655	archive_entry_set_size(entry, cpio->entry_bytes_remaining);
656	/* Pad file contents to a multiple of 4. */
657	cpio->entry_padding = 3 & -cpio->entry_bytes_remaining;
658	__archive_read_consume(a, newc_header_size);
659	return (r);
660}
661
662/*
663 * Skip forward to the next cpio odc header by searching for the
664 * 070707 string.  This is a hand-optimized search that could
665 * probably be easily generalized to handle all character-based
666 * cpio variants.
667 */
668static int
669is_octal(const char *p, size_t len)
670{
671	while (len-- > 0) {
672		if (*p < '0' || *p > '7')
673			return (0);
674	        ++p;
675	}
676	return (1);
677}
678
679static int
680is_afio_large(const char *h, size_t len)
681{
682	if (len < afiol_header_size)
683		return (0);
684	if (h[afiol_ino_m_offset] != 'm'
685	    || h[afiol_mtime_n_offset] != 'n'
686	    || h[afiol_xsize_s_offset] != 's'
687	    || h[afiol_filesize_c_offset] != ':')
688		return (0);
689	if (!is_hex(h + afiol_dev_offset, afiol_ino_m_offset - afiol_dev_offset))
690		return (0);
691	if (!is_hex(h + afiol_mode_offset, afiol_mtime_n_offset - afiol_mode_offset))
692		return (0);
693	if (!is_hex(h + afiol_namesize_offset, afiol_xsize_s_offset - afiol_namesize_offset))
694		return (0);
695	if (!is_hex(h + afiol_filesize_offset, afiol_filesize_size))
696		return (0);
697	return (1);
698}
699
700static int
701find_odc_header(struct archive_read *a)
702{
703	const void *h;
704	const char *p, *q;
705	size_t skip, skipped = 0;
706	ssize_t bytes;
707
708	for (;;) {
709		h = __archive_read_ahead(a, odc_header_size, &bytes);
710		if (h == NULL)
711			return (ARCHIVE_FATAL);
712		p = h;
713		q = p + bytes;
714
715		/* Try the typical case first, then go into the slow search.*/
716		if (memcmp("070707", p, 6) == 0 && is_octal(p, odc_header_size))
717			return (ARCHIVE_OK);
718		if (memcmp("070727", p, 6) == 0 && is_afio_large(p, bytes)) {
719			a->archive.archive_format = ARCHIVE_FORMAT_CPIO_AFIO_LARGE;
720			return (ARCHIVE_OK);
721		}
722
723		/*
724		 * Scan ahead until we find something that looks
725		 * like an odc header.
726		 */
727		while (p + odc_header_size <= q) {
728			switch (p[5]) {
729			case '7':
730				if ((memcmp("070707", p, 6) == 0
731				    && is_octal(p, odc_header_size))
732				    || (memcmp("070727", p, 6) == 0
733				        && is_afio_large(p, q - p))) {
734					skip = p - (const char *)h;
735					__archive_read_consume(a, skip);
736					skipped += skip;
737					if (p[4] == '2')
738						a->archive.archive_format =
739						    ARCHIVE_FORMAT_CPIO_AFIO_LARGE;
740					if (skipped > 0) {
741						archive_set_error(&a->archive,
742						    0,
743						    "Skipped %d bytes before "
744						    "finding valid header",
745						    (int)skipped);
746						return (ARCHIVE_WARN);
747					}
748					return (ARCHIVE_OK);
749				}
750				p += 2;
751				break;
752			case '0':
753				p++;
754				break;
755			default:
756				p += 6;
757				break;
758			}
759		}
760		skip = p - (const char *)h;
761		__archive_read_consume(a, skip);
762		skipped += skip;
763	}
764}
765
766static int
767header_odc(struct archive_read *a, struct cpio *cpio,
768    struct archive_entry *entry, size_t *namelength, size_t *name_pad)
769{
770	const void *h;
771	int r;
772	const char *header;
773
774	a->archive.archive_format = ARCHIVE_FORMAT_CPIO_POSIX;
775	a->archive.archive_format_name = "POSIX octet-oriented cpio";
776
777	/* Find the start of the next header. */
778	r = find_odc_header(a);
779	if (r < ARCHIVE_WARN)
780		return (r);
781
782	if (a->archive.archive_format == ARCHIVE_FORMAT_CPIO_AFIO_LARGE) {
783		int r2 = (header_afiol(a, cpio, entry, namelength, name_pad));
784		if (r2 == ARCHIVE_OK)
785			return (r);
786		else
787			return (r2);
788	}
789
790	/* Read fixed-size portion of header. */
791	h = __archive_read_ahead(a, odc_header_size, NULL);
792	if (h == NULL)
793	    return (ARCHIVE_FATAL);
794
795	/* Parse out octal fields. */
796	header = (const char *)h;
797
798	archive_entry_set_dev(entry,
799		(dev_t)atol8(header + odc_dev_offset, odc_dev_size));
800	archive_entry_set_ino(entry, atol8(header + odc_ino_offset, odc_ino_size));
801	archive_entry_set_mode(entry,
802		(mode_t)atol8(header + odc_mode_offset, odc_mode_size));
803	archive_entry_set_uid(entry, atol8(header + odc_uid_offset, odc_uid_size));
804	archive_entry_set_gid(entry, atol8(header + odc_gid_offset, odc_gid_size));
805	archive_entry_set_nlink(entry,
806		(unsigned int)atol8(header + odc_nlink_offset, odc_nlink_size));
807	archive_entry_set_rdev(entry,
808		(dev_t)atol8(header + odc_rdev_offset, odc_rdev_size));
809	archive_entry_set_mtime(entry, atol8(header + odc_mtime_offset, odc_mtime_size), 0);
810	*namelength = (size_t)atol8(header + odc_namesize_offset, odc_namesize_size);
811	*name_pad = 0; /* No padding of filename. */
812
813	/*
814	 * Note: entry_bytes_remaining is at least 64 bits and
815	 * therefore guaranteed to be big enough for a 33-bit file
816	 * size.
817	 */
818	cpio->entry_bytes_remaining =
819	    atol8(header + odc_filesize_offset, odc_filesize_size);
820	archive_entry_set_size(entry, cpio->entry_bytes_remaining);
821	cpio->entry_padding = 0;
822	__archive_read_consume(a, odc_header_size);
823	return (r);
824}
825
826/*
827 * NOTE: if a filename suffix is ".z", it is the file gziped by afio.
828 * it would be nice that we can show uncompressed file size and we can
829 * uncompressed file contents automatically, unfortunately we have nothing
830 * to get a uncompressed file size while reading each header. It means
831 * we also cannot uncompress file contents under our framework.
832 */
833static int
834header_afiol(struct archive_read *a, struct cpio *cpio,
835    struct archive_entry *entry, size_t *namelength, size_t *name_pad)
836{
837	const void *h;
838	const char *header;
839
840	a->archive.archive_format = ARCHIVE_FORMAT_CPIO_AFIO_LARGE;
841	a->archive.archive_format_name = "afio large ASCII";
842
843	/* Read fixed-size portion of header. */
844	h = __archive_read_ahead(a, afiol_header_size, NULL);
845	if (h == NULL)
846	    return (ARCHIVE_FATAL);
847
848	/* Parse out octal fields. */
849	header = (const char *)h;
850
851	archive_entry_set_dev(entry,
852		(dev_t)atol16(header + afiol_dev_offset, afiol_dev_size));
853	archive_entry_set_ino(entry, atol16(header + afiol_ino_offset, afiol_ino_size));
854	archive_entry_set_mode(entry,
855		(mode_t)atol8(header + afiol_mode_offset, afiol_mode_size));
856	archive_entry_set_uid(entry, atol16(header + afiol_uid_offset, afiol_uid_size));
857	archive_entry_set_gid(entry, atol16(header + afiol_gid_offset, afiol_gid_size));
858	archive_entry_set_nlink(entry,
859		(unsigned int)atol16(header + afiol_nlink_offset, afiol_nlink_size));
860	archive_entry_set_rdev(entry,
861		(dev_t)atol16(header + afiol_rdev_offset, afiol_rdev_size));
862	archive_entry_set_mtime(entry, atol16(header + afiol_mtime_offset, afiol_mtime_size), 0);
863	*namelength = (size_t)atol16(header + afiol_namesize_offset, afiol_namesize_size);
864	*name_pad = 0; /* No padding of filename. */
865
866	cpio->entry_bytes_remaining =
867	    atol16(header + afiol_filesize_offset, afiol_filesize_size);
868	archive_entry_set_size(entry, cpio->entry_bytes_remaining);
869	cpio->entry_padding = 0;
870	__archive_read_consume(a, afiol_header_size);
871	return (ARCHIVE_OK);
872}
873
874
875static int
876header_bin_le(struct archive_read *a, struct cpio *cpio,
877    struct archive_entry *entry, size_t *namelength, size_t *name_pad)
878{
879	const void *h;
880	const unsigned char *header;
881
882	a->archive.archive_format = ARCHIVE_FORMAT_CPIO_BIN_LE;
883	a->archive.archive_format_name = "cpio (little-endian binary)";
884
885	/* Read fixed-size portion of header. */
886	h = __archive_read_ahead(a, bin_header_size, NULL);
887	if (h == NULL) {
888	    archive_set_error(&a->archive, 0,
889		"End of file trying to read next cpio header");
890	    return (ARCHIVE_FATAL);
891	}
892
893	/* Parse out binary fields. */
894	header = (const unsigned char *)h;
895
896	archive_entry_set_dev(entry, header[bin_dev_offset] + header[bin_dev_offset + 1] * 256);
897	archive_entry_set_ino(entry, header[bin_ino_offset] + header[bin_ino_offset + 1] * 256);
898	archive_entry_set_mode(entry, header[bin_mode_offset] + header[bin_mode_offset + 1] * 256);
899	if (cpio->option_pwb) {
900		/* turn off random bits left over from V6 inode */
901		archive_entry_set_mode(entry, archive_entry_mode(entry) & 067777);
902		if ((archive_entry_mode(entry) & AE_IFMT) == 0)
903			archive_entry_set_mode(entry, archive_entry_mode(entry) | AE_IFREG);
904	}
905	archive_entry_set_uid(entry, header[bin_uid_offset] + header[bin_uid_offset + 1] * 256);
906	archive_entry_set_gid(entry, header[bin_gid_offset] + header[bin_gid_offset + 1] * 256);
907	archive_entry_set_nlink(entry, header[bin_nlink_offset] + header[bin_nlink_offset + 1] * 256);
908	archive_entry_set_rdev(entry, header[bin_rdev_offset] + header[bin_rdev_offset + 1] * 256);
909	archive_entry_set_mtime(entry, le4(header + bin_mtime_offset), 0);
910	*namelength = header[bin_namesize_offset] + header[bin_namesize_offset + 1] * 256;
911	*name_pad = *namelength & 1; /* Pad to even. */
912
913	cpio->entry_bytes_remaining = le4(header + bin_filesize_offset);
914	archive_entry_set_size(entry, cpio->entry_bytes_remaining);
915	cpio->entry_padding = cpio->entry_bytes_remaining & 1; /* Pad to even. */
916	__archive_read_consume(a, bin_header_size);
917	return (ARCHIVE_OK);
918}
919
920static int
921header_bin_be(struct archive_read *a, struct cpio *cpio,
922    struct archive_entry *entry, size_t *namelength, size_t *name_pad)
923{
924	const void *h;
925	const unsigned char *header;
926
927	a->archive.archive_format = ARCHIVE_FORMAT_CPIO_BIN_BE;
928	a->archive.archive_format_name = "cpio (big-endian binary)";
929
930	/* Read fixed-size portion of header. */
931	h = __archive_read_ahead(a, bin_header_size, NULL);
932	if (h == NULL) {
933	    archive_set_error(&a->archive, 0,
934		"End of file trying to read next cpio header");
935	    return (ARCHIVE_FATAL);
936	}
937
938	/* Parse out binary fields. */
939	header = (const unsigned char *)h;
940
941	archive_entry_set_dev(entry, header[bin_dev_offset] * 256 + header[bin_dev_offset + 1]);
942	archive_entry_set_ino(entry, header[bin_ino_offset] * 256 + header[bin_ino_offset + 1]);
943	archive_entry_set_mode(entry, header[bin_mode_offset] * 256 + header[bin_mode_offset + 1]);
944	if (cpio->option_pwb) {
945		/* turn off random bits left over from V6 inode */
946		archive_entry_set_mode(entry, archive_entry_mode(entry) & 067777);
947		if ((archive_entry_mode(entry) & AE_IFMT) == 0)
948			archive_entry_set_mode(entry, archive_entry_mode(entry) | AE_IFREG);
949	}
950	archive_entry_set_uid(entry, header[bin_uid_offset] * 256 + header[bin_uid_offset + 1]);
951	archive_entry_set_gid(entry, header[bin_gid_offset] * 256 + header[bin_gid_offset + 1]);
952	archive_entry_set_nlink(entry, header[bin_nlink_offset] * 256 + header[bin_nlink_offset + 1]);
953	archive_entry_set_rdev(entry, header[bin_rdev_offset] * 256 + header[bin_rdev_offset + 1]);
954	archive_entry_set_mtime(entry, be4(header + bin_mtime_offset), 0);
955	*namelength = header[bin_namesize_offset] * 256 + header[bin_namesize_offset + 1];
956	*name_pad = *namelength & 1; /* Pad to even. */
957
958	cpio->entry_bytes_remaining = be4(header + bin_filesize_offset);
959	archive_entry_set_size(entry, cpio->entry_bytes_remaining);
960	cpio->entry_padding = cpio->entry_bytes_remaining & 1; /* Pad to even. */
961	    __archive_read_consume(a, bin_header_size);
962	return (ARCHIVE_OK);
963}
964
965static int
966archive_read_format_cpio_cleanup(struct archive_read *a)
967{
968	struct cpio *cpio;
969
970	cpio = (struct cpio *)(a->format->data);
971        /* Free inode->name map */
972        while (cpio->links_head != NULL) {
973                struct links_entry *lp = cpio->links_head->next;
974
975                free(cpio->links_head->name);
976                free(cpio->links_head);
977                cpio->links_head = lp;
978        }
979	free(cpio);
980	(a->format->data) = NULL;
981	return (ARCHIVE_OK);
982}
983
984static int64_t
985le4(const unsigned char *p)
986{
987	return ((p[0] << 16) | (((int64_t)p[1]) << 24) | (p[2] << 0) | (p[3] << 8));
988}
989
990
991static int64_t
992be4(const unsigned char *p)
993{
994	return ((((int64_t)p[0]) << 24) | (p[1] << 16) | (p[2] << 8) | (p[3]));
995}
996
997/*
998 * Note that this implementation does not (and should not!) obey
999 * locale settings; you cannot simply substitute strtol here, since
1000 * it does obey locale.
1001 */
1002static int64_t
1003atol8(const char *p, unsigned char_cnt)
1004{
1005	int64_t l;
1006	int digit;
1007
1008	l = 0;
1009	while (char_cnt-- > 0) {
1010		if (*p >= '0' && *p <= '7')
1011			digit = *p - '0';
1012		else
1013			return (l);
1014		p++;
1015		l <<= 3;
1016		l |= digit;
1017	}
1018	return (l);
1019}
1020
1021static int64_t
1022atol16(const char *p, unsigned char_cnt)
1023{
1024	int64_t l;
1025	int digit;
1026
1027	l = 0;
1028	while (char_cnt-- > 0) {
1029		if (*p >= 'a' && *p <= 'f')
1030			digit = *p - 'a' + 10;
1031		else if (*p >= 'A' && *p <= 'F')
1032			digit = *p - 'A' + 10;
1033		else if (*p >= '0' && *p <= '9')
1034			digit = *p - '0';
1035		else
1036			return (l);
1037		p++;
1038		l <<= 4;
1039		l |= digit;
1040	}
1041	return (l);
1042}
1043
1044static int
1045record_hardlink(struct archive_read *a,
1046    struct cpio *cpio, struct archive_entry *entry)
1047{
1048	struct links_entry      *le;
1049	dev_t dev;
1050	int64_t ino;
1051
1052	if (archive_entry_nlink(entry) <= 1)
1053		return (ARCHIVE_OK);
1054
1055	dev = archive_entry_dev(entry);
1056	ino = archive_entry_ino64(entry);
1057
1058	/*
1059	 * First look in the list of multiply-linked files.  If we've
1060	 * already dumped it, convert this entry to a hard link entry.
1061	 */
1062	for (le = cpio->links_head; le; le = le->next) {
1063		if (le->dev == dev && le->ino == ino) {
1064			archive_entry_copy_hardlink(entry, le->name);
1065
1066			if (--le->links <= 0) {
1067				if (le->previous != NULL)
1068					le->previous->next = le->next;
1069				if (le->next != NULL)
1070					le->next->previous = le->previous;
1071				if (cpio->links_head == le)
1072					cpio->links_head = le->next;
1073				free(le->name);
1074				free(le);
1075			}
1076
1077			return (ARCHIVE_OK);
1078		}
1079	}
1080
1081	le = (struct links_entry *)malloc(sizeof(struct links_entry));
1082	if (le == NULL) {
1083		archive_set_error(&a->archive,
1084		    ENOMEM, "Out of memory adding file to list");
1085		return (ARCHIVE_FATAL);
1086	}
1087	if (cpio->links_head != NULL)
1088		cpio->links_head->previous = le;
1089	le->next = cpio->links_head;
1090	le->previous = NULL;
1091	cpio->links_head = le;
1092	le->dev = dev;
1093	le->ino = ino;
1094	le->links = archive_entry_nlink(entry) - 1;
1095	le->name = strdup(archive_entry_pathname(entry));
1096	if (le->name == NULL) {
1097		archive_set_error(&a->archive,
1098		    ENOMEM, "Out of memory adding file to list");
1099		return (ARCHIVE_FATAL);
1100	}
1101
1102	return (ARCHIVE_OK);
1103}
1104