archive_write_disk_posix.c revision 353376
1/*-
2 * Copyright (c) 2003-2010 Tim Kientzle
3 * Copyright (c) 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 *    in this position and unchanged.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "archive_platform.h"
29__FBSDID("$FreeBSD$");
30
31#if !defined(_WIN32) || defined(__CYGWIN__)
32
33#ifdef HAVE_SYS_TYPES_H
34#include <sys/types.h>
35#endif
36#ifdef HAVE_SYS_ACL_H
37#include <sys/acl.h>
38#endif
39#ifdef HAVE_SYS_EXTATTR_H
40#include <sys/extattr.h>
41#endif
42#if HAVE_SYS_XATTR_H
43#include <sys/xattr.h>
44#elif HAVE_ATTR_XATTR_H
45#include <attr/xattr.h>
46#endif
47#ifdef HAVE_SYS_EA_H
48#include <sys/ea.h>
49#endif
50#ifdef HAVE_SYS_IOCTL_H
51#include <sys/ioctl.h>
52#endif
53#ifdef HAVE_SYS_STAT_H
54#include <sys/stat.h>
55#endif
56#ifdef HAVE_SYS_TIME_H
57#include <sys/time.h>
58#endif
59#ifdef HAVE_SYS_UTIME_H
60#include <sys/utime.h>
61#endif
62#ifdef HAVE_COPYFILE_H
63#include <copyfile.h>
64#endif
65#ifdef HAVE_ERRNO_H
66#include <errno.h>
67#endif
68#ifdef HAVE_FCNTL_H
69#include <fcntl.h>
70#endif
71#ifdef HAVE_GRP_H
72#include <grp.h>
73#endif
74#ifdef HAVE_LANGINFO_H
75#include <langinfo.h>
76#endif
77#ifdef HAVE_LINUX_FS_H
78#include <linux/fs.h>	/* for Linux file flags */
79#endif
80/*
81 * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
82 * As the include guards don't agree, the order of include is important.
83 */
84#ifdef HAVE_LINUX_EXT2_FS_H
85#include <linux/ext2_fs.h>	/* for Linux file flags */
86#endif
87#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
88#include <ext2fs/ext2_fs.h>	/* Linux file flags, broken on Cygwin */
89#endif
90#ifdef HAVE_LIMITS_H
91#include <limits.h>
92#endif
93#ifdef HAVE_PWD_H
94#include <pwd.h>
95#endif
96#include <stdio.h>
97#ifdef HAVE_STDLIB_H
98#include <stdlib.h>
99#endif
100#ifdef HAVE_STRING_H
101#include <string.h>
102#endif
103#ifdef HAVE_UNISTD_H
104#include <unistd.h>
105#endif
106#ifdef HAVE_UTIME_H
107#include <utime.h>
108#endif
109#ifdef F_GETTIMES /* Tru64 specific */
110#include <sys/fcntl1.h>
111#endif
112
113/*
114 * Macro to cast st_mtime and time_t to an int64 so that 2 numbers can reliably be compared.
115 *
116 * It assumes that the input is an integer type of no more than 64 bits.
117 * If the number is less than zero, t must be a signed type, so it fits in
118 * int64_t. Otherwise, it's a nonnegative value so we can cast it to uint64_t
119 * without loss. But it could be a large unsigned value, so we have to clip it
120 * to INT64_MAX.*
121 */
122#define to_int64_time(t) \
123   ((t) < 0 ? (int64_t)(t) : (uint64_t)(t) > (uint64_t)INT64_MAX ? INT64_MAX : (int64_t)(t))
124
125#if __APPLE__
126#include <TargetConditionals.h>
127#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H
128#include <quarantine.h>
129#define HAVE_QUARANTINE 1
130#endif
131#endif
132
133#ifdef HAVE_ZLIB_H
134#include <zlib.h>
135#endif
136
137/* TODO: Support Mac OS 'quarantine' feature.  This is really just a
138 * standard tag to mark files that have been downloaded as "tainted".
139 * On Mac OS, we should mark the extracted files as tainted if the
140 * archive being read was tainted.  Windows has a similar feature; we
141 * should investigate ways to support this generically. */
142
143#include "archive.h"
144#include "archive_acl_private.h"
145#include "archive_string.h"
146#include "archive_endian.h"
147#include "archive_entry.h"
148#include "archive_private.h"
149#include "archive_write_disk_private.h"
150
151#ifndef O_BINARY
152#define O_BINARY 0
153#endif
154#ifndef O_CLOEXEC
155#define O_CLOEXEC 0
156#endif
157
158/* Ignore non-int O_NOFOLLOW constant. */
159/* gnulib's fcntl.h does this on AIX, but it seems practical everywhere */
160#if defined O_NOFOLLOW && !(INT_MIN <= O_NOFOLLOW && O_NOFOLLOW <= INT_MAX)
161#undef O_NOFOLLOW
162#endif
163
164#ifndef O_NOFOLLOW
165#define O_NOFOLLOW 0
166#endif
167
168#ifndef AT_FDCWD
169#define AT_FDCWD -100
170#endif
171
172struct fixup_entry {
173	struct fixup_entry	*next;
174	struct archive_acl	 acl;
175	mode_t			 mode;
176	int64_t			 atime;
177	int64_t                  birthtime;
178	int64_t			 mtime;
179	int64_t			 ctime;
180	unsigned long		 atime_nanos;
181	unsigned long            birthtime_nanos;
182	unsigned long		 mtime_nanos;
183	unsigned long		 ctime_nanos;
184	unsigned long		 fflags_set;
185	size_t			 mac_metadata_size;
186	void			*mac_metadata;
187	int			 fixup; /* bitmask of what needs fixing */
188	char			*name;
189};
190
191/*
192 * We use a bitmask to track which operations remain to be done for
193 * this file.  In particular, this helps us avoid unnecessary
194 * operations when it's possible to take care of one step as a
195 * side-effect of another.  For example, mkdir() can specify the mode
196 * for the newly-created object but symlink() cannot.  This means we
197 * can skip chmod() if mkdir() succeeded, but we must explicitly
198 * chmod() if we're trying to create a directory that already exists
199 * (mkdir() failed) or if we're restoring a symlink.  Similarly, we
200 * need to verify UID/GID before trying to restore SUID/SGID bits;
201 * that verification can occur explicitly through a stat() call or
202 * implicitly because of a successful chown() call.
203 */
204#define	TODO_MODE_FORCE		0x40000000
205#define	TODO_MODE_BASE		0x20000000
206#define	TODO_SUID		0x10000000
207#define	TODO_SUID_CHECK		0x08000000
208#define	TODO_SGID		0x04000000
209#define	TODO_SGID_CHECK		0x02000000
210#define	TODO_APPLEDOUBLE	0x01000000
211#define	TODO_MODE		(TODO_MODE_BASE|TODO_SUID|TODO_SGID)
212#define	TODO_TIMES		ARCHIVE_EXTRACT_TIME
213#define	TODO_OWNER		ARCHIVE_EXTRACT_OWNER
214#define	TODO_FFLAGS		ARCHIVE_EXTRACT_FFLAGS
215#define	TODO_ACLS		ARCHIVE_EXTRACT_ACL
216#define	TODO_XATTR		ARCHIVE_EXTRACT_XATTR
217#define	TODO_MAC_METADATA	ARCHIVE_EXTRACT_MAC_METADATA
218#define	TODO_HFS_COMPRESSION	ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED
219
220struct archive_write_disk {
221	struct archive	archive;
222
223	mode_t			 user_umask;
224	struct fixup_entry	*fixup_list;
225	struct fixup_entry	*current_fixup;
226	int64_t			 user_uid;
227	int			 skip_file_set;
228	int64_t			 skip_file_dev;
229	int64_t			 skip_file_ino;
230	time_t			 start_time;
231
232	int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid);
233	void  (*cleanup_gid)(void *private);
234	void			*lookup_gid_data;
235	int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid);
236	void  (*cleanup_uid)(void *private);
237	void			*lookup_uid_data;
238
239	/*
240	 * Full path of last file to satisfy symlink checks.
241	 */
242	struct archive_string	path_safe;
243
244	/*
245	 * Cached stat data from disk for the current entry.
246	 * If this is valid, pst points to st.  Otherwise,
247	 * pst is null.
248	 */
249	struct stat		 st;
250	struct stat		*pst;
251
252	/* Information about the object being restored right now. */
253	struct archive_entry	*entry; /* Entry being extracted. */
254	char			*name; /* Name of entry, possibly edited. */
255	struct archive_string	 _name_data; /* backing store for 'name' */
256	/* Tasks remaining for this object. */
257	int			 todo;
258	/* Tasks deferred until end-of-archive. */
259	int			 deferred;
260	/* Options requested by the client. */
261	int			 flags;
262	/* Handle for the file we're restoring. */
263	int			 fd;
264	/* Current offset for writing data to the file. */
265	int64_t			 offset;
266	/* Last offset actually written to disk. */
267	int64_t			 fd_offset;
268	/* Total bytes actually written to files. */
269	int64_t			 total_bytes_written;
270	/* Maximum size of file, -1 if unknown. */
271	int64_t			 filesize;
272	/* Dir we were in before this restore; only for deep paths. */
273	int			 restore_pwd;
274	/* Mode we should use for this entry; affected by _PERM and umask. */
275	mode_t			 mode;
276	/* UID/GID to use in restoring this entry. */
277	int64_t			 uid;
278	int64_t			 gid;
279	/*
280	 * HFS+ Compression.
281	 */
282	/* Xattr "com.apple.decmpfs". */
283	uint32_t		 decmpfs_attr_size;
284	unsigned char		*decmpfs_header_p;
285	/* ResourceFork set options used for fsetxattr. */
286	int			 rsrc_xattr_options;
287	/* Xattr "com.apple.ResourceFork". */
288	unsigned char		*resource_fork;
289	size_t			 resource_fork_allocated_size;
290	unsigned int		 decmpfs_block_count;
291	uint32_t		*decmpfs_block_info;
292	/* Buffer for compressed data. */
293	unsigned char		*compressed_buffer;
294	size_t			 compressed_buffer_size;
295	size_t			 compressed_buffer_remaining;
296	/* The offset of the ResourceFork where compressed data will
297	 * be placed. */
298	uint32_t		 compressed_rsrc_position;
299	uint32_t		 compressed_rsrc_position_v;
300	/* Buffer for uncompressed data. */
301	char			*uncompressed_buffer;
302	size_t			 block_remaining_bytes;
303	size_t			 file_remaining_bytes;
304#ifdef HAVE_ZLIB_H
305	z_stream		 stream;
306	int			 stream_valid;
307	int			 decmpfs_compression_level;
308#endif
309};
310
311/*
312 * Default mode for dirs created automatically (will be modified by umask).
313 * Note that POSIX specifies 0777 for implicitly-created dirs, "modified
314 * by the process' file creation mask."
315 */
316#define	DEFAULT_DIR_MODE 0777
317/*
318 * Dir modes are restored in two steps:  During the extraction, the permissions
319 * in the archive are modified to match the following limits.  During
320 * the post-extract fixup pass, the permissions from the archive are
321 * applied.
322 */
323#define	MINIMUM_DIR_MODE 0700
324#define	MAXIMUM_DIR_MODE 0775
325
326/*
327 * Maximum uncompressed size of a decmpfs block.
328 */
329#define MAX_DECMPFS_BLOCK_SIZE	(64 * 1024)
330/*
331 * HFS+ compression type.
332 */
333#define CMP_XATTR		3/* Compressed data in xattr. */
334#define CMP_RESOURCE_FORK	4/* Compressed data in resource fork. */
335/*
336 * HFS+ compression resource fork.
337 */
338#define RSRC_H_SIZE	260	/* Base size of Resource fork header. */
339#define RSRC_F_SIZE	50	/* Size of Resource fork footer. */
340/* Size to write compressed data to resource fork. */
341#define COMPRESSED_W_SIZE	(64 * 1024)
342/* decmpfs definitions. */
343#define MAX_DECMPFS_XATTR_SIZE		3802
344#ifndef DECMPFS_XATTR_NAME
345#define DECMPFS_XATTR_NAME		"com.apple.decmpfs"
346#endif
347#define DECMPFS_MAGIC			0x636d7066
348#define DECMPFS_COMPRESSION_MAGIC	0
349#define DECMPFS_COMPRESSION_TYPE	4
350#define DECMPFS_UNCOMPRESSED_SIZE	8
351#define DECMPFS_HEADER_SIZE		16
352
353#define HFS_BLOCKS(s)	((s) >> 12)
354
355
356static int	la_opendirat(int, const char *);
357static void	fsobj_error(int *, struct archive_string *, int, const char *,
358		    const char *);
359static int	check_symlinks_fsobj(char *, int *, struct archive_string *,
360		    int);
361static int	check_symlinks(struct archive_write_disk *);
362static int	create_filesystem_object(struct archive_write_disk *);
363static struct fixup_entry *current_fixup(struct archive_write_disk *,
364		    const char *pathname);
365#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
366static void	edit_deep_directories(struct archive_write_disk *ad);
367#endif
368static int	cleanup_pathname_fsobj(char *, int *, struct archive_string *,
369		    int);
370static int	cleanup_pathname(struct archive_write_disk *);
371static int	create_dir(struct archive_write_disk *, char *);
372static int	create_parent_dir(struct archive_write_disk *, char *);
373static ssize_t	hfs_write_data_block(struct archive_write_disk *,
374		    const char *, size_t);
375static int	fixup_appledouble(struct archive_write_disk *, const char *);
376static int	older(struct stat *, struct archive_entry *);
377static int	restore_entry(struct archive_write_disk *);
378static int	set_mac_metadata(struct archive_write_disk *, const char *,
379				 const void *, size_t);
380static int	set_xattrs(struct archive_write_disk *);
381static int	clear_nochange_fflags(struct archive_write_disk *);
382static int	set_fflags(struct archive_write_disk *);
383static int	set_fflags_platform(struct archive_write_disk *, int fd,
384		    const char *name, mode_t mode,
385		    unsigned long fflags_set, unsigned long fflags_clear);
386static int	set_ownership(struct archive_write_disk *);
387static int	set_mode(struct archive_write_disk *, int mode);
388static int	set_time(int, int, const char *, time_t, long, time_t, long);
389static int	set_times(struct archive_write_disk *, int, int, const char *,
390		    time_t, long, time_t, long, time_t, long, time_t, long);
391static int	set_times_from_entry(struct archive_write_disk *);
392static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
393static ssize_t	write_data_block(struct archive_write_disk *,
394		    const char *, size_t);
395
396static struct archive_vtable *archive_write_disk_vtable(void);
397
398static int	_archive_write_disk_close(struct archive *);
399static int	_archive_write_disk_free(struct archive *);
400static int	_archive_write_disk_header(struct archive *,
401		    struct archive_entry *);
402static int64_t	_archive_write_disk_filter_bytes(struct archive *, int);
403static int	_archive_write_disk_finish_entry(struct archive *);
404static ssize_t	_archive_write_disk_data(struct archive *, const void *,
405		    size_t);
406static ssize_t	_archive_write_disk_data_block(struct archive *, const void *,
407		    size_t, int64_t);
408
409static int
410la_opendirat(int fd, const char *path) {
411	const int flags = O_CLOEXEC
412#if defined(O_BINARY)
413	    | O_BINARY
414#endif
415#if defined(O_DIRECTORY)
416	    | O_DIRECTORY
417#endif
418#if defined(O_PATH)
419	    | O_PATH
420#elif defined(O_SEARCH)
421	    | O_SEARCH
422#elif defined(O_EXEC)
423	    | O_EXEC
424#else
425	    | O_RDONLY
426#endif
427	    ;
428
429#if !defined(HAVE_OPENAT)
430	if (fd != AT_FDCWD) {
431		errno = ENOTSUP;
432		return (-1);
433	} else
434		return (open(path, flags));
435#else
436	return (openat(fd, path, flags));
437#endif
438}
439
440static int
441lazy_stat(struct archive_write_disk *a)
442{
443	if (a->pst != NULL) {
444		/* Already have stat() data available. */
445		return (ARCHIVE_OK);
446	}
447#ifdef HAVE_FSTAT
448	if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
449		a->pst = &a->st;
450		return (ARCHIVE_OK);
451	}
452#endif
453	/*
454	 * XXX At this point, symlinks should not be hit, otherwise
455	 * XXX a race occurred.  Do we want to check explicitly for that?
456	 */
457	if (lstat(a->name, &a->st) == 0) {
458		a->pst = &a->st;
459		return (ARCHIVE_OK);
460	}
461	archive_set_error(&a->archive, errno, "Couldn't stat file");
462	return (ARCHIVE_WARN);
463}
464
465static struct archive_vtable *
466archive_write_disk_vtable(void)
467{
468	static struct archive_vtable av;
469	static int inited = 0;
470
471	if (!inited) {
472		av.archive_close = _archive_write_disk_close;
473		av.archive_filter_bytes = _archive_write_disk_filter_bytes;
474		av.archive_free = _archive_write_disk_free;
475		av.archive_write_header = _archive_write_disk_header;
476		av.archive_write_finish_entry
477		    = _archive_write_disk_finish_entry;
478		av.archive_write_data = _archive_write_disk_data;
479		av.archive_write_data_block = _archive_write_disk_data_block;
480		inited = 1;
481	}
482	return (&av);
483}
484
485static int64_t
486_archive_write_disk_filter_bytes(struct archive *_a, int n)
487{
488	struct archive_write_disk *a = (struct archive_write_disk *)_a;
489	(void)n; /* UNUSED */
490	if (n == -1 || n == 0)
491		return (a->total_bytes_written);
492	return (-1);
493}
494
495
496int
497archive_write_disk_set_options(struct archive *_a, int flags)
498{
499	struct archive_write_disk *a = (struct archive_write_disk *)_a;
500
501	a->flags = flags;
502	return (ARCHIVE_OK);
503}
504
505
506/*
507 * Extract this entry to disk.
508 *
509 * TODO: Validate hardlinks.  According to the standards, we're
510 * supposed to check each extracted hardlink and squawk if it refers
511 * to a file that we didn't restore.  I'm not entirely convinced this
512 * is a good idea, but more importantly: Is there any way to validate
513 * hardlinks without keeping a complete list of filenames from the
514 * entire archive?? Ugh.
515 *
516 */
517static int
518_archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
519{
520	struct archive_write_disk *a = (struct archive_write_disk *)_a;
521	struct fixup_entry *fe;
522	int ret, r;
523
524	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
525	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
526	    "archive_write_disk_header");
527	archive_clear_error(&a->archive);
528	if (a->archive.state & ARCHIVE_STATE_DATA) {
529		r = _archive_write_disk_finish_entry(&a->archive);
530		if (r == ARCHIVE_FATAL)
531			return (r);
532	}
533
534	/* Set up for this particular entry. */
535	a->pst = NULL;
536	a->current_fixup = NULL;
537	a->deferred = 0;
538	if (a->entry) {
539		archive_entry_free(a->entry);
540		a->entry = NULL;
541	}
542	a->entry = archive_entry_clone(entry);
543	a->fd = -1;
544	a->fd_offset = 0;
545	a->offset = 0;
546	a->restore_pwd = -1;
547	a->uid = a->user_uid;
548	a->mode = archive_entry_mode(a->entry);
549	if (archive_entry_size_is_set(a->entry))
550		a->filesize = archive_entry_size(a->entry);
551	else
552		a->filesize = -1;
553	archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
554	a->name = a->_name_data.s;
555	archive_clear_error(&a->archive);
556
557	/*
558	 * Clean up the requested path.  This is necessary for correct
559	 * dir restores; the dir restore logic otherwise gets messed
560	 * up by nonsense like "dir/.".
561	 */
562	ret = cleanup_pathname(a);
563	if (ret != ARCHIVE_OK)
564		return (ret);
565
566	/*
567	 * Query the umask so we get predictable mode settings.
568	 * This gets done on every call to _write_header in case the
569	 * user edits their umask during the extraction for some
570	 * reason.
571	 */
572	umask(a->user_umask = umask(0));
573
574	/* Figure out what we need to do for this entry. */
575	a->todo = TODO_MODE_BASE;
576	if (a->flags & ARCHIVE_EXTRACT_PERM) {
577		a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
578		/*
579		 * SGID requires an extra "check" step because we
580		 * cannot easily predict the GID that the system will
581		 * assign.  (Different systems assign GIDs to files
582		 * based on a variety of criteria, including process
583		 * credentials and the gid of the enclosing
584		 * directory.)  We can only restore the SGID bit if
585		 * the file has the right GID, and we only know the
586		 * GID if we either set it (see set_ownership) or if
587		 * we've actually called stat() on the file after it
588		 * was restored.  Since there are several places at
589		 * which we might verify the GID, we need a TODO bit
590		 * to keep track.
591		 */
592		if (a->mode & S_ISGID)
593			a->todo |= TODO_SGID | TODO_SGID_CHECK;
594		/*
595		 * Verifying the SUID is simpler, but can still be
596		 * done in multiple ways, hence the separate "check" bit.
597		 */
598		if (a->mode & S_ISUID)
599			a->todo |= TODO_SUID | TODO_SUID_CHECK;
600	} else {
601		/*
602		 * User didn't request full permissions, so don't
603		 * restore SUID, SGID bits and obey umask.
604		 */
605		a->mode &= ~S_ISUID;
606		a->mode &= ~S_ISGID;
607		a->mode &= ~S_ISVTX;
608		a->mode &= ~a->user_umask;
609	}
610	if (a->flags & ARCHIVE_EXTRACT_OWNER)
611		a->todo |= TODO_OWNER;
612	if (a->flags & ARCHIVE_EXTRACT_TIME)
613		a->todo |= TODO_TIMES;
614	if (a->flags & ARCHIVE_EXTRACT_ACL) {
615#if ARCHIVE_ACL_DARWIN
616		/*
617		 * On MacOS, platform ACLs get stored in mac_metadata, too.
618		 * If we intend to extract mac_metadata and it is present
619		 * we skip extracting libarchive NFSv4 ACLs.
620		 */
621		size_t metadata_size;
622
623		if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
624		    archive_entry_mac_metadata(a->entry,
625		    &metadata_size) == NULL || metadata_size == 0)
626#endif
627#if ARCHIVE_ACL_LIBRICHACL
628		/*
629		 * RichACLs are stored in an extended attribute.
630		 * If we intend to extract extended attributes and have this
631		 * attribute we skip extracting libarchive NFSv4 ACLs.
632		 */
633		short extract_acls = 1;
634		if (a->flags & ARCHIVE_EXTRACT_XATTR && (
635		    archive_entry_acl_types(a->entry) &
636		    ARCHIVE_ENTRY_ACL_TYPE_NFS4)) {
637			const char *attr_name;
638			const void *attr_value;
639			size_t attr_size;
640			int i = archive_entry_xattr_reset(a->entry);
641			while (i--) {
642				archive_entry_xattr_next(a->entry, &attr_name,
643				    &attr_value, &attr_size);
644				if (attr_name != NULL && attr_value != NULL &&
645				    attr_size > 0 && strcmp(attr_name,
646				    "trusted.richacl") == 0) {
647					extract_acls = 0;
648					break;
649				}
650			}
651		}
652		if (extract_acls)
653#endif
654#if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
655		{
656#endif
657		if (archive_entry_filetype(a->entry) == AE_IFDIR)
658			a->deferred |= TODO_ACLS;
659		else
660			a->todo |= TODO_ACLS;
661#if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
662		}
663#endif
664	}
665	if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
666		if (archive_entry_filetype(a->entry) == AE_IFDIR)
667			a->deferred |= TODO_MAC_METADATA;
668		else
669			a->todo |= TODO_MAC_METADATA;
670	}
671#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
672	if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) {
673		unsigned long set, clear;
674		archive_entry_fflags(a->entry, &set, &clear);
675		if ((set & ~clear) & UF_COMPRESSED) {
676			a->todo |= TODO_HFS_COMPRESSION;
677			a->decmpfs_block_count = (unsigned)-1;
678		}
679	}
680	if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 &&
681	    (a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) {
682		a->todo |= TODO_HFS_COMPRESSION;
683		a->decmpfs_block_count = (unsigned)-1;
684	}
685	{
686		const char *p;
687
688		/* Check if the current file name is a type of the
689		 * resource fork file. */
690		p = strrchr(a->name, '/');
691		if (p == NULL)
692			p = a->name;
693		else
694			p++;
695		if (p[0] == '.' && p[1] == '_') {
696			/* Do not compress "._XXX" files. */
697			a->todo &= ~TODO_HFS_COMPRESSION;
698			if (a->filesize > 0)
699				a->todo |= TODO_APPLEDOUBLE;
700		}
701	}
702#endif
703
704	if (a->flags & ARCHIVE_EXTRACT_XATTR) {
705#if ARCHIVE_XATTR_DARWIN
706		/*
707		 * On MacOS, extended attributes get stored in mac_metadata,
708		 * too. If we intend to extract mac_metadata and it is present
709		 * we skip extracting extended attributes.
710		 */
711		size_t metadata_size;
712
713		if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
714		    archive_entry_mac_metadata(a->entry,
715		    &metadata_size) == NULL || metadata_size == 0)
716#endif
717		a->todo |= TODO_XATTR;
718	}
719	if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
720		a->todo |= TODO_FFLAGS;
721	if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
722		ret = check_symlinks(a);
723		if (ret != ARCHIVE_OK)
724			return (ret);
725	}
726#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
727	/* If path exceeds PATH_MAX, shorten the path. */
728	edit_deep_directories(a);
729#endif
730
731	ret = restore_entry(a);
732
733#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
734	/*
735	 * Check if the filesystem the file is restoring on supports
736	 * HFS+ Compression. If not, cancel HFS+ Compression.
737	 */
738	if (a->todo | TODO_HFS_COMPRESSION) {
739		/*
740		 * NOTE: UF_COMPRESSED is ignored even if the filesystem
741		 * supports HFS+ Compression because the file should
742		 * have at least an extended attribute "com.apple.decmpfs"
743		 * before the flag is set to indicate that the file have
744		 * been compressed. If the filesystem does not support
745		 * HFS+ Compression the system call will fail.
746		 */
747		if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
748			a->todo &= ~TODO_HFS_COMPRESSION;
749	}
750#endif
751
752	/*
753	 * TODO: There are rumours that some extended attributes must
754	 * be restored before file data is written.  If this is true,
755	 * then we either need to write all extended attributes both
756	 * before and after restoring the data, or find some rule for
757	 * determining which must go first and which last.  Due to the
758	 * many ways people are using xattrs, this may prove to be an
759	 * intractable problem.
760	 */
761
762#ifdef HAVE_FCHDIR
763	/* If we changed directory above, restore it here. */
764	if (a->restore_pwd >= 0) {
765		r = fchdir(a->restore_pwd);
766		if (r != 0) {
767			archive_set_error(&a->archive, errno,
768			    "chdir() failure");
769			ret = ARCHIVE_FATAL;
770		}
771		close(a->restore_pwd);
772		a->restore_pwd = -1;
773	}
774#endif
775
776	/*
777	 * Fixup uses the unedited pathname from archive_entry_pathname(),
778	 * because it is relative to the base dir and the edited path
779	 * might be relative to some intermediate dir as a result of the
780	 * deep restore logic.
781	 */
782	if (a->deferred & TODO_MODE) {
783		fe = current_fixup(a, archive_entry_pathname(entry));
784		if (fe == NULL)
785			return (ARCHIVE_FATAL);
786		fe->fixup |= TODO_MODE_BASE;
787		fe->mode = a->mode;
788	}
789
790	if ((a->deferred & TODO_TIMES)
791		&& (archive_entry_mtime_is_set(entry)
792		    || archive_entry_atime_is_set(entry))) {
793		fe = current_fixup(a, archive_entry_pathname(entry));
794		if (fe == NULL)
795			return (ARCHIVE_FATAL);
796		fe->mode = a->mode;
797		fe->fixup |= TODO_TIMES;
798		if (archive_entry_atime_is_set(entry)) {
799			fe->atime = archive_entry_atime(entry);
800			fe->atime_nanos = archive_entry_atime_nsec(entry);
801		} else {
802			/* If atime is unset, use start time. */
803			fe->atime = a->start_time;
804			fe->atime_nanos = 0;
805		}
806		if (archive_entry_mtime_is_set(entry)) {
807			fe->mtime = archive_entry_mtime(entry);
808			fe->mtime_nanos = archive_entry_mtime_nsec(entry);
809		} else {
810			/* If mtime is unset, use start time. */
811			fe->mtime = a->start_time;
812			fe->mtime_nanos = 0;
813		}
814		if (archive_entry_birthtime_is_set(entry)) {
815			fe->birthtime = archive_entry_birthtime(entry);
816			fe->birthtime_nanos = archive_entry_birthtime_nsec(
817			    entry);
818		} else {
819			/* If birthtime is unset, use mtime. */
820			fe->birthtime = fe->mtime;
821			fe->birthtime_nanos = fe->mtime_nanos;
822		}
823	}
824
825	if (a->deferred & TODO_ACLS) {
826		fe = current_fixup(a, archive_entry_pathname(entry));
827		if (fe == NULL)
828			return (ARCHIVE_FATAL);
829		fe->fixup |= TODO_ACLS;
830		archive_acl_copy(&fe->acl, archive_entry_acl(entry));
831	}
832
833	if (a->deferred & TODO_MAC_METADATA) {
834		const void *metadata;
835		size_t metadata_size;
836		metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
837		if (metadata != NULL && metadata_size > 0) {
838			fe = current_fixup(a, archive_entry_pathname(entry));
839			if (fe == NULL)
840				return (ARCHIVE_FATAL);
841			fe->mac_metadata = malloc(metadata_size);
842			if (fe->mac_metadata != NULL) {
843				memcpy(fe->mac_metadata, metadata,
844				    metadata_size);
845				fe->mac_metadata_size = metadata_size;
846				fe->fixup |= TODO_MAC_METADATA;
847			}
848		}
849	}
850
851	if (a->deferred & TODO_FFLAGS) {
852		fe = current_fixup(a, archive_entry_pathname(entry));
853		if (fe == NULL)
854			return (ARCHIVE_FATAL);
855		fe->fixup |= TODO_FFLAGS;
856		/* TODO: Complete this.. defer fflags from below. */
857	}
858
859	/* We've created the object and are ready to pour data into it. */
860	if (ret >= ARCHIVE_WARN)
861		a->archive.state = ARCHIVE_STATE_DATA;
862	/*
863	 * If it's not open, tell our client not to try writing.
864	 * In particular, dirs, links, etc, don't get written to.
865	 */
866	if (a->fd < 0) {
867		archive_entry_set_size(entry, 0);
868		a->filesize = 0;
869	}
870
871	return (ret);
872}
873
874int
875archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i)
876{
877	struct archive_write_disk *a = (struct archive_write_disk *)_a;
878	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
879	    ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
880	a->skip_file_set = 1;
881	a->skip_file_dev = d;
882	a->skip_file_ino = i;
883	return (ARCHIVE_OK);
884}
885
886static ssize_t
887write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
888{
889	uint64_t start_size = size;
890	ssize_t bytes_written = 0;
891	ssize_t block_size = 0, bytes_to_write;
892
893	if (size == 0)
894		return (ARCHIVE_OK);
895
896	if (a->filesize == 0 || a->fd < 0) {
897		archive_set_error(&a->archive, 0,
898		    "Attempt to write to an empty file");
899		return (ARCHIVE_WARN);
900	}
901
902	if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
903#if HAVE_STRUCT_STAT_ST_BLKSIZE
904		int r;
905		if ((r = lazy_stat(a)) != ARCHIVE_OK)
906			return (r);
907		block_size = a->pst->st_blksize;
908#else
909		/* XXX TODO XXX Is there a more appropriate choice here ? */
910		/* This needn't match the filesystem allocation size. */
911		block_size = 16*1024;
912#endif
913	}
914
915	/* If this write would run beyond the file size, truncate it. */
916	if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
917		start_size = size = (size_t)(a->filesize - a->offset);
918
919	/* Write the data. */
920	while (size > 0) {
921		if (block_size == 0) {
922			bytes_to_write = size;
923		} else {
924			/* We're sparsifying the file. */
925			const char *p, *end;
926			int64_t block_end;
927
928			/* Skip leading zero bytes. */
929			for (p = buff, end = buff + size; p < end; ++p) {
930				if (*p != '\0')
931					break;
932			}
933			a->offset += p - buff;
934			size -= p - buff;
935			buff = p;
936			if (size == 0)
937				break;
938
939			/* Calculate next block boundary after offset. */
940			block_end
941			    = (a->offset / block_size + 1) * block_size;
942
943			/* If the adjusted write would cross block boundary,
944			 * truncate it to the block boundary. */
945			bytes_to_write = size;
946			if (a->offset + bytes_to_write > block_end)
947				bytes_to_write = block_end - a->offset;
948		}
949		/* Seek if necessary to the specified offset. */
950		if (a->offset != a->fd_offset) {
951			if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
952				archive_set_error(&a->archive, errno,
953				    "Seek failed");
954				return (ARCHIVE_FATAL);
955			}
956			a->fd_offset = a->offset;
957		}
958		bytes_written = write(a->fd, buff, bytes_to_write);
959		if (bytes_written < 0) {
960			archive_set_error(&a->archive, errno, "Write failed");
961			return (ARCHIVE_WARN);
962		}
963		buff += bytes_written;
964		size -= bytes_written;
965		a->total_bytes_written += bytes_written;
966		a->offset += bytes_written;
967		a->fd_offset = a->offset;
968	}
969	return (start_size - size);
970}
971
972#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
973	&& defined(HAVE_ZLIB_H)
974
975/*
976 * Set UF_COMPRESSED file flag.
977 * This have to be called after hfs_write_decmpfs() because if the
978 * file does not have "com.apple.decmpfs" xattr the flag is ignored.
979 */
980static int
981hfs_set_compressed_fflag(struct archive_write_disk *a)
982{
983	int r;
984
985	if ((r = lazy_stat(a)) != ARCHIVE_OK)
986		return (r);
987
988	a->st.st_flags |= UF_COMPRESSED;
989	if (fchflags(a->fd, a->st.st_flags) != 0) {
990		archive_set_error(&a->archive, errno,
991		    "Failed to set UF_COMPRESSED file flag");
992		return (ARCHIVE_WARN);
993	}
994	return (ARCHIVE_OK);
995}
996
997/*
998 * HFS+ Compression decmpfs
999 *
1000 *     +------------------------------+ +0
1001 *     |      Magic(LE 4 bytes)       |
1002 *     +------------------------------+
1003 *     |      Type(LE 4 bytes)        |
1004 *     +------------------------------+
1005 *     | Uncompressed size(LE 8 bytes)|
1006 *     +------------------------------+ +16
1007 *     |                              |
1008 *     |       Compressed data        |
1009 *     |  (Placed only if Type == 3)  |
1010 *     |                              |
1011 *     +------------------------------+  +3802 = MAX_DECMPFS_XATTR_SIZE
1012 *
1013 *  Type is 3: decmpfs has compressed data.
1014 *  Type is 4: Resource Fork has compressed data.
1015 */
1016/*
1017 * Write "com.apple.decmpfs"
1018 */
1019static int
1020hfs_write_decmpfs(struct archive_write_disk *a)
1021{
1022	int r;
1023	uint32_t compression_type;
1024
1025	r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
1026	    a->decmpfs_attr_size, 0, 0);
1027	if (r < 0) {
1028		archive_set_error(&a->archive, errno,
1029		    "Cannot restore xattr:%s", DECMPFS_XATTR_NAME);
1030		compression_type = archive_le32dec(
1031		    &a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]);
1032		if (compression_type == CMP_RESOURCE_FORK)
1033			fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME,
1034			    XATTR_SHOWCOMPRESSION);
1035		return (ARCHIVE_WARN);
1036	}
1037	return (ARCHIVE_OK);
1038}
1039
1040/*
1041 * HFS+ Compression Resource Fork
1042 *
1043 *     +-----------------------------+
1044 *     |     Header(260 bytes)       |
1045 *     +-----------------------------+
1046 *     |   Block count(LE 4 bytes)   |
1047 *     +-----------------------------+  --+
1048 * +-- |     Offset (LE 4 bytes)     |    |
1049 * |   | [distance from Block count] |    | Block 0
1050 * |   +-----------------------------+    |
1051 * |   | Compressed size(LE 4 bytes) |    |
1052 * |   +-----------------------------+  --+
1053 * |   |                             |
1054 * |   |      ..................     |
1055 * |   |                             |
1056 * |   +-----------------------------+  --+
1057 * |   |     Offset (LE 4 bytes)     |    |
1058 * |   +-----------------------------+    | Block (Block count -1)
1059 * |   | Compressed size(LE 4 bytes) |    |
1060 * +-> +-----------------------------+  --+
1061 *     |   Compressed data(n bytes)  |  Block 0
1062 *     +-----------------------------+
1063 *     |                             |
1064 *     |      ..................     |
1065 *     |                             |
1066 *     +-----------------------------+
1067 *     |   Compressed data(n bytes)  |  Block (Block count -1)
1068 *     +-----------------------------+
1069 *     |      Footer(50 bytes)       |
1070 *     +-----------------------------+
1071 *
1072 */
1073/*
1074 * Write the header of "com.apple.ResourceFork"
1075 */
1076static int
1077hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
1078    size_t bytes, uint32_t position)
1079{
1080	int ret;
1081
1082	ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
1083	    position, a->rsrc_xattr_options);
1084	if (ret < 0) {
1085		archive_set_error(&a->archive, errno,
1086		    "Cannot restore xattr: %s at %u pos %u bytes",
1087		    XATTR_RESOURCEFORK_NAME,
1088		    (unsigned)position,
1089		    (unsigned)bytes);
1090		return (ARCHIVE_WARN);
1091	}
1092	a->rsrc_xattr_options &= ~XATTR_CREATE;
1093	return (ARCHIVE_OK);
1094}
1095
1096static int
1097hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
1098{
1099	int ret;
1100
1101	ret = hfs_write_resource_fork(a, a->compressed_buffer,
1102	    bytes_compressed, a->compressed_rsrc_position);
1103	if (ret == ARCHIVE_OK)
1104		a->compressed_rsrc_position += bytes_compressed;
1105	return (ret);
1106}
1107
1108static int
1109hfs_write_resource_fork_header(struct archive_write_disk *a)
1110{
1111	unsigned char *buff;
1112	uint32_t rsrc_bytes;
1113	uint32_t rsrc_header_bytes;
1114
1115	/*
1116	 * Write resource fork header + block info.
1117	 */
1118	buff = a->resource_fork;
1119	rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
1120	rsrc_header_bytes =
1121		RSRC_H_SIZE +		/* Header base size. */
1122		4 +			/* Block count. */
1123		(a->decmpfs_block_count * 8);/* Block info */
1124	archive_be32enc(buff, 0x100);
1125	archive_be32enc(buff + 4, rsrc_bytes);
1126	archive_be32enc(buff + 8, rsrc_bytes - 256);
1127	archive_be32enc(buff + 12, 0x32);
1128	memset(buff + 16, 0, 240);
1129	archive_be32enc(buff + 256, rsrc_bytes - 260);
1130	return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0);
1131}
1132
1133static size_t
1134hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
1135{
1136	static const char rsrc_footer[RSRC_F_SIZE] = {
1137		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1138		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1139		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1140		0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c',  'm',
1141		'p', 'f',   0x00, 0x00, 0x00, 0x0a, 0x00, 0x01,
1142		0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1143		0x00, 0x00
1144	};
1145	if (buff_size < sizeof(rsrc_footer))
1146		return (0);
1147	memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
1148	return (sizeof(rsrc_footer));
1149}
1150
1151static int
1152hfs_reset_compressor(struct archive_write_disk *a)
1153{
1154	int ret;
1155
1156	if (a->stream_valid)
1157		ret = deflateReset(&a->stream);
1158	else
1159		ret = deflateInit(&a->stream, a->decmpfs_compression_level);
1160
1161	if (ret != Z_OK) {
1162		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1163		    "Failed to initialize compressor");
1164		return (ARCHIVE_FATAL);
1165	} else
1166		a->stream_valid = 1;
1167
1168	return (ARCHIVE_OK);
1169}
1170
1171static int
1172hfs_decompress(struct archive_write_disk *a)
1173{
1174	uint32_t *block_info;
1175	unsigned int block_count;
1176	uint32_t data_pos, data_size;
1177	ssize_t r;
1178	ssize_t bytes_written, bytes_to_write;
1179	unsigned char *b;
1180
1181	block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1182	block_count = archive_le32dec(block_info++);
1183	while (block_count--) {
1184		data_pos = RSRC_H_SIZE + archive_le32dec(block_info++);
1185		data_size = archive_le32dec(block_info++);
1186		r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME,
1187		    a->compressed_buffer, data_size, data_pos, 0);
1188		if (r != data_size)  {
1189			archive_set_error(&a->archive,
1190			    (r < 0)?errno:ARCHIVE_ERRNO_MISC,
1191			    "Failed to read resource fork");
1192			return (ARCHIVE_WARN);
1193		}
1194		if (a->compressed_buffer[0] == 0xff) {
1195			bytes_to_write = data_size -1;
1196			b = a->compressed_buffer + 1;
1197		} else {
1198			uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
1199			int zr;
1200
1201			zr = uncompress((Bytef *)a->uncompressed_buffer,
1202			    &dest_len, a->compressed_buffer, data_size);
1203			if (zr != Z_OK) {
1204				archive_set_error(&a->archive,
1205				    ARCHIVE_ERRNO_MISC,
1206				    "Failed to decompress resource fork");
1207				return (ARCHIVE_WARN);
1208			}
1209			bytes_to_write = dest_len;
1210			b = (unsigned char *)a->uncompressed_buffer;
1211		}
1212		do {
1213			bytes_written = write(a->fd, b, bytes_to_write);
1214			if (bytes_written < 0) {
1215				archive_set_error(&a->archive, errno,
1216				    "Write failed");
1217				return (ARCHIVE_WARN);
1218			}
1219			bytes_to_write -= bytes_written;
1220			b += bytes_written;
1221		} while (bytes_to_write > 0);
1222	}
1223	r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
1224	if (r == -1)  {
1225		archive_set_error(&a->archive, errno,
1226		    "Failed to remove resource fork");
1227		return (ARCHIVE_WARN);
1228	}
1229	return (ARCHIVE_OK);
1230}
1231
1232static int
1233hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
1234    size_t size)
1235{
1236	unsigned char *buffer_compressed;
1237	size_t bytes_compressed;
1238	size_t bytes_used;
1239	int ret;
1240
1241	ret = hfs_reset_compressor(a);
1242	if (ret != ARCHIVE_OK)
1243		return (ret);
1244
1245	if (a->compressed_buffer == NULL) {
1246		size_t block_size;
1247
1248		block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
1249		    + compressBound(MAX_DECMPFS_BLOCK_SIZE);
1250		a->compressed_buffer = malloc(block_size);
1251		if (a->compressed_buffer == NULL) {
1252			archive_set_error(&a->archive, ENOMEM,
1253			    "Can't allocate memory for Resource Fork");
1254			return (ARCHIVE_FATAL);
1255		}
1256		a->compressed_buffer_size = block_size;
1257		a->compressed_buffer_remaining = block_size;
1258	}
1259
1260	buffer_compressed = a->compressed_buffer +
1261	    a->compressed_buffer_size - a->compressed_buffer_remaining;
1262	a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
1263	a->stream.avail_in = size;
1264	a->stream.next_out = buffer_compressed;
1265	a->stream.avail_out = a->compressed_buffer_remaining;
1266	do {
1267		ret = deflate(&a->stream, Z_FINISH);
1268		switch (ret) {
1269		case Z_OK:
1270		case Z_STREAM_END:
1271			break;
1272		default:
1273			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1274			    "Failed to compress data");
1275			return (ARCHIVE_FAILED);
1276		}
1277	} while (ret == Z_OK);
1278	bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
1279
1280	/*
1281	 * If the compressed size is larger than the original size,
1282	 * throw away compressed data, use uncompressed data instead.
1283	 */
1284	if (bytes_compressed > size) {
1285		buffer_compressed[0] = 0xFF;/* uncompressed marker. */
1286		memcpy(buffer_compressed + 1, buff, size);
1287		bytes_compressed = size + 1;
1288	}
1289	a->compressed_buffer_remaining -= bytes_compressed;
1290
1291	/*
1292	 * If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
1293	 * and the block count in the file is only one, store compressed
1294	 * data to decmpfs xattr instead of the resource fork.
1295	 */
1296	if (a->decmpfs_block_count == 1 &&
1297	    (a->decmpfs_attr_size + bytes_compressed)
1298	      <= MAX_DECMPFS_XATTR_SIZE) {
1299		archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1300		    CMP_XATTR);
1301		memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
1302		    buffer_compressed, bytes_compressed);
1303		a->decmpfs_attr_size += bytes_compressed;
1304		a->compressed_buffer_remaining = a->compressed_buffer_size;
1305		/*
1306		 * Finish HFS+ Compression.
1307		 * - Write the decmpfs xattr.
1308		 * - Set the UF_COMPRESSED file flag.
1309		 */
1310		ret = hfs_write_decmpfs(a);
1311		if (ret == ARCHIVE_OK)
1312			ret = hfs_set_compressed_fflag(a);
1313		return (ret);
1314	}
1315
1316	/* Update block info. */
1317	archive_le32enc(a->decmpfs_block_info++,
1318	    a->compressed_rsrc_position_v - RSRC_H_SIZE);
1319	archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
1320	a->compressed_rsrc_position_v += bytes_compressed;
1321
1322	/*
1323	 * Write the compressed data to the resource fork.
1324	 */
1325	bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
1326	while (bytes_used >= COMPRESSED_W_SIZE) {
1327		ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
1328		if (ret != ARCHIVE_OK)
1329			return (ret);
1330		bytes_used -= COMPRESSED_W_SIZE;
1331		if (bytes_used > COMPRESSED_W_SIZE)
1332			memmove(a->compressed_buffer,
1333			    a->compressed_buffer + COMPRESSED_W_SIZE,
1334			    bytes_used);
1335		else
1336			memcpy(a->compressed_buffer,
1337			    a->compressed_buffer + COMPRESSED_W_SIZE,
1338			    bytes_used);
1339	}
1340	a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
1341
1342	/*
1343	 * If the current block is the last block, write the remaining
1344	 * compressed data and the resource fork footer.
1345	 */
1346	if (a->file_remaining_bytes == 0) {
1347		size_t rsrc_size;
1348		int64_t bk;
1349
1350		/* Append the resource footer. */
1351		rsrc_size = hfs_set_resource_fork_footer(
1352		    a->compressed_buffer + bytes_used,
1353		    a->compressed_buffer_remaining);
1354		ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
1355		a->compressed_buffer_remaining = a->compressed_buffer_size;
1356
1357		/* If the compressed size is not enough smaller than
1358		 * the uncompressed size. cancel HFS+ compression.
1359		 * TODO: study a behavior of ditto utility and improve
1360		 * the condition to fall back into no HFS+ compression. */
1361		bk = HFS_BLOCKS(a->compressed_rsrc_position);
1362		bk += bk >> 7;
1363		if (bk > HFS_BLOCKS(a->filesize))
1364			return hfs_decompress(a);
1365		/*
1366		 * Write the resourcefork header.
1367		 */
1368		if (ret == ARCHIVE_OK)
1369			ret = hfs_write_resource_fork_header(a);
1370		/*
1371		 * Finish HFS+ Compression.
1372		 * - Write the decmpfs xattr.
1373		 * - Set the UF_COMPRESSED file flag.
1374		 */
1375		if (ret == ARCHIVE_OK)
1376			ret = hfs_write_decmpfs(a);
1377		if (ret == ARCHIVE_OK)
1378			ret = hfs_set_compressed_fflag(a);
1379	}
1380	return (ret);
1381}
1382
1383static ssize_t
1384hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
1385    size_t size)
1386{
1387	const char *buffer_to_write;
1388	size_t bytes_to_write;
1389	int ret;
1390
1391	if (a->decmpfs_block_count == (unsigned)-1) {
1392		void *new_block;
1393		size_t new_size;
1394		unsigned int block_count;
1395
1396		if (a->decmpfs_header_p == NULL) {
1397			new_block = malloc(MAX_DECMPFS_XATTR_SIZE
1398			    + sizeof(uint32_t));
1399			if (new_block == NULL) {
1400				archive_set_error(&a->archive, ENOMEM,
1401				    "Can't allocate memory for decmpfs");
1402				return (ARCHIVE_FATAL);
1403			}
1404			a->decmpfs_header_p = new_block;
1405		}
1406		a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
1407		archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
1408		    DECMPFS_MAGIC);
1409		archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1410		    CMP_RESOURCE_FORK);
1411		archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
1412		    a->filesize);
1413
1414		/* Calculate a block count of the file. */
1415		block_count =
1416		    (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
1417			MAX_DECMPFS_BLOCK_SIZE;
1418		/*
1419		 * Allocate buffer for resource fork.
1420		 * Set up related pointers;
1421		 */
1422		new_size =
1423		    RSRC_H_SIZE + /* header */
1424		    4 + /* Block count */
1425		    (block_count * sizeof(uint32_t) * 2) +
1426		    RSRC_F_SIZE; /* footer */
1427		if (new_size > a->resource_fork_allocated_size) {
1428			new_block = realloc(a->resource_fork, new_size);
1429			if (new_block == NULL) {
1430				archive_set_error(&a->archive, ENOMEM,
1431				    "Can't allocate memory for ResourceFork");
1432				return (ARCHIVE_FATAL);
1433			}
1434			a->resource_fork_allocated_size = new_size;
1435			a->resource_fork = new_block;
1436		}
1437
1438		/* Allocate uncompressed buffer */
1439		if (a->uncompressed_buffer == NULL) {
1440			new_block = malloc(MAX_DECMPFS_BLOCK_SIZE);
1441			if (new_block == NULL) {
1442				archive_set_error(&a->archive, ENOMEM,
1443				    "Can't allocate memory for decmpfs");
1444				return (ARCHIVE_FATAL);
1445			}
1446			a->uncompressed_buffer = new_block;
1447		}
1448		a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1449		a->file_remaining_bytes = a->filesize;
1450		a->compressed_buffer_remaining = a->compressed_buffer_size;
1451
1452		/*
1453		 * Set up a resource fork.
1454		 */
1455		a->rsrc_xattr_options = XATTR_CREATE;
1456		/* Get the position where we are going to set a bunch
1457		 * of block info. */
1458		a->decmpfs_block_info =
1459		    (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1460		/* Set the block count to the resource fork. */
1461		archive_le32enc(a->decmpfs_block_info++, block_count);
1462		/* Get the position where we are going to set compressed
1463		 * data. */
1464		a->compressed_rsrc_position =
1465		    RSRC_H_SIZE + 4 + (block_count * 8);
1466		a->compressed_rsrc_position_v = a->compressed_rsrc_position;
1467		a->decmpfs_block_count = block_count;
1468	}
1469
1470	/* Ignore redundant bytes. */
1471	if (a->file_remaining_bytes == 0)
1472		return ((ssize_t)size);
1473
1474	/* Do not overrun a block size. */
1475	if (size > a->block_remaining_bytes)
1476		bytes_to_write = a->block_remaining_bytes;
1477	else
1478		bytes_to_write = size;
1479	/* Do not overrun the file size. */
1480	if (bytes_to_write > a->file_remaining_bytes)
1481		bytes_to_write = a->file_remaining_bytes;
1482
1483	/* For efficiency, if a copy length is full of the uncompressed
1484	 * buffer size, do not copy writing data to it. */
1485	if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE)
1486		buffer_to_write = buff;
1487	else {
1488		memcpy(a->uncompressed_buffer +
1489		    MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes,
1490		    buff, bytes_to_write);
1491		buffer_to_write = a->uncompressed_buffer;
1492	}
1493	a->block_remaining_bytes -= bytes_to_write;
1494	a->file_remaining_bytes -= bytes_to_write;
1495
1496	if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) {
1497		ret = hfs_drive_compressor(a, buffer_to_write,
1498		    MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes);
1499		if (ret < 0)
1500			return (ret);
1501		a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1502	}
1503	/* Ignore redundant bytes. */
1504	if (a->file_remaining_bytes == 0)
1505		return ((ssize_t)size);
1506	return (bytes_to_write);
1507}
1508
1509static ssize_t
1510hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1511    size_t size)
1512{
1513	uint64_t start_size = size;
1514	ssize_t bytes_written = 0;
1515	ssize_t bytes_to_write;
1516
1517	if (size == 0)
1518		return (ARCHIVE_OK);
1519
1520	if (a->filesize == 0 || a->fd < 0) {
1521		archive_set_error(&a->archive, 0,
1522		    "Attempt to write to an empty file");
1523		return (ARCHIVE_WARN);
1524	}
1525
1526	/* If this write would run beyond the file size, truncate it. */
1527	if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
1528		start_size = size = (size_t)(a->filesize - a->offset);
1529
1530	/* Write the data. */
1531	while (size > 0) {
1532		bytes_to_write = size;
1533		/* Seek if necessary to the specified offset. */
1534		if (a->offset < a->fd_offset) {
1535			/* Can't support backward move. */
1536			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1537			    "Seek failed");
1538			return (ARCHIVE_FATAL);
1539		} else if (a->offset > a->fd_offset) {
1540			int64_t skip = a->offset - a->fd_offset;
1541			char nullblock[1024];
1542
1543			memset(nullblock, 0, sizeof(nullblock));
1544			while (skip > 0) {
1545				if (skip > (int64_t)sizeof(nullblock))
1546					bytes_written = hfs_write_decmpfs_block(
1547					    a, nullblock, sizeof(nullblock));
1548				else
1549					bytes_written = hfs_write_decmpfs_block(
1550					    a, nullblock, skip);
1551				if (bytes_written < 0) {
1552					archive_set_error(&a->archive, errno,
1553					    "Write failed");
1554					return (ARCHIVE_WARN);
1555				}
1556				skip -= bytes_written;
1557			}
1558
1559			a->fd_offset = a->offset;
1560		}
1561		bytes_written =
1562		    hfs_write_decmpfs_block(a, buff, bytes_to_write);
1563		if (bytes_written < 0)
1564			return (bytes_written);
1565		buff += bytes_written;
1566		size -= bytes_written;
1567		a->total_bytes_written += bytes_written;
1568		a->offset += bytes_written;
1569		a->fd_offset = a->offset;
1570	}
1571	return (start_size - size);
1572}
1573#else
1574static ssize_t
1575hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1576    size_t size)
1577{
1578	return (write_data_block(a, buff, size));
1579}
1580#endif
1581
1582static ssize_t
1583_archive_write_disk_data_block(struct archive *_a,
1584    const void *buff, size_t size, int64_t offset)
1585{
1586	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1587	ssize_t r;
1588
1589	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1590	    ARCHIVE_STATE_DATA, "archive_write_data_block");
1591
1592	a->offset = offset;
1593	if (a->todo & TODO_HFS_COMPRESSION)
1594		r = hfs_write_data_block(a, buff, size);
1595	else
1596		r = write_data_block(a, buff, size);
1597	if (r < ARCHIVE_OK)
1598		return (r);
1599	if ((size_t)r < size) {
1600		archive_set_error(&a->archive, 0,
1601		    "Too much data: Truncating file at %ju bytes",
1602		    (uintmax_t)a->filesize);
1603		return (ARCHIVE_WARN);
1604	}
1605#if ARCHIVE_VERSION_NUMBER < 3999000
1606	return (ARCHIVE_OK);
1607#else
1608	return (size);
1609#endif
1610}
1611
1612static ssize_t
1613_archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
1614{
1615	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1616
1617	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1618	    ARCHIVE_STATE_DATA, "archive_write_data");
1619
1620	if (a->todo & TODO_HFS_COMPRESSION)
1621		return (hfs_write_data_block(a, buff, size));
1622	return (write_data_block(a, buff, size));
1623}
1624
1625static int
1626_archive_write_disk_finish_entry(struct archive *_a)
1627{
1628	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1629	int ret = ARCHIVE_OK;
1630
1631	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1632	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1633	    "archive_write_finish_entry");
1634	if (a->archive.state & ARCHIVE_STATE_HEADER)
1635		return (ARCHIVE_OK);
1636	archive_clear_error(&a->archive);
1637
1638	/* Pad or truncate file to the right size. */
1639	if (a->fd < 0) {
1640		/* There's no file. */
1641	} else if (a->filesize < 0) {
1642		/* File size is unknown, so we can't set the size. */
1643	} else if (a->fd_offset == a->filesize) {
1644		/* Last write ended at exactly the filesize; we're done. */
1645		/* Hopefully, this is the common case. */
1646#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
1647	} else if (a->todo & TODO_HFS_COMPRESSION) {
1648		char null_d[1024];
1649		ssize_t r;
1650
1651		if (a->file_remaining_bytes)
1652			memset(null_d, 0, sizeof(null_d));
1653		while (a->file_remaining_bytes) {
1654			if (a->file_remaining_bytes > sizeof(null_d))
1655				r = hfs_write_data_block(
1656				    a, null_d, sizeof(null_d));
1657			else
1658				r = hfs_write_data_block(
1659				    a, null_d, a->file_remaining_bytes);
1660			if (r < 0)
1661				return ((int)r);
1662		}
1663#endif
1664	} else {
1665#if HAVE_FTRUNCATE
1666		if (ftruncate(a->fd, a->filesize) == -1 &&
1667		    a->filesize == 0) {
1668			archive_set_error(&a->archive, errno,
1669			    "File size could not be restored");
1670			return (ARCHIVE_FAILED);
1671		}
1672#endif
1673		/*
1674		 * Not all platforms implement the XSI option to
1675		 * extend files via ftruncate.  Stat() the file again
1676		 * to see what happened.
1677		 */
1678		a->pst = NULL;
1679		if ((ret = lazy_stat(a)) != ARCHIVE_OK)
1680			return (ret);
1681		/* We can use lseek()/write() to extend the file if
1682		 * ftruncate didn't work or isn't available. */
1683		if (a->st.st_size < a->filesize) {
1684			const char nul = '\0';
1685			if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) {
1686				archive_set_error(&a->archive, errno,
1687				    "Seek failed");
1688				return (ARCHIVE_FATAL);
1689			}
1690			if (write(a->fd, &nul, 1) < 0) {
1691				archive_set_error(&a->archive, errno,
1692				    "Write to restore size failed");
1693				return (ARCHIVE_FATAL);
1694			}
1695			a->pst = NULL;
1696		}
1697	}
1698
1699	/* Restore metadata. */
1700
1701	/*
1702	 * This is specific to Mac OS X.
1703	 * If the current file is an AppleDouble file, it should be
1704	 * linked with the data fork file and remove it.
1705	 */
1706	if (a->todo & TODO_APPLEDOUBLE) {
1707		int r2 = fixup_appledouble(a, a->name);
1708		if (r2 == ARCHIVE_EOF) {
1709			/* The current file has been successfully linked
1710			 * with the data fork file and removed. So there
1711			 * is nothing to do on the current file.  */
1712			goto finish_metadata;
1713		}
1714		if (r2 < ret) ret = r2;
1715	}
1716
1717	/*
1718	 * Look up the "real" UID only if we're going to need it.
1719	 * TODO: the TODO_SGID condition can be dropped here, can't it?
1720	 */
1721	if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
1722		a->uid = archive_write_disk_uid(&a->archive,
1723		    archive_entry_uname(a->entry),
1724		    archive_entry_uid(a->entry));
1725	}
1726	/* Look up the "real" GID only if we're going to need it. */
1727	/* TODO: the TODO_SUID condition can be dropped here, can't it? */
1728	if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
1729		a->gid = archive_write_disk_gid(&a->archive,
1730		    archive_entry_gname(a->entry),
1731		    archive_entry_gid(a->entry));
1732	 }
1733
1734	/*
1735	 * Restore ownership before set_mode tries to restore suid/sgid
1736	 * bits.  If we set the owner, we know what it is and can skip
1737	 * a stat() call to examine the ownership of the file on disk.
1738	 */
1739	if (a->todo & TODO_OWNER) {
1740		int r2 = set_ownership(a);
1741		if (r2 < ret) ret = r2;
1742	}
1743
1744	/*
1745	 * HYPOTHESIS:
1746	 * If we're not root, we won't be setting any security
1747	 * attributes that may be wiped by the set_mode() routine
1748	 * below.  We also can't set xattr on non-owner-writable files,
1749	 * which may be the state after set_mode(). Perform
1750	 * set_xattrs() first based on these constraints.
1751	 */
1752	if (a->user_uid != 0 &&
1753	    (a->todo & TODO_XATTR)) {
1754		int r2 = set_xattrs(a);
1755		if (r2 < ret) ret = r2;
1756	}
1757
1758	/*
1759	 * set_mode must precede ACLs on systems such as Solaris and
1760	 * FreeBSD where setting the mode implicitly clears extended ACLs
1761	 */
1762	if (a->todo & TODO_MODE) {
1763		int r2 = set_mode(a, a->mode);
1764		if (r2 < ret) ret = r2;
1765	}
1766
1767	/*
1768	 * Security-related extended attributes (such as
1769	 * security.capability on Linux) have to be restored last,
1770	 * since they're implicitly removed by other file changes.
1771	 * We do this last only when root.
1772	 */
1773	if (a->user_uid == 0 &&
1774	    (a->todo & TODO_XATTR)) {
1775		int r2 = set_xattrs(a);
1776		if (r2 < ret) ret = r2;
1777	}
1778
1779	/*
1780	 * Some flags prevent file modification; they must be restored after
1781	 * file contents are written.
1782	 */
1783	if (a->todo & TODO_FFLAGS) {
1784		int r2 = set_fflags(a);
1785		if (r2 < ret) ret = r2;
1786	}
1787
1788	/*
1789	 * Time must follow most other metadata;
1790	 * otherwise atime will get changed.
1791	 */
1792	if (a->todo & TODO_TIMES) {
1793		int r2 = set_times_from_entry(a);
1794		if (r2 < ret) ret = r2;
1795	}
1796
1797	/*
1798	 * Mac extended metadata includes ACLs.
1799	 */
1800	if (a->todo & TODO_MAC_METADATA) {
1801		const void *metadata;
1802		size_t metadata_size;
1803		metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
1804		if (metadata != NULL && metadata_size > 0) {
1805			int r2 = set_mac_metadata(a, archive_entry_pathname(
1806			    a->entry), metadata, metadata_size);
1807			if (r2 < ret) ret = r2;
1808		}
1809	}
1810
1811	/*
1812	 * ACLs must be restored after timestamps because there are
1813	 * ACLs that prevent attribute changes (including time).
1814	 */
1815	if (a->todo & TODO_ACLS) {
1816		int r2;
1817		r2 = archive_write_disk_set_acls(&a->archive, a->fd,
1818		    archive_entry_pathname(a->entry),
1819		    archive_entry_acl(a->entry),
1820		    archive_entry_mode(a->entry));
1821		if (r2 < ret) ret = r2;
1822	}
1823
1824finish_metadata:
1825	/* If there's an fd, we can close it now. */
1826	if (a->fd >= 0) {
1827		close(a->fd);
1828		a->fd = -1;
1829	}
1830	/* If there's an entry, we can release it now. */
1831	archive_entry_free(a->entry);
1832	a->entry = NULL;
1833	a->archive.state = ARCHIVE_STATE_HEADER;
1834	return (ret);
1835}
1836
1837int
1838archive_write_disk_set_group_lookup(struct archive *_a,
1839    void *private_data,
1840    la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid),
1841    void (*cleanup_gid)(void *private))
1842{
1843	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1844	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1845	    ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
1846
1847	if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1848		(a->cleanup_gid)(a->lookup_gid_data);
1849
1850	a->lookup_gid = lookup_gid;
1851	a->cleanup_gid = cleanup_gid;
1852	a->lookup_gid_data = private_data;
1853	return (ARCHIVE_OK);
1854}
1855
1856int
1857archive_write_disk_set_user_lookup(struct archive *_a,
1858    void *private_data,
1859    int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
1860    void (*cleanup_uid)(void *private))
1861{
1862	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1863	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1864	    ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
1865
1866	if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1867		(a->cleanup_uid)(a->lookup_uid_data);
1868
1869	a->lookup_uid = lookup_uid;
1870	a->cleanup_uid = cleanup_uid;
1871	a->lookup_uid_data = private_data;
1872	return (ARCHIVE_OK);
1873}
1874
1875int64_t
1876archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id)
1877{
1878       struct archive_write_disk *a = (struct archive_write_disk *)_a;
1879       archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1880           ARCHIVE_STATE_ANY, "archive_write_disk_gid");
1881       if (a->lookup_gid)
1882               return (a->lookup_gid)(a->lookup_gid_data, name, id);
1883       return (id);
1884}
1885
1886int64_t
1887archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id)
1888{
1889	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1890	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1891	    ARCHIVE_STATE_ANY, "archive_write_disk_uid");
1892	if (a->lookup_uid)
1893		return (a->lookup_uid)(a->lookup_uid_data, name, id);
1894	return (id);
1895}
1896
1897/*
1898 * Create a new archive_write_disk object and initialize it with global state.
1899 */
1900struct archive *
1901archive_write_disk_new(void)
1902{
1903	struct archive_write_disk *a;
1904
1905	a = (struct archive_write_disk *)calloc(1, sizeof(*a));
1906	if (a == NULL)
1907		return (NULL);
1908	a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
1909	/* We're ready to write a header immediately. */
1910	a->archive.state = ARCHIVE_STATE_HEADER;
1911	a->archive.vtable = archive_write_disk_vtable();
1912	a->start_time = time(NULL);
1913	/* Query and restore the umask. */
1914	umask(a->user_umask = umask(0));
1915#ifdef HAVE_GETEUID
1916	a->user_uid = geteuid();
1917#endif /* HAVE_GETEUID */
1918	if (archive_string_ensure(&a->path_safe, 512) == NULL) {
1919		free(a);
1920		return (NULL);
1921	}
1922#ifdef HAVE_ZLIB_H
1923	a->decmpfs_compression_level = 5;
1924#endif
1925	return (&a->archive);
1926}
1927
1928
1929/*
1930 * If pathname is longer than PATH_MAX, chdir to a suitable
1931 * intermediate dir and edit the path down to a shorter suffix.  Note
1932 * that this routine never returns an error; if the chdir() attempt
1933 * fails for any reason, we just go ahead with the long pathname.  The
1934 * object creation is likely to fail, but any error will get handled
1935 * at that time.
1936 */
1937#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
1938static void
1939edit_deep_directories(struct archive_write_disk *a)
1940{
1941	int ret;
1942	char *tail = a->name;
1943
1944	/* If path is short, avoid the open() below. */
1945	if (strlen(tail) < PATH_MAX)
1946		return;
1947
1948	/* Try to record our starting dir. */
1949	a->restore_pwd = la_opendirat(AT_FDCWD, ".");
1950	__archive_ensure_cloexec_flag(a->restore_pwd);
1951	if (a->restore_pwd < 0)
1952		return;
1953
1954	/* As long as the path is too long... */
1955	while (strlen(tail) >= PATH_MAX) {
1956		/* Locate a dir prefix shorter than PATH_MAX. */
1957		tail += PATH_MAX - 8;
1958		while (tail > a->name && *tail != '/')
1959			tail--;
1960		/* Exit if we find a too-long path component. */
1961		if (tail <= a->name)
1962			return;
1963		/* Create the intermediate dir and chdir to it. */
1964		*tail = '\0'; /* Terminate dir portion */
1965		ret = create_dir(a, a->name);
1966		if (ret == ARCHIVE_OK && chdir(a->name) != 0)
1967			ret = ARCHIVE_FAILED;
1968		*tail = '/'; /* Restore the / we removed. */
1969		if (ret != ARCHIVE_OK)
1970			return;
1971		tail++;
1972		/* The chdir() succeeded; we've now shortened the path. */
1973		a->name = tail;
1974	}
1975	return;
1976}
1977#endif
1978
1979/*
1980 * The main restore function.
1981 */
1982static int
1983restore_entry(struct archive_write_disk *a)
1984{
1985	int ret = ARCHIVE_OK, en;
1986
1987	if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
1988		/*
1989		 * TODO: Fix this.  Apparently, there are platforms
1990		 * that still allow root to hose the entire filesystem
1991		 * by unlinking a dir.  The S_ISDIR() test above
1992		 * prevents us from using unlink() here if the new
1993		 * object is a dir, but that doesn't mean the old
1994		 * object isn't a dir.
1995		 */
1996		if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
1997			(void)clear_nochange_fflags(a);
1998		if (unlink(a->name) == 0) {
1999			/* We removed it, reset cached stat. */
2000			a->pst = NULL;
2001		} else if (errno == ENOENT) {
2002			/* File didn't exist, that's just as good. */
2003		} else if (rmdir(a->name) == 0) {
2004			/* It was a dir, but now it's gone. */
2005			a->pst = NULL;
2006		} else {
2007			/* We tried, but couldn't get rid of it. */
2008			archive_set_error(&a->archive, errno,
2009			    "Could not unlink");
2010			return(ARCHIVE_FAILED);
2011		}
2012	}
2013
2014	/* Try creating it first; if this fails, we'll try to recover. */
2015	en = create_filesystem_object(a);
2016
2017	if ((en == ENOTDIR || en == ENOENT)
2018	    && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
2019		/* If the parent dir doesn't exist, try creating it. */
2020		create_parent_dir(a, a->name);
2021		/* Now try to create the object again. */
2022		en = create_filesystem_object(a);
2023	}
2024
2025	if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) {
2026		archive_set_error(&a->archive, en,
2027		    "Hard-link target '%s' does not exist.",
2028		    archive_entry_hardlink(a->entry));
2029		return (ARCHIVE_FAILED);
2030	}
2031
2032	if ((en == EISDIR || en == EEXIST)
2033	    && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
2034		/* If we're not overwriting, we're done. */
2035		if (S_ISDIR(a->mode)) {
2036			/* Don't overwrite any settings on existing directories. */
2037			a->todo = 0;
2038		}
2039		archive_entry_unset_size(a->entry);
2040		return (ARCHIVE_OK);
2041	}
2042
2043	/*
2044	 * Some platforms return EISDIR if you call
2045	 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
2046	 * return EEXIST.  POSIX is ambiguous, requiring EISDIR
2047	 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
2048	 * on an existing item.
2049	 */
2050	if (en == EISDIR) {
2051		/* A dir is in the way of a non-dir, rmdir it. */
2052		if (rmdir(a->name) != 0) {
2053			archive_set_error(&a->archive, errno,
2054			    "Can't remove already-existing dir");
2055			return (ARCHIVE_FAILED);
2056		}
2057		a->pst = NULL;
2058		/* Try again. */
2059		en = create_filesystem_object(a);
2060	} else if (en == EEXIST) {
2061		/*
2062		 * We know something is in the way, but we don't know what;
2063		 * we need to find out before we go any further.
2064		 */
2065		int r = 0;
2066		/*
2067		 * The SECURE_SYMLINKS logic has already removed a
2068		 * symlink to a dir if the client wants that.  So
2069		 * follow the symlink if we're creating a dir.
2070		 */
2071		if (S_ISDIR(a->mode))
2072			r = la_stat(a->name, &a->st);
2073		/*
2074		 * If it's not a dir (or it's a broken symlink),
2075		 * then don't follow it.
2076		 */
2077		if (r != 0 || !S_ISDIR(a->mode))
2078			r = lstat(a->name, &a->st);
2079		if (r != 0) {
2080			archive_set_error(&a->archive, errno,
2081			    "Can't stat existing object");
2082			return (ARCHIVE_FAILED);
2083		}
2084
2085		/*
2086		 * NO_OVERWRITE_NEWER doesn't apply to directories.
2087		 */
2088		if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
2089		    &&  !S_ISDIR(a->st.st_mode)) {
2090			if (!older(&(a->st), a->entry)) {
2091				archive_entry_unset_size(a->entry);
2092				return (ARCHIVE_OK);
2093			}
2094		}
2095
2096		/* If it's our archive, we're done. */
2097		if (a->skip_file_set &&
2098		    a->st.st_dev == (dev_t)a->skip_file_dev &&
2099		    a->st.st_ino == (ino_t)a->skip_file_ino) {
2100			archive_set_error(&a->archive, 0,
2101			    "Refusing to overwrite archive");
2102			return (ARCHIVE_FAILED);
2103		}
2104
2105		if (!S_ISDIR(a->st.st_mode)) {
2106			/* A non-dir is in the way, unlink it. */
2107			if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2108				(void)clear_nochange_fflags(a);
2109			if (unlink(a->name) != 0) {
2110				archive_set_error(&a->archive, errno,
2111				    "Can't unlink already-existing object");
2112				return (ARCHIVE_FAILED);
2113			}
2114			a->pst = NULL;
2115			/* Try again. */
2116			en = create_filesystem_object(a);
2117		} else if (!S_ISDIR(a->mode)) {
2118			/* A dir is in the way of a non-dir, rmdir it. */
2119			if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2120				(void)clear_nochange_fflags(a);
2121			if (rmdir(a->name) != 0) {
2122				archive_set_error(&a->archive, errno,
2123				    "Can't replace existing directory with non-directory");
2124				return (ARCHIVE_FAILED);
2125			}
2126			/* Try again. */
2127			en = create_filesystem_object(a);
2128		} else {
2129			/*
2130			 * There's a dir in the way of a dir.  Don't
2131			 * waste time with rmdir()/mkdir(), just fix
2132			 * up the permissions on the existing dir.
2133			 * Note that we don't change perms on existing
2134			 * dirs unless _EXTRACT_PERM is specified.
2135			 */
2136			if ((a->mode != a->st.st_mode)
2137			    && (a->todo & TODO_MODE_FORCE))
2138				a->deferred |= (a->todo & TODO_MODE);
2139			/* Ownership doesn't need deferred fixup. */
2140			en = 0; /* Forget the EEXIST. */
2141		}
2142	}
2143
2144	if (en) {
2145		/* Everything failed; give up here. */
2146		if ((&a->archive)->error == NULL)
2147			archive_set_error(&a->archive, en, "Can't create '%s'",
2148			    a->name);
2149		return (ARCHIVE_FAILED);
2150	}
2151
2152	a->pst = NULL; /* Cached stat data no longer valid. */
2153	return (ret);
2154}
2155
2156/*
2157 * Returns 0 if creation succeeds, or else returns errno value from
2158 * the failed system call.   Note:  This function should only ever perform
2159 * a single system call.
2160 */
2161static int
2162create_filesystem_object(struct archive_write_disk *a)
2163{
2164	/* Create the entry. */
2165	const char *linkname;
2166	mode_t final_mode, mode;
2167	int r;
2168	/* these for check_symlinks_fsobj */
2169	char *linkname_copy;	/* non-const copy of linkname */
2170	struct stat st;
2171	struct archive_string error_string;
2172	int error_number;
2173
2174	/* We identify hard/symlinks according to the link names. */
2175	/* Since link(2) and symlink(2) don't handle modes, we're done here. */
2176	linkname = archive_entry_hardlink(a->entry);
2177	if (linkname != NULL) {
2178#if !HAVE_LINK
2179		return (EPERM);
2180#else
2181		archive_string_init(&error_string);
2182		linkname_copy = strdup(linkname);
2183		if (linkname_copy == NULL) {
2184		    return (EPERM);
2185		}
2186		/*
2187		 * TODO: consider using the cleaned-up path as the link
2188		 * target?
2189		 */
2190		r = cleanup_pathname_fsobj(linkname_copy, &error_number,
2191		    &error_string, a->flags);
2192		if (r != ARCHIVE_OK) {
2193			archive_set_error(&a->archive, error_number, "%s",
2194			    error_string.s);
2195			free(linkname_copy);
2196			archive_string_free(&error_string);
2197			/*
2198			 * EPERM is more appropriate than error_number for our
2199			 * callers
2200			 */
2201			return (EPERM);
2202		}
2203		r = check_symlinks_fsobj(linkname_copy, &error_number,
2204		    &error_string, a->flags);
2205		if (r != ARCHIVE_OK) {
2206			archive_set_error(&a->archive, error_number, "%s",
2207			    error_string.s);
2208			free(linkname_copy);
2209			archive_string_free(&error_string);
2210			/*
2211			 * EPERM is more appropriate than error_number for our
2212			 * callers
2213			 */
2214			return (EPERM);
2215		}
2216		free(linkname_copy);
2217		archive_string_free(&error_string);
2218		r = link(linkname, a->name) ? errno : 0;
2219		/*
2220		 * New cpio and pax formats allow hardlink entries
2221		 * to carry data, so we may have to open the file
2222		 * for hardlink entries.
2223		 *
2224		 * If the hardlink was successfully created and
2225		 * the archive doesn't have carry data for it,
2226		 * consider it to be non-authoritative for meta data.
2227		 * This is consistent with GNU tar and BSD pax.
2228		 * If the hardlink does carry data, let the last
2229		 * archive entry decide ownership.
2230		 */
2231		if (r == 0 && a->filesize <= 0) {
2232			a->todo = 0;
2233			a->deferred = 0;
2234		} else if (r == 0 && a->filesize > 0) {
2235#ifdef HAVE_LSTAT
2236			r = lstat(a->name, &st);
2237#else
2238			r = la_stat(a->name, &st);
2239#endif
2240			if (r != 0)
2241				r = errno;
2242			else if ((st.st_mode & AE_IFMT) == AE_IFREG) {
2243				a->fd = open(a->name, O_WRONLY | O_TRUNC |
2244				    O_BINARY | O_CLOEXEC | O_NOFOLLOW);
2245				__archive_ensure_cloexec_flag(a->fd);
2246				if (a->fd < 0)
2247					r = errno;
2248			}
2249		}
2250		return (r);
2251#endif
2252	}
2253	linkname = archive_entry_symlink(a->entry);
2254	if (linkname != NULL) {
2255#if HAVE_SYMLINK
2256		return symlink(linkname, a->name) ? errno : 0;
2257#else
2258		return (EPERM);
2259#endif
2260	}
2261
2262	/*
2263	 * The remaining system calls all set permissions, so let's
2264	 * try to take advantage of that to avoid an extra chmod()
2265	 * call.  (Recall that umask is set to zero right now!)
2266	 */
2267
2268	/* Mode we want for the final restored object (w/o file type bits). */
2269	final_mode = a->mode & 07777;
2270	/*
2271	 * The mode that will actually be restored in this step.  Note
2272	 * that SUID, SGID, etc, require additional work to ensure
2273	 * security, so we never restore them at this point.
2274	 */
2275	mode = final_mode & 0777 & ~a->user_umask;
2276
2277	/*
2278	 * Always create writable such that [f]setxattr() works if we're not
2279	 * root.
2280	 */
2281	if (a->user_uid != 0 &&
2282	    a->todo & (TODO_HFS_COMPRESSION | TODO_XATTR)) {
2283		mode |= 0200;
2284	}
2285
2286	switch (a->mode & AE_IFMT) {
2287	default:
2288		/* POSIX requires that we fall through here. */
2289		/* FALLTHROUGH */
2290	case AE_IFREG:
2291		a->fd = open(a->name,
2292		    O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
2293		__archive_ensure_cloexec_flag(a->fd);
2294		r = (a->fd < 0);
2295		break;
2296	case AE_IFCHR:
2297#ifdef HAVE_MKNOD
2298		/* Note: we use AE_IFCHR for the case label, and
2299		 * S_IFCHR for the mknod() call.  This is correct.  */
2300		r = mknod(a->name, mode | S_IFCHR,
2301		    archive_entry_rdev(a->entry));
2302		break;
2303#else
2304		/* TODO: Find a better way to warn about our inability
2305		 * to restore a char device node. */
2306		return (EINVAL);
2307#endif /* HAVE_MKNOD */
2308	case AE_IFBLK:
2309#ifdef HAVE_MKNOD
2310		r = mknod(a->name, mode | S_IFBLK,
2311		    archive_entry_rdev(a->entry));
2312		break;
2313#else
2314		/* TODO: Find a better way to warn about our inability
2315		 * to restore a block device node. */
2316		return (EINVAL);
2317#endif /* HAVE_MKNOD */
2318	case AE_IFDIR:
2319		mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
2320		r = mkdir(a->name, mode);
2321		if (r == 0) {
2322			/* Defer setting dir times. */
2323			a->deferred |= (a->todo & TODO_TIMES);
2324			a->todo &= ~TODO_TIMES;
2325			/* Never use an immediate chmod(). */
2326			/* We can't avoid the chmod() entirely if EXTRACT_PERM
2327			 * because of SysV SGID inheritance. */
2328			if ((mode != final_mode)
2329			    || (a->flags & ARCHIVE_EXTRACT_PERM))
2330				a->deferred |= (a->todo & TODO_MODE);
2331			a->todo &= ~TODO_MODE;
2332		}
2333		break;
2334	case AE_IFIFO:
2335#ifdef HAVE_MKFIFO
2336		r = mkfifo(a->name, mode);
2337		break;
2338#else
2339		/* TODO: Find a better way to warn about our inability
2340		 * to restore a fifo. */
2341		return (EINVAL);
2342#endif /* HAVE_MKFIFO */
2343	}
2344
2345	/* All the system calls above set errno on failure. */
2346	if (r)
2347		return (errno);
2348
2349	/* If we managed to set the final mode, we've avoided a chmod(). */
2350	if (mode == final_mode)
2351		a->todo &= ~TODO_MODE;
2352	return (0);
2353}
2354
2355/*
2356 * Cleanup function for archive_extract.  Mostly, this involves processing
2357 * the fixup list, which is used to address a number of problems:
2358 *   * Dir permissions might prevent us from restoring a file in that
2359 *     dir, so we restore the dir with minimum 0700 permissions first,
2360 *     then correct the mode at the end.
2361 *   * Similarly, the act of restoring a file touches the directory
2362 *     and changes the timestamp on the dir, so we have to touch-up dir
2363 *     timestamps at the end as well.
2364 *   * Some file flags can interfere with the restore by, for example,
2365 *     preventing the creation of hardlinks to those files.
2366 *   * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
2367 *
2368 * Note that tar/cpio do not require that archives be in a particular
2369 * order; there is no way to know when the last file has been restored
2370 * within a directory, so there's no way to optimize the memory usage
2371 * here by fixing up the directory any earlier than the
2372 * end-of-archive.
2373 *
2374 * XXX TODO: Directory ACLs should be restored here, for the same
2375 * reason we set directory perms here. XXX
2376 */
2377static int
2378_archive_write_disk_close(struct archive *_a)
2379{
2380	struct archive_write_disk *a = (struct archive_write_disk *)_a;
2381	struct fixup_entry *next, *p;
2382	int fd, ret;
2383
2384	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
2385	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
2386	    "archive_write_disk_close");
2387	ret = _archive_write_disk_finish_entry(&a->archive);
2388
2389	/* Sort dir list so directories are fixed up in depth-first order. */
2390	p = sort_dir_list(a->fixup_list);
2391
2392	while (p != NULL) {
2393		fd = -1;
2394		a->pst = NULL; /* Mark stat cache as out-of-date. */
2395		if (p->fixup &
2396		    (TODO_TIMES | TODO_MODE_BASE | TODO_ACLS | TODO_FFLAGS)) {
2397			fd = open(p->name,
2398			    O_WRONLY | O_BINARY | O_NOFOLLOW | O_CLOEXEC);
2399		}
2400		if (p->fixup & TODO_TIMES) {
2401			set_times(a, fd, p->mode, p->name,
2402			    p->atime, p->atime_nanos,
2403			    p->birthtime, p->birthtime_nanos,
2404			    p->mtime, p->mtime_nanos,
2405			    p->ctime, p->ctime_nanos);
2406		}
2407		if (p->fixup & TODO_MODE_BASE) {
2408#ifdef HAVE_FCHMOD
2409			if (fd >= 0)
2410				fchmod(fd, p->mode);
2411			else
2412#endif
2413			chmod(p->name, p->mode);
2414		}
2415		if (p->fixup & TODO_ACLS)
2416			archive_write_disk_set_acls(&a->archive, fd,
2417			    p->name, &p->acl, p->mode);
2418		if (p->fixup & TODO_FFLAGS)
2419			set_fflags_platform(a, fd, p->name,
2420			    p->mode, p->fflags_set, 0);
2421		if (p->fixup & TODO_MAC_METADATA)
2422			set_mac_metadata(a, p->name, p->mac_metadata,
2423					 p->mac_metadata_size);
2424		next = p->next;
2425		archive_acl_clear(&p->acl);
2426		free(p->mac_metadata);
2427		free(p->name);
2428		if (fd >= 0)
2429			close(fd);
2430		free(p);
2431		p = next;
2432	}
2433	a->fixup_list = NULL;
2434	return (ret);
2435}
2436
2437static int
2438_archive_write_disk_free(struct archive *_a)
2439{
2440	struct archive_write_disk *a;
2441	int ret;
2442	if (_a == NULL)
2443		return (ARCHIVE_OK);
2444	archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
2445	    ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
2446	a = (struct archive_write_disk *)_a;
2447	ret = _archive_write_disk_close(&a->archive);
2448	archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
2449	archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
2450	archive_entry_free(a->entry);
2451	archive_string_free(&a->_name_data);
2452	archive_string_free(&a->archive.error_string);
2453	archive_string_free(&a->path_safe);
2454	a->archive.magic = 0;
2455	__archive_clean(&a->archive);
2456	free(a->decmpfs_header_p);
2457	free(a->resource_fork);
2458	free(a->compressed_buffer);
2459	free(a->uncompressed_buffer);
2460#if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
2461	&& defined(HAVE_ZLIB_H)
2462	if (a->stream_valid) {
2463		switch (deflateEnd(&a->stream)) {
2464		case Z_OK:
2465			break;
2466		default:
2467			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2468			    "Failed to clean up compressor");
2469			ret = ARCHIVE_FATAL;
2470			break;
2471		}
2472	}
2473#endif
2474	free(a);
2475	return (ret);
2476}
2477
2478/*
2479 * Simple O(n log n) merge sort to order the fixup list.  In
2480 * particular, we want to restore dir timestamps depth-first.
2481 */
2482static struct fixup_entry *
2483sort_dir_list(struct fixup_entry *p)
2484{
2485	struct fixup_entry *a, *b, *t;
2486
2487	if (p == NULL)
2488		return (NULL);
2489	/* A one-item list is already sorted. */
2490	if (p->next == NULL)
2491		return (p);
2492
2493	/* Step 1: split the list. */
2494	t = p;
2495	a = p->next->next;
2496	while (a != NULL) {
2497		/* Step a twice, t once. */
2498		a = a->next;
2499		if (a != NULL)
2500			a = a->next;
2501		t = t->next;
2502	}
2503	/* Now, t is at the mid-point, so break the list here. */
2504	b = t->next;
2505	t->next = NULL;
2506	a = p;
2507
2508	/* Step 2: Recursively sort the two sub-lists. */
2509	a = sort_dir_list(a);
2510	b = sort_dir_list(b);
2511
2512	/* Step 3: Merge the returned lists. */
2513	/* Pick the first element for the merged list. */
2514	if (strcmp(a->name, b->name) > 0) {
2515		t = p = a;
2516		a = a->next;
2517	} else {
2518		t = p = b;
2519		b = b->next;
2520	}
2521
2522	/* Always put the later element on the list first. */
2523	while (a != NULL && b != NULL) {
2524		if (strcmp(a->name, b->name) > 0) {
2525			t->next = a;
2526			a = a->next;
2527		} else {
2528			t->next = b;
2529			b = b->next;
2530		}
2531		t = t->next;
2532	}
2533
2534	/* Only one list is non-empty, so just splice it on. */
2535	if (a != NULL)
2536		t->next = a;
2537	if (b != NULL)
2538		t->next = b;
2539
2540	return (p);
2541}
2542
2543/*
2544 * Returns a new, initialized fixup entry.
2545 *
2546 * TODO: Reduce the memory requirements for this list by using a tree
2547 * structure rather than a simple list of names.
2548 */
2549static struct fixup_entry *
2550new_fixup(struct archive_write_disk *a, const char *pathname)
2551{
2552	struct fixup_entry *fe;
2553
2554	fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
2555	if (fe == NULL) {
2556		archive_set_error(&a->archive, ENOMEM,
2557		    "Can't allocate memory for a fixup");
2558		return (NULL);
2559	}
2560	fe->next = a->fixup_list;
2561	a->fixup_list = fe;
2562	fe->fixup = 0;
2563	fe->name = strdup(pathname);
2564	return (fe);
2565}
2566
2567/*
2568 * Returns a fixup structure for the current entry.
2569 */
2570static struct fixup_entry *
2571current_fixup(struct archive_write_disk *a, const char *pathname)
2572{
2573	if (a->current_fixup == NULL)
2574		a->current_fixup = new_fixup(a, pathname);
2575	return (a->current_fixup);
2576}
2577
2578/* Error helper for new *_fsobj functions */
2579static void
2580fsobj_error(int *a_eno, struct archive_string *a_estr,
2581    int err, const char *errstr, const char *path)
2582{
2583	if (a_eno)
2584		*a_eno = err;
2585	if (a_estr)
2586		archive_string_sprintf(a_estr, "%s%s", errstr, path);
2587}
2588
2589/*
2590 * TODO: Someday, integrate this with the deep dir support; they both
2591 * scan the path and both can be optimized by comparing against other
2592 * recent paths.
2593 */
2594/*
2595 * Checks the given path to see if any elements along it are symlinks.  Returns
2596 * ARCHIVE_OK if there are none, otherwise puts an error in errmsg.
2597 */
2598static int
2599check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2600    int flags)
2601{
2602#if !defined(HAVE_LSTAT) && \
2603    !(defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT))
2604	/* Platform doesn't have lstat, so we can't look for symlinks. */
2605	(void)path; /* UNUSED */
2606	(void)error_number; /* UNUSED */
2607	(void)error_string; /* UNUSED */
2608	(void)flags; /* UNUSED */
2609	return (ARCHIVE_OK);
2610#else
2611	int res = ARCHIVE_OK;
2612	char *tail;
2613	char *head;
2614	int last;
2615	char c;
2616	int r;
2617	struct stat st;
2618	int chdir_fd;
2619#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2620	int fd;
2621#endif
2622
2623	/* Nothing to do here if name is empty */
2624	if(path[0] == '\0')
2625	    return (ARCHIVE_OK);
2626
2627	/*
2628	 * Guard against symlink tricks.  Reject any archive entry whose
2629	 * destination would be altered by a symlink.
2630	 *
2631	 * Walk the filename in chunks separated by '/'.  For each segment:
2632	 *  - if it doesn't exist, continue
2633	 *  - if it's symlink, abort or remove it
2634	 *  - if it's a directory and it's not the last chunk, cd into it
2635	 * As we go:
2636	 *  head points to the current (relative) path
2637	 *  tail points to the temporary \0 terminating the segment we're
2638	 *      currently examining
2639	 *  c holds what used to be in *tail
2640	 *  last is 1 if this is the last tail
2641	 */
2642	chdir_fd = la_opendirat(AT_FDCWD, ".");
2643	__archive_ensure_cloexec_flag(chdir_fd);
2644	if (chdir_fd < 0) {
2645		fsobj_error(a_eno, a_estr, errno,
2646		    "Could not open ", path);
2647		return (ARCHIVE_FATAL);
2648	}
2649	head = path;
2650	tail = path;
2651	last = 0;
2652	/* TODO: reintroduce a safe cache here? */
2653	/* Skip the root directory if the path is absolute. */
2654	if(tail == path && tail[0] == '/')
2655		++tail;
2656	/* Keep going until we've checked the entire name.
2657	 * head, tail, path all alias the same string, which is
2658	 * temporarily zeroed at tail, so be careful restoring the
2659	 * stashed (c=tail[0]) for error messages.
2660	 * Exiting the loop with break is okay; continue is not.
2661	 */
2662	while (!last) {
2663		/*
2664		 * Skip the separator we just consumed, plus any adjacent ones
2665		 */
2666		while (*tail == '/')
2667		    ++tail;
2668		/* Skip the next path element. */
2669		while (*tail != '\0' && *tail != '/')
2670			++tail;
2671		/* is this the last path component? */
2672		last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
2673		/* temporarily truncate the string here */
2674		c = tail[0];
2675		tail[0] = '\0';
2676		/* Check that we haven't hit a symlink. */
2677#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2678		r = fstatat(chdir_fd, head, &st, AT_SYMLINK_NOFOLLOW);
2679#else
2680		r = lstat(head, &st);
2681#endif
2682		if (r != 0) {
2683			tail[0] = c;
2684			/* We've hit a dir that doesn't exist; stop now. */
2685			if (errno == ENOENT) {
2686				break;
2687			} else {
2688				/*
2689				 * Treat any other error as fatal - best to be
2690				 * paranoid here.
2691				 * Note: This effectively disables deep
2692				 * directory support when security checks are
2693				 * enabled. Otherwise, very long pathnames that
2694				 * trigger an error here could evade the
2695				 * sandbox.
2696				 * TODO: We could do better, but it would
2697				 * probably require merging the symlink checks
2698				 * with the deep-directory editing.
2699				 */
2700				fsobj_error(a_eno, a_estr, errno,
2701				    "Could not stat ", path);
2702				res = ARCHIVE_FAILED;
2703				break;
2704			}
2705		} else if (S_ISDIR(st.st_mode)) {
2706			if (!last) {
2707#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2708				fd = la_opendirat(chdir_fd, head);
2709				if (fd < 0)
2710					r = -1;
2711				else {
2712					r = 0;
2713					close(chdir_fd);
2714					chdir_fd = fd;
2715				}
2716#else
2717				r = chdir(head);
2718#endif
2719				if (r != 0) {
2720					tail[0] = c;
2721					fsobj_error(a_eno, a_estr, errno,
2722					    "Could not chdir ", path);
2723					res = (ARCHIVE_FATAL);
2724					break;
2725				}
2726				/* Our view is now from inside this dir: */
2727				head = tail + 1;
2728			}
2729		} else if (S_ISLNK(st.st_mode)) {
2730			if (last) {
2731				/*
2732				 * Last element is symlink; remove it
2733				 * so we can overwrite it with the
2734				 * item being extracted.
2735				 */
2736#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2737				r = unlinkat(chdir_fd, head, 0);
2738#else
2739				r = unlink(head);
2740#endif
2741				if (r != 0) {
2742					tail[0] = c;
2743					fsobj_error(a_eno, a_estr, errno,
2744					    "Could not remove symlink ",
2745					    path);
2746					res = ARCHIVE_FAILED;
2747					break;
2748				}
2749				/*
2750				 * Even if we did remove it, a warning
2751				 * is in order.  The warning is silly,
2752				 * though, if we're just replacing one
2753				 * symlink with another symlink.
2754				 */
2755				tail[0] = c;
2756				/*
2757				 * FIXME:  not sure how important this is to
2758				 * restore
2759				 */
2760				/*
2761				if (!S_ISLNK(path)) {
2762					fsobj_error(a_eno, a_estr, 0,
2763					    "Removing symlink ", path);
2764				}
2765				*/
2766				/* Symlink gone.  No more problem! */
2767				res = ARCHIVE_OK;
2768				break;
2769			} else if (flags & ARCHIVE_EXTRACT_UNLINK) {
2770				/* User asked us to remove problems. */
2771#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2772				r = unlinkat(chdir_fd, head, 0);
2773#else
2774				r = unlink(head);
2775#endif
2776				if (r != 0) {
2777					tail[0] = c;
2778					fsobj_error(a_eno, a_estr, 0,
2779					    "Cannot remove intervening "
2780					    "symlink ", path);
2781					res = ARCHIVE_FAILED;
2782					break;
2783				}
2784				tail[0] = c;
2785			} else if ((flags &
2786			    ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) {
2787				/*
2788				 * We are not the last element and we want to
2789				 * follow symlinks if they are a directory.
2790				 *
2791				 * This is needed to extract hardlinks over
2792				 * symlinks.
2793				 */
2794#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2795				r = fstatat(chdir_fd, head, &st, 0);
2796#else
2797				r = la_stat(head, &st);
2798#endif
2799				if (r != 0) {
2800					tail[0] = c;
2801					if (errno == ENOENT) {
2802						break;
2803					} else {
2804						fsobj_error(a_eno, a_estr,
2805						    errno,
2806						    "Could not stat ", path);
2807						res = (ARCHIVE_FAILED);
2808						break;
2809					}
2810				} else if (S_ISDIR(st.st_mode)) {
2811#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2812					fd = la_opendirat(chdir_fd, head);
2813					if (fd < 0)
2814						r = -1;
2815					else {
2816						r = 0;
2817						close(chdir_fd);
2818						chdir_fd = fd;
2819					}
2820#else
2821					r = chdir(head);
2822#endif
2823					if (r != 0) {
2824						tail[0] = c;
2825						fsobj_error(a_eno, a_estr,
2826						    errno,
2827						    "Could not chdir ", path);
2828						res = (ARCHIVE_FATAL);
2829						break;
2830					}
2831					/*
2832					 * Our view is now from inside
2833					 * this dir:
2834					 */
2835					head = tail + 1;
2836				} else {
2837					tail[0] = c;
2838					fsobj_error(a_eno, a_estr, 0,
2839					    "Cannot extract through "
2840					    "symlink ", path);
2841					res = ARCHIVE_FAILED;
2842					break;
2843				}
2844			} else {
2845				tail[0] = c;
2846				fsobj_error(a_eno, a_estr, 0,
2847				    "Cannot extract through symlink ", path);
2848				res = ARCHIVE_FAILED;
2849				break;
2850			}
2851		}
2852		/* be sure to always maintain this */
2853		tail[0] = c;
2854		if (tail[0] != '\0')
2855			tail++; /* Advance to the next segment. */
2856	}
2857	/* Catches loop exits via break */
2858	tail[0] = c;
2859#if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2860	/* If we operate with openat(), fstatat() and unlinkat() there was
2861	 * no chdir(), so just close the fd */
2862	if (chdir_fd >= 0)
2863		close(chdir_fd);
2864#elif HAVE_FCHDIR
2865	/* If we changed directory above, restore it here. */
2866	if (chdir_fd >= 0) {
2867		r = fchdir(chdir_fd);
2868		if (r != 0) {
2869			fsobj_error(a_eno, a_estr, errno,
2870			    "chdir() failure", "");
2871		}
2872		close(chdir_fd);
2873		chdir_fd = -1;
2874		if (r != 0) {
2875			res = (ARCHIVE_FATAL);
2876		}
2877	}
2878#endif
2879	/* TODO: reintroduce a safe cache here? */
2880	return res;
2881#endif
2882}
2883
2884/*
2885 * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise
2886 * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED}
2887 */
2888static int
2889check_symlinks(struct archive_write_disk *a)
2890{
2891	struct archive_string error_string;
2892	int error_number;
2893	int rc;
2894	archive_string_init(&error_string);
2895	rc = check_symlinks_fsobj(a->name, &error_number, &error_string,
2896	    a->flags);
2897	if (rc != ARCHIVE_OK) {
2898		archive_set_error(&a->archive, error_number, "%s",
2899		    error_string.s);
2900	}
2901	archive_string_free(&error_string);
2902	a->pst = NULL;	/* to be safe */
2903	return rc;
2904}
2905
2906
2907#if defined(__CYGWIN__)
2908/*
2909 * 1. Convert a path separator from '\' to '/' .
2910 *    We shouldn't check multibyte character directly because some
2911 *    character-set have been using the '\' character for a part of
2912 *    its multibyte character code.
2913 * 2. Replace unusable characters in Windows with underscore('_').
2914 * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
2915 */
2916static void
2917cleanup_pathname_win(char *path)
2918{
2919	wchar_t wc;
2920	char *p;
2921	size_t alen, l;
2922	int mb, complete, utf8;
2923
2924	alen = 0;
2925	mb = 0;
2926	complete = 1;
2927	utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
2928	for (p = path; *p != '\0'; p++) {
2929		++alen;
2930		if (*p == '\\') {
2931			/* If previous byte is smaller than 128,
2932			 * this is not second byte of multibyte characters,
2933			 * so we can replace '\' with '/'. */
2934			if (utf8 || !mb)
2935				*p = '/';
2936			else
2937				complete = 0;/* uncompleted. */
2938		} else if (*(unsigned char *)p > 127)
2939			mb = 1;
2940		else
2941			mb = 0;
2942		/* Rewrite the path name if its next character is unusable. */
2943		if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
2944		    *p == '<' || *p == '>' || *p == '|')
2945			*p = '_';
2946	}
2947	if (complete)
2948		return;
2949
2950	/*
2951	 * Convert path separator in wide-character.
2952	 */
2953	p = path;
2954	while (*p != '\0' && alen) {
2955		l = mbtowc(&wc, p, alen);
2956		if (l == (size_t)-1) {
2957			while (*p != '\0') {
2958				if (*p == '\\')
2959					*p = '/';
2960				++p;
2961			}
2962			break;
2963		}
2964		if (l == 1 && wc == L'\\')
2965			*p = '/';
2966		p += l;
2967		alen -= l;
2968	}
2969}
2970#endif
2971
2972/*
2973 * Canonicalize the pathname.  In particular, this strips duplicate
2974 * '/' characters, '.' elements, and trailing '/'.  It also raises an
2975 * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is
2976 * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
2977 * is set) if the path is absolute.
2978 */
2979static int
2980cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2981    int flags)
2982{
2983	char *dest, *src;
2984	char separator = '\0';
2985
2986	dest = src = path;
2987	if (*src == '\0') {
2988		fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
2989		    "Invalid empty ", "pathname");
2990		return (ARCHIVE_FAILED);
2991	}
2992
2993#if defined(__CYGWIN__)
2994	cleanup_pathname_win(path);
2995#endif
2996	/* Skip leading '/'. */
2997	if (*src == '/') {
2998		if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
2999			fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3000			    "Path is ", "absolute");
3001			return (ARCHIVE_FAILED);
3002		}
3003
3004		separator = *src++;
3005	}
3006
3007	/* Scan the pathname one element at a time. */
3008	for (;;) {
3009		/* src points to first char after '/' */
3010		if (src[0] == '\0') {
3011			break;
3012		} else if (src[0] == '/') {
3013			/* Found '//', ignore second one. */
3014			src++;
3015			continue;
3016		} else if (src[0] == '.') {
3017			if (src[1] == '\0') {
3018				/* Ignore trailing '.' */
3019				break;
3020			} else if (src[1] == '/') {
3021				/* Skip './'. */
3022				src += 2;
3023				continue;
3024			} else if (src[1] == '.') {
3025				if (src[2] == '/' || src[2] == '\0') {
3026					/* Conditionally warn about '..' */
3027					if (flags
3028					    & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
3029						fsobj_error(a_eno, a_estr,
3030						    ARCHIVE_ERRNO_MISC,
3031						    "Path contains ", "'..'");
3032						return (ARCHIVE_FAILED);
3033					}
3034				}
3035				/*
3036				 * Note: Under no circumstances do we
3037				 * remove '..' elements.  In
3038				 * particular, restoring
3039				 * '/foo/../bar/' should create the
3040				 * 'foo' dir as a side-effect.
3041				 */
3042			}
3043		}
3044
3045		/* Copy current element, including leading '/'. */
3046		if (separator)
3047			*dest++ = '/';
3048		while (*src != '\0' && *src != '/') {
3049			*dest++ = *src++;
3050		}
3051
3052		if (*src == '\0')
3053			break;
3054
3055		/* Skip '/' separator. */
3056		separator = *src++;
3057	}
3058	/*
3059	 * We've just copied zero or more path elements, not including the
3060	 * final '/'.
3061	 */
3062	if (dest == path) {
3063		/*
3064		 * Nothing got copied.  The path must have been something
3065		 * like '.' or '/' or './' or '/././././/./'.
3066		 */
3067		if (separator)
3068			*dest++ = '/';
3069		else
3070			*dest++ = '.';
3071	}
3072	/* Terminate the result. */
3073	*dest = '\0';
3074	return (ARCHIVE_OK);
3075}
3076
3077static int
3078cleanup_pathname(struct archive_write_disk *a)
3079{
3080	struct archive_string error_string;
3081	int error_number;
3082	int rc;
3083	archive_string_init(&error_string);
3084	rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string,
3085	    a->flags);
3086	if (rc != ARCHIVE_OK) {
3087		archive_set_error(&a->archive, error_number, "%s",
3088		    error_string.s);
3089	}
3090	archive_string_free(&error_string);
3091	return rc;
3092}
3093
3094/*
3095 * Create the parent directory of the specified path, assuming path
3096 * is already in mutable storage.
3097 */
3098static int
3099create_parent_dir(struct archive_write_disk *a, char *path)
3100{
3101	char *slash;
3102	int r;
3103
3104	/* Remove tail element to obtain parent name. */
3105	slash = strrchr(path, '/');
3106	if (slash == NULL)
3107		return (ARCHIVE_OK);
3108	*slash = '\0';
3109	r = create_dir(a, path);
3110	*slash = '/';
3111	return (r);
3112}
3113
3114/*
3115 * Create the specified dir, recursing to create parents as necessary.
3116 *
3117 * Returns ARCHIVE_OK if the path exists when we're done here.
3118 * Otherwise, returns ARCHIVE_FAILED.
3119 * Assumes path is in mutable storage; path is unchanged on exit.
3120 */
3121static int
3122create_dir(struct archive_write_disk *a, char *path)
3123{
3124	struct stat st;
3125	struct fixup_entry *le;
3126	char *slash, *base;
3127	mode_t mode_final, mode;
3128	int r;
3129
3130	/* Check for special names and just skip them. */
3131	slash = strrchr(path, '/');
3132	if (slash == NULL)
3133		base = path;
3134	else
3135		base = slash + 1;
3136
3137	if (base[0] == '\0' ||
3138	    (base[0] == '.' && base[1] == '\0') ||
3139	    (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
3140		/* Don't bother trying to create null path, '.', or '..'. */
3141		if (slash != NULL) {
3142			*slash = '\0';
3143			r = create_dir(a, path);
3144			*slash = '/';
3145			return (r);
3146		}
3147		return (ARCHIVE_OK);
3148	}
3149
3150	/*
3151	 * Yes, this should be stat() and not lstat().  Using lstat()
3152	 * here loses the ability to extract through symlinks.  Also note
3153	 * that this should not use the a->st cache.
3154	 */
3155	if (la_stat(path, &st) == 0) {
3156		if (S_ISDIR(st.st_mode))
3157			return (ARCHIVE_OK);
3158		if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
3159			archive_set_error(&a->archive, EEXIST,
3160			    "Can't create directory '%s'", path);
3161			return (ARCHIVE_FAILED);
3162		}
3163		if (unlink(path) != 0) {
3164			archive_set_error(&a->archive, errno,
3165			    "Can't create directory '%s': "
3166			    "Conflicting file cannot be removed",
3167			    path);
3168			return (ARCHIVE_FAILED);
3169		}
3170	} else if (errno != ENOENT && errno != ENOTDIR) {
3171		/* Stat failed? */
3172		archive_set_error(&a->archive, errno,
3173		    "Can't test directory '%s'", path);
3174		return (ARCHIVE_FAILED);
3175	} else if (slash != NULL) {
3176		*slash = '\0';
3177		r = create_dir(a, path);
3178		*slash = '/';
3179		if (r != ARCHIVE_OK)
3180			return (r);
3181	}
3182
3183	/*
3184	 * Mode we want for the final restored directory.  Per POSIX,
3185	 * implicitly-created dirs must be created obeying the umask.
3186	 * There's no mention whether this is different for privileged
3187	 * restores (which the rest of this code handles by pretending
3188	 * umask=0).  I've chosen here to always obey the user's umask for
3189	 * implicit dirs, even if _EXTRACT_PERM was specified.
3190	 */
3191	mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
3192	/* Mode we want on disk during the restore process. */
3193	mode = mode_final;
3194	mode |= MINIMUM_DIR_MODE;
3195	mode &= MAXIMUM_DIR_MODE;
3196	if (mkdir(path, mode) == 0) {
3197		if (mode != mode_final) {
3198			le = new_fixup(a, path);
3199			if (le == NULL)
3200				return (ARCHIVE_FATAL);
3201			le->fixup |=TODO_MODE_BASE;
3202			le->mode = mode_final;
3203		}
3204		return (ARCHIVE_OK);
3205	}
3206
3207	/*
3208	 * Without the following check, a/b/../b/c/d fails at the
3209	 * second visit to 'b', so 'd' can't be created.  Note that we
3210	 * don't add it to the fixup list here, as it's already been
3211	 * added.
3212	 */
3213	if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
3214		return (ARCHIVE_OK);
3215
3216	archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
3217	    path);
3218	return (ARCHIVE_FAILED);
3219}
3220
3221/*
3222 * Note: Although we can skip setting the user id if the desired user
3223 * id matches the current user, we cannot skip setting the group, as
3224 * many systems set the gid based on the containing directory.  So
3225 * we have to perform a chown syscall if we want to set the SGID
3226 * bit.  (The alternative is to stat() and then possibly chown(); it's
3227 * more efficient to skip the stat() and just always chown().)  Note
3228 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
3229 * allows set_mode to skip the stat() check for the GID.
3230 */
3231static int
3232set_ownership(struct archive_write_disk *a)
3233{
3234#if !defined(__CYGWIN__) && !defined(__linux__)
3235/*
3236 * On Linux, a process may have the CAP_CHOWN capability.
3237 * On Windows there is no 'root' user with uid 0.
3238 * Elsewhere we can skip calling chown if we are not root and the desired
3239 * user id does not match the current user.
3240 */
3241	if (a->user_uid != 0 && a->user_uid != a->uid) {
3242		archive_set_error(&a->archive, errno,
3243		    "Can't set UID=%jd", (intmax_t)a->uid);
3244		return (ARCHIVE_WARN);
3245	}
3246#endif
3247
3248#ifdef HAVE_FCHOWN
3249	/* If we have an fd, we can avoid a race. */
3250	if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
3251		/* We've set owner and know uid/gid are correct. */
3252		a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3253		return (ARCHIVE_OK);
3254	}
3255#endif
3256
3257	/* We prefer lchown() but will use chown() if that's all we have. */
3258	/* Of course, if we have neither, this will always fail. */
3259#ifdef HAVE_LCHOWN
3260	if (lchown(a->name, a->uid, a->gid) == 0) {
3261		/* We've set owner and know uid/gid are correct. */
3262		a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3263		return (ARCHIVE_OK);
3264	}
3265#elif HAVE_CHOWN
3266	if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
3267		/* We've set owner and know uid/gid are correct. */
3268		a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3269		return (ARCHIVE_OK);
3270	}
3271#endif
3272
3273	archive_set_error(&a->archive, errno,
3274	    "Can't set user=%jd/group=%jd for %s",
3275	    (intmax_t)a->uid, (intmax_t)a->gid, a->name);
3276	return (ARCHIVE_WARN);
3277}
3278
3279/*
3280 * Note: Returns 0 on success, non-zero on failure.
3281 */
3282static int
3283set_time(int fd, int mode, const char *name,
3284    time_t atime, long atime_nsec,
3285    time_t mtime, long mtime_nsec)
3286{
3287	/* Select the best implementation for this platform. */
3288#if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
3289	/*
3290	 * utimensat() and futimens() are defined in
3291	 * POSIX.1-2008. They support ns resolution and setting times
3292	 * on fds and symlinks.
3293	 */
3294	struct timespec ts[2];
3295	(void)mode; /* UNUSED */
3296	ts[0].tv_sec = atime;
3297	ts[0].tv_nsec = atime_nsec;
3298	ts[1].tv_sec = mtime;
3299	ts[1].tv_nsec = mtime_nsec;
3300	if (fd >= 0)
3301		return futimens(fd, ts);
3302	return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
3303
3304#elif HAVE_UTIMES
3305	/*
3306	 * The utimes()-family functions support ��s-resolution and
3307	 * setting times fds and symlinks.  utimes() is documented as
3308	 * LEGACY by POSIX, futimes() and lutimes() are not described
3309	 * in POSIX.
3310	 */
3311	struct timeval times[2];
3312
3313	times[0].tv_sec = atime;
3314	times[0].tv_usec = atime_nsec / 1000;
3315	times[1].tv_sec = mtime;
3316	times[1].tv_usec = mtime_nsec / 1000;
3317
3318#ifdef HAVE_FUTIMES
3319	if (fd >= 0)
3320		return (futimes(fd, times));
3321#else
3322	(void)fd; /* UNUSED */
3323#endif
3324#ifdef HAVE_LUTIMES
3325	(void)mode; /* UNUSED */
3326	return (lutimes(name, times));
3327#else
3328	if (S_ISLNK(mode))
3329		return (0);
3330	return (utimes(name, times));
3331#endif
3332
3333#elif defined(HAVE_UTIME)
3334	/*
3335	 * utime() is POSIX-standard but only supports 1s resolution and
3336	 * does not support fds or symlinks.
3337	 */
3338	struct utimbuf times;
3339	(void)fd; /* UNUSED */
3340	(void)name; /* UNUSED */
3341	(void)atime_nsec; /* UNUSED */
3342	(void)mtime_nsec; /* UNUSED */
3343	times.actime = atime;
3344	times.modtime = mtime;
3345	if (S_ISLNK(mode))
3346		return (ARCHIVE_OK);
3347	return (utime(name, &times));
3348
3349#else
3350	/*
3351	 * We don't know how to set the time on this platform.
3352	 */
3353	(void)fd; /* UNUSED */
3354	(void)mode; /* UNUSED */
3355	(void)name; /* UNUSED */
3356	(void)atime_nsec; /* UNUSED */
3357	(void)mtime_nsec; /* UNUSED */
3358	return (ARCHIVE_WARN);
3359#endif
3360}
3361
3362#ifdef F_SETTIMES
3363static int
3364set_time_tru64(int fd, int mode, const char *name,
3365    time_t atime, long atime_nsec,
3366    time_t mtime, long mtime_nsec,
3367    time_t ctime, long ctime_nsec)
3368{
3369	struct attr_timbuf tstamp;
3370	tstamp.atime.tv_sec = atime;
3371	tstamp.mtime.tv_sec = mtime;
3372	tstamp.ctime.tv_sec = ctime;
3373#if defined (__hpux) && defined (__ia64)
3374	tstamp.atime.tv_nsec = atime_nsec;
3375	tstamp.mtime.tv_nsec = mtime_nsec;
3376	tstamp.ctime.tv_nsec = ctime_nsec;
3377#else
3378	tstamp.atime.tv_usec = atime_nsec / 1000;
3379	tstamp.mtime.tv_usec = mtime_nsec / 1000;
3380	tstamp.ctime.tv_usec = ctime_nsec / 1000;
3381#endif
3382	return (fcntl(fd,F_SETTIMES,&tstamp));
3383}
3384#endif /* F_SETTIMES */
3385
3386static int
3387set_times(struct archive_write_disk *a,
3388    int fd, int mode, const char *name,
3389    time_t atime, long atime_nanos,
3390    time_t birthtime, long birthtime_nanos,
3391    time_t mtime, long mtime_nanos,
3392    time_t cctime, long ctime_nanos)
3393{
3394	/* Note: set_time doesn't use libarchive return conventions!
3395	 * It uses syscall conventions.  So 0 here instead of ARCHIVE_OK. */
3396	int r1 = 0, r2 = 0;
3397
3398#ifdef F_SETTIMES
3399	 /*
3400	 * on Tru64 try own fcntl first which can restore even the
3401	 * ctime, fall back to default code path below if it fails
3402	 * or if we are not running as root
3403	 */
3404	if (a->user_uid == 0 &&
3405	    set_time_tru64(fd, mode, name,
3406			   atime, atime_nanos, mtime,
3407			   mtime_nanos, cctime, ctime_nanos) == 0) {
3408		return (ARCHIVE_OK);
3409	}
3410#else /* Tru64 */
3411	(void)cctime; /* UNUSED */
3412	(void)ctime_nanos; /* UNUSED */
3413#endif /* Tru64 */
3414
3415#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
3416	/*
3417	 * If you have struct stat.st_birthtime, we assume BSD
3418	 * birthtime semantics, in which {f,l,}utimes() updates
3419	 * birthtime to earliest mtime.  So we set the time twice,
3420	 * first using the birthtime, then using the mtime.  If
3421	 * birthtime == mtime, this isn't necessary, so we skip it.
3422	 * If birthtime > mtime, then this won't work, so we skip it.
3423	 */
3424	if (birthtime < mtime
3425	    || (birthtime == mtime && birthtime_nanos < mtime_nanos))
3426		r1 = set_time(fd, mode, name,
3427			      atime, atime_nanos,
3428			      birthtime, birthtime_nanos);
3429#else
3430	(void)birthtime; /* UNUSED */
3431	(void)birthtime_nanos; /* UNUSED */
3432#endif
3433	r2 = set_time(fd, mode, name,
3434		      atime, atime_nanos,
3435		      mtime, mtime_nanos);
3436	if (r1 != 0 || r2 != 0) {
3437		archive_set_error(&a->archive, errno,
3438				  "Can't restore time");
3439		return (ARCHIVE_WARN);
3440	}
3441	return (ARCHIVE_OK);
3442}
3443
3444static int
3445set_times_from_entry(struct archive_write_disk *a)
3446{
3447	time_t atime, birthtime, mtime, cctime;
3448	long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
3449
3450	/* Suitable defaults. */
3451	atime = birthtime = mtime = cctime = a->start_time;
3452	atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
3453
3454	/* If no time was provided, we're done. */
3455	if (!archive_entry_atime_is_set(a->entry)
3456#if HAVE_STRUCT_STAT_ST_BIRTHTIME
3457	    && !archive_entry_birthtime_is_set(a->entry)
3458#endif
3459	    && !archive_entry_mtime_is_set(a->entry))
3460		return (ARCHIVE_OK);
3461
3462	if (archive_entry_atime_is_set(a->entry)) {
3463		atime = archive_entry_atime(a->entry);
3464		atime_nsec = archive_entry_atime_nsec(a->entry);
3465	}
3466	if (archive_entry_birthtime_is_set(a->entry)) {
3467		birthtime = archive_entry_birthtime(a->entry);
3468		birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
3469	}
3470	if (archive_entry_mtime_is_set(a->entry)) {
3471		mtime = archive_entry_mtime(a->entry);
3472		mtime_nsec = archive_entry_mtime_nsec(a->entry);
3473	}
3474	if (archive_entry_ctime_is_set(a->entry)) {
3475		cctime = archive_entry_ctime(a->entry);
3476		ctime_nsec = archive_entry_ctime_nsec(a->entry);
3477	}
3478
3479	return set_times(a, a->fd, a->mode, a->name,
3480			 atime, atime_nsec,
3481			 birthtime, birthtime_nsec,
3482			 mtime, mtime_nsec,
3483			 cctime, ctime_nsec);
3484}
3485
3486static int
3487set_mode(struct archive_write_disk *a, int mode)
3488{
3489	int r = ARCHIVE_OK;
3490	int r2;
3491	mode &= 07777; /* Strip off file type bits. */
3492
3493	if (a->todo & TODO_SGID_CHECK) {
3494		/*
3495		 * If we don't know the GID is right, we must stat()
3496		 * to verify it.  We can't just check the GID of this
3497		 * process, since systems sometimes set GID from
3498		 * the enclosing dir or based on ACLs.
3499		 */
3500		if ((r = lazy_stat(a)) != ARCHIVE_OK)
3501			return (r);
3502		if (a->pst->st_gid != a->gid) {
3503			mode &= ~ S_ISGID;
3504			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3505				/*
3506				 * This is only an error if you
3507				 * requested owner restore.  If you
3508				 * didn't, we'll try to restore
3509				 * sgid/suid, but won't consider it a
3510				 * problem if we can't.
3511				 */
3512				archive_set_error(&a->archive, -1,
3513				    "Can't restore SGID bit");
3514				r = ARCHIVE_WARN;
3515			}
3516		}
3517		/* While we're here, double-check the UID. */
3518		if (a->pst->st_uid != a->uid
3519		    && (a->todo & TODO_SUID)) {
3520			mode &= ~ S_ISUID;
3521			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3522				archive_set_error(&a->archive, -1,
3523				    "Can't restore SUID bit");
3524				r = ARCHIVE_WARN;
3525			}
3526		}
3527		a->todo &= ~TODO_SGID_CHECK;
3528		a->todo &= ~TODO_SUID_CHECK;
3529	} else if (a->todo & TODO_SUID_CHECK) {
3530		/*
3531		 * If we don't know the UID is right, we can just check
3532		 * the user, since all systems set the file UID from
3533		 * the process UID.
3534		 */
3535		if (a->user_uid != a->uid) {
3536			mode &= ~ S_ISUID;
3537			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3538				archive_set_error(&a->archive, -1,
3539				    "Can't make file SUID");
3540				r = ARCHIVE_WARN;
3541			}
3542		}
3543		a->todo &= ~TODO_SUID_CHECK;
3544	}
3545
3546	if (S_ISLNK(a->mode)) {
3547#ifdef HAVE_LCHMOD
3548		/*
3549		 * If this is a symlink, use lchmod().  If the
3550		 * platform doesn't support lchmod(), just skip it.  A
3551		 * platform that doesn't provide a way to set
3552		 * permissions on symlinks probably ignores
3553		 * permissions on symlinks, so a failure here has no
3554		 * impact.
3555		 */
3556		if (lchmod(a->name, mode) != 0) {
3557			switch (errno) {
3558			case ENOTSUP:
3559			case ENOSYS:
3560#if ENOTSUP != EOPNOTSUPP
3561			case EOPNOTSUPP:
3562#endif
3563				/*
3564				 * if lchmod is defined but the platform
3565				 * doesn't support it, silently ignore
3566				 * error
3567				 */
3568				break;
3569			default:
3570				archive_set_error(&a->archive, errno,
3571				    "Can't set permissions to 0%o", (int)mode);
3572				r = ARCHIVE_WARN;
3573			}
3574		}
3575#endif
3576	} else if (!S_ISDIR(a->mode)) {
3577		/*
3578		 * If it's not a symlink and not a dir, then use
3579		 * fchmod() or chmod(), depending on whether we have
3580		 * an fd.  Dirs get their perms set during the
3581		 * post-extract fixup, which is handled elsewhere.
3582		 */
3583#ifdef HAVE_FCHMOD
3584		if (a->fd >= 0)
3585			r2 = fchmod(a->fd, mode);
3586		else
3587#endif
3588		/* If this platform lacks fchmod(), then
3589		 * we'll just use chmod(). */
3590		r2 = chmod(a->name, mode);
3591
3592		if (r2 != 0) {
3593			archive_set_error(&a->archive, errno,
3594			    "Can't set permissions to 0%o", (int)mode);
3595			r = ARCHIVE_WARN;
3596		}
3597	}
3598	return (r);
3599}
3600
3601static int
3602set_fflags(struct archive_write_disk *a)
3603{
3604	struct fixup_entry *le;
3605	unsigned long	set, clear;
3606	int		r;
3607	mode_t		mode = archive_entry_mode(a->entry);
3608	/*
3609	 * Make 'critical_flags' hold all file flags that can't be
3610	 * immediately restored.  For example, on BSD systems,
3611	 * SF_IMMUTABLE prevents hardlinks from being created, so
3612	 * should not be set until after any hardlinks are created.  To
3613	 * preserve some semblance of portability, this uses #ifdef
3614	 * extensively.  Ugly, but it works.
3615	 *
3616	 * Yes, Virginia, this does create a security race.  It's mitigated
3617	 * somewhat by the practice of creating dirs 0700 until the extract
3618	 * is done, but it would be nice if we could do more than that.
3619	 * People restoring critical file systems should be wary of
3620	 * other programs that might try to muck with files as they're
3621	 * being restored.
3622	 */
3623	const int	critical_flags = 0
3624#ifdef SF_IMMUTABLE
3625	    | SF_IMMUTABLE
3626#endif
3627#ifdef UF_IMMUTABLE
3628	    | UF_IMMUTABLE
3629#endif
3630#ifdef SF_APPEND
3631	    | SF_APPEND
3632#endif
3633#ifdef UF_APPEND
3634	    | UF_APPEND
3635#endif
3636#if defined(FS_APPEND_FL)
3637	    | FS_APPEND_FL
3638#elif defined(EXT2_APPEND_FL)
3639	    | EXT2_APPEND_FL
3640#endif
3641#if defined(FS_IMMUTABLE_FL)
3642	    | FS_IMMUTABLE_FL
3643#elif defined(EXT2_IMMUTABLE_FL)
3644	    | EXT2_IMMUTABLE_FL
3645#endif
3646#ifdef FS_JOURNAL_DATA_FL
3647	    | FS_JOURNAL_DATA_FL
3648#endif
3649	;
3650
3651	if (a->todo & TODO_FFLAGS) {
3652		archive_entry_fflags(a->entry, &set, &clear);
3653
3654		/*
3655		 * The first test encourages the compiler to eliminate
3656		 * all of this if it's not necessary.
3657		 */
3658		if ((critical_flags != 0)  &&  (set & critical_flags)) {
3659			le = current_fixup(a, a->name);
3660			if (le == NULL)
3661				return (ARCHIVE_FATAL);
3662			le->fixup |= TODO_FFLAGS;
3663			le->fflags_set = set;
3664			/* Store the mode if it's not already there. */
3665			if ((le->fixup & TODO_MODE) == 0)
3666				le->mode = mode;
3667		} else {
3668			r = set_fflags_platform(a, a->fd,
3669			    a->name, mode, set, clear);
3670			if (r != ARCHIVE_OK)
3671				return (r);
3672		}
3673	}
3674	return (ARCHIVE_OK);
3675}
3676
3677static int
3678clear_nochange_fflags(struct archive_write_disk *a)
3679{
3680	mode_t		mode = archive_entry_mode(a->entry);
3681	const int nochange_flags = 0
3682#ifdef SF_IMMUTABLE
3683	    | SF_IMMUTABLE
3684#endif
3685#ifdef UF_IMMUTABLE
3686	    | UF_IMMUTABLE
3687#endif
3688#ifdef SF_APPEND
3689	    | SF_APPEND
3690#endif
3691#ifdef UF_APPEND
3692	    | UF_APPEND
3693#endif
3694#ifdef EXT2_APPEND_FL
3695	    | EXT2_APPEND_FL
3696#endif
3697#ifdef EXT2_IMMUTABLE_FL
3698	    | EXT2_IMMUTABLE_FL
3699#endif
3700	;
3701
3702	return (set_fflags_platform(a, a->fd, a->name, mode, 0,
3703	    nochange_flags));
3704}
3705
3706
3707#if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
3708/*
3709 * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
3710 */
3711static int
3712set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3713    mode_t mode, unsigned long set, unsigned long clear)
3714{
3715	int r;
3716	const int sf_mask = 0
3717#ifdef SF_APPEND
3718	    | SF_APPEND
3719#endif
3720#ifdef SF_ARCHIVED
3721	    | SF_ARCHIVED
3722#endif
3723#ifdef SF_IMMUTABLE
3724	    | SF_IMMUTABLE
3725#endif
3726#ifdef SF_NOUNLINK
3727	    | SF_NOUNLINK
3728#endif
3729	;
3730	(void)mode; /* UNUSED */
3731
3732	if (set == 0  && clear == 0)
3733		return (ARCHIVE_OK);
3734
3735	/*
3736	 * XXX Is the stat here really necessary?  Or can I just use
3737	 * the 'set' flags directly?  In particular, I'm not sure
3738	 * about the correct approach if we're overwriting an existing
3739	 * file that already has flags on it. XXX
3740	 */
3741	if ((r = lazy_stat(a)) != ARCHIVE_OK)
3742		return (r);
3743
3744	a->st.st_flags &= ~clear;
3745	a->st.st_flags |= set;
3746
3747	/* Only super-user may change SF_* flags */
3748
3749	if (a->user_uid != 0)
3750		a->st.st_flags &= ~sf_mask;
3751
3752#ifdef HAVE_FCHFLAGS
3753	/* If platform has fchflags() and we were given an fd, use it. */
3754	if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
3755		return (ARCHIVE_OK);
3756#endif
3757	/*
3758	 * If we can't use the fd to set the flags, we'll use the
3759	 * pathname to set flags.  We prefer lchflags() but will use
3760	 * chflags() if we must.
3761	 */
3762#ifdef HAVE_LCHFLAGS
3763	if (lchflags(name, a->st.st_flags) == 0)
3764		return (ARCHIVE_OK);
3765#elif defined(HAVE_CHFLAGS)
3766	if (S_ISLNK(a->st.st_mode)) {
3767		archive_set_error(&a->archive, errno,
3768		    "Can't set file flags on symlink.");
3769		return (ARCHIVE_WARN);
3770	}
3771	if (chflags(name, a->st.st_flags) == 0)
3772		return (ARCHIVE_OK);
3773#endif
3774	archive_set_error(&a->archive, errno,
3775	    "Failed to set file flags");
3776	return (ARCHIVE_WARN);
3777}
3778
3779#elif (defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) && \
3780       defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \
3781      (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && \
3782       defined(HAVE_WORKING_EXT2_IOC_GETFLAGS))
3783/*
3784 * Linux uses ioctl() to read and write file flags.
3785 */
3786static int
3787set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3788    mode_t mode, unsigned long set, unsigned long clear)
3789{
3790	int		 ret;
3791	int		 myfd = fd;
3792	int newflags, oldflags;
3793	/*
3794	 * Linux has no define for the flags that are only settable by
3795	 * the root user.  This code may seem a little complex, but
3796	 * there seem to be some Linux systems that lack these
3797	 * defines. (?)  The code below degrades reasonably gracefully
3798	 * if sf_mask is incomplete.
3799	 */
3800	const int sf_mask = 0
3801#if defined(FS_IMMUTABLE_FL)
3802	    | FS_IMMUTABLE_FL
3803#elif defined(EXT2_IMMUTABLE_FL)
3804	    | EXT2_IMMUTABLE_FL
3805#endif
3806#if defined(FS_APPEND_FL)
3807	    | FS_APPEND_FL
3808#elif defined(EXT2_APPEND_FL)
3809	    | EXT2_APPEND_FL
3810#endif
3811#if defined(FS_JOURNAL_DATA_FL)
3812	    | FS_JOURNAL_DATA_FL
3813#endif
3814	;
3815
3816	if (set == 0 && clear == 0)
3817		return (ARCHIVE_OK);
3818	/* Only regular files and dirs can have flags. */
3819	if (!S_ISREG(mode) && !S_ISDIR(mode))
3820		return (ARCHIVE_OK);
3821
3822	/* If we weren't given an fd, open it ourselves. */
3823	if (myfd < 0) {
3824		myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);
3825		__archive_ensure_cloexec_flag(myfd);
3826	}
3827	if (myfd < 0)
3828		return (ARCHIVE_OK);
3829
3830	/*
3831	 * XXX As above, this would be way simpler if we didn't have
3832	 * to read the current flags from disk. XXX
3833	 */
3834	ret = ARCHIVE_OK;
3835
3836	/* Read the current file flags. */
3837	if (ioctl(myfd,
3838#ifdef FS_IOC_GETFLAGS
3839	    FS_IOC_GETFLAGS,
3840#else
3841	    EXT2_IOC_GETFLAGS,
3842#endif
3843	    &oldflags) < 0)
3844		goto fail;
3845
3846	/* Try setting the flags as given. */
3847	newflags = (oldflags & ~clear) | set;
3848	if (ioctl(myfd,
3849#ifdef FS_IOC_SETFLAGS
3850	    FS_IOC_SETFLAGS,
3851#else
3852	    EXT2_IOC_SETFLAGS,
3853#endif
3854	    &newflags) >= 0)
3855		goto cleanup;
3856	if (errno != EPERM)
3857		goto fail;
3858
3859	/* If we couldn't set all the flags, try again with a subset. */
3860	newflags &= ~sf_mask;
3861	oldflags &= sf_mask;
3862	newflags |= oldflags;
3863	if (ioctl(myfd,
3864#ifdef FS_IOC_SETFLAGS
3865	    FS_IOC_SETFLAGS,
3866#else
3867	    EXT2_IOC_SETFLAGS,
3868#endif
3869	    &newflags) >= 0)
3870		goto cleanup;
3871
3872	/* We couldn't set the flags, so report the failure. */
3873fail:
3874	archive_set_error(&a->archive, errno,
3875	    "Failed to set file flags");
3876	ret = ARCHIVE_WARN;
3877cleanup:
3878	if (fd < 0)
3879		close(myfd);
3880	return (ret);
3881}
3882
3883#else
3884
3885/*
3886 * Of course, some systems have neither BSD chflags() nor Linux' flags
3887 * support through ioctl().
3888 */
3889static int
3890set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3891    mode_t mode, unsigned long set, unsigned long clear)
3892{
3893	(void)a; /* UNUSED */
3894	(void)fd; /* UNUSED */
3895	(void)name; /* UNUSED */
3896	(void)mode; /* UNUSED */
3897	(void)set; /* UNUSED */
3898	(void)clear; /* UNUSED */
3899	return (ARCHIVE_OK);
3900}
3901
3902#endif /* __linux */
3903
3904#ifndef HAVE_COPYFILE_H
3905/* Default is to simply drop Mac extended metadata. */
3906static int
3907set_mac_metadata(struct archive_write_disk *a, const char *pathname,
3908		 const void *metadata, size_t metadata_size)
3909{
3910	(void)a; /* UNUSED */
3911	(void)pathname; /* UNUSED */
3912	(void)metadata; /* UNUSED */
3913	(void)metadata_size; /* UNUSED */
3914	return (ARCHIVE_OK);
3915}
3916
3917static int
3918fixup_appledouble(struct archive_write_disk *a, const char *pathname)
3919{
3920	(void)a; /* UNUSED */
3921	(void)pathname; /* UNUSED */
3922	return (ARCHIVE_OK);
3923}
3924#else
3925
3926/*
3927 * On Mac OS, we use copyfile() to unpack the metadata and
3928 * apply it to the target file.
3929 */
3930
3931#if defined(HAVE_SYS_XATTR_H)
3932static int
3933copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
3934{
3935	ssize_t xattr_size;
3936	char *xattr_names = NULL, *xattr_val = NULL;
3937	int ret = ARCHIVE_OK, xattr_i;
3938
3939	xattr_size = flistxattr(tmpfd, NULL, 0, 0);
3940	if (xattr_size == -1) {
3941		archive_set_error(&a->archive, errno,
3942		    "Failed to read metadata(xattr)");
3943		ret = ARCHIVE_WARN;
3944		goto exit_xattr;
3945	}
3946	xattr_names = malloc(xattr_size);
3947	if (xattr_names == NULL) {
3948		archive_set_error(&a->archive, ENOMEM,
3949		    "Can't allocate memory for metadata(xattr)");
3950		ret = ARCHIVE_FATAL;
3951		goto exit_xattr;
3952	}
3953	xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
3954	if (xattr_size == -1) {
3955		archive_set_error(&a->archive, errno,
3956		    "Failed to read metadata(xattr)");
3957		ret = ARCHIVE_WARN;
3958		goto exit_xattr;
3959	}
3960	for (xattr_i = 0; xattr_i < xattr_size;
3961	    xattr_i += strlen(xattr_names + xattr_i) + 1) {
3962		char *xattr_val_saved;
3963		ssize_t s;
3964		int f;
3965
3966		s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
3967		if (s == -1) {
3968			archive_set_error(&a->archive, errno,
3969			    "Failed to get metadata(xattr)");
3970			ret = ARCHIVE_WARN;
3971			goto exit_xattr;
3972		}
3973		xattr_val_saved = xattr_val;
3974		xattr_val = realloc(xattr_val, s);
3975		if (xattr_val == NULL) {
3976			archive_set_error(&a->archive, ENOMEM,
3977			    "Failed to get metadata(xattr)");
3978			ret = ARCHIVE_WARN;
3979			free(xattr_val_saved);
3980			goto exit_xattr;
3981		}
3982		s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
3983		if (s == -1) {
3984			archive_set_error(&a->archive, errno,
3985			    "Failed to get metadata(xattr)");
3986			ret = ARCHIVE_WARN;
3987			goto exit_xattr;
3988		}
3989		f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
3990		if (f == -1) {
3991			archive_set_error(&a->archive, errno,
3992			    "Failed to get metadata(xattr)");
3993			ret = ARCHIVE_WARN;
3994			goto exit_xattr;
3995		}
3996	}
3997exit_xattr:
3998	free(xattr_names);
3999	free(xattr_val);
4000	return (ret);
4001}
4002#endif
4003
4004static int
4005copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
4006{
4007#ifndef HAVE_SYS_ACL_H
4008	return 0;
4009#else
4010	acl_t acl, dfacl = NULL;
4011	int acl_r, ret = ARCHIVE_OK;
4012
4013	acl = acl_get_fd(tmpfd);
4014	if (acl == NULL) {
4015		if (errno == ENOENT)
4016			/* There are not any ACLs. */
4017			return (ret);
4018		archive_set_error(&a->archive, errno,
4019		    "Failed to get metadata(acl)");
4020		ret = ARCHIVE_WARN;
4021		goto exit_acl;
4022	}
4023	dfacl = acl_dup(acl);
4024	acl_r = acl_set_fd(dffd, dfacl);
4025	if (acl_r == -1) {
4026		archive_set_error(&a->archive, errno,
4027		    "Failed to get metadata(acl)");
4028		ret = ARCHIVE_WARN;
4029		goto exit_acl;
4030	}
4031exit_acl:
4032	if (acl)
4033		acl_free(acl);
4034	if (dfacl)
4035		acl_free(dfacl);
4036	return (ret);
4037#endif
4038}
4039
4040static int
4041create_tempdatafork(struct archive_write_disk *a, const char *pathname)
4042{
4043	struct archive_string tmpdatafork;
4044	int tmpfd;
4045
4046	archive_string_init(&tmpdatafork);
4047	archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
4048	tmpfd = mkstemp(tmpdatafork.s);
4049	if (tmpfd < 0) {
4050		archive_set_error(&a->archive, errno,
4051		    "Failed to mkstemp");
4052		archive_string_free(&tmpdatafork);
4053		return (-1);
4054	}
4055	if (copyfile(pathname, tmpdatafork.s, 0,
4056	    COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4057	    | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4058		archive_set_error(&a->archive, errno,
4059		    "Failed to restore metadata");
4060		close(tmpfd);
4061		tmpfd = -1;
4062	}
4063	unlink(tmpdatafork.s);
4064	archive_string_free(&tmpdatafork);
4065	return (tmpfd);
4066}
4067
4068static int
4069copy_metadata(struct archive_write_disk *a, const char *metadata,
4070    const char *datafork, int datafork_compressed)
4071{
4072	int ret = ARCHIVE_OK;
4073
4074	if (datafork_compressed) {
4075		int dffd, tmpfd;
4076
4077		tmpfd = create_tempdatafork(a, metadata);
4078		if (tmpfd == -1)
4079			return (ARCHIVE_WARN);
4080
4081		/*
4082		 * Do not open the data fork compressed by HFS+ compression
4083		 * with at least a writing mode(O_RDWR or O_WRONLY). it
4084		 * makes the data fork uncompressed.
4085		 */
4086		dffd = open(datafork, 0);
4087		if (dffd == -1) {
4088			archive_set_error(&a->archive, errno,
4089			    "Failed to open the data fork for metadata");
4090			close(tmpfd);
4091			return (ARCHIVE_WARN);
4092		}
4093
4094#if defined(HAVE_SYS_XATTR_H)
4095		ret = copy_xattrs(a, tmpfd, dffd);
4096		if (ret == ARCHIVE_OK)
4097#endif
4098			ret = copy_acls(a, tmpfd, dffd);
4099		close(tmpfd);
4100		close(dffd);
4101	} else {
4102		if (copyfile(metadata, datafork, 0,
4103		    COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4104		    | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4105			archive_set_error(&a->archive, errno,
4106			    "Failed to restore metadata");
4107			ret = ARCHIVE_WARN;
4108		}
4109	}
4110	return (ret);
4111}
4112
4113static int
4114set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4115		 const void *metadata, size_t metadata_size)
4116{
4117	struct archive_string tmp;
4118	ssize_t written;
4119	int fd;
4120	int ret = ARCHIVE_OK;
4121
4122	/* This would be simpler if copyfile() could just accept the
4123	 * metadata as a block of memory; then we could sidestep this
4124	 * silly dance of writing the data to disk just so that
4125	 * copyfile() can read it back in again. */
4126	archive_string_init(&tmp);
4127	archive_strcpy(&tmp, pathname);
4128	archive_strcat(&tmp, ".XXXXXX");
4129	fd = mkstemp(tmp.s);
4130
4131	if (fd < 0) {
4132		archive_set_error(&a->archive, errno,
4133				  "Failed to restore metadata");
4134		archive_string_free(&tmp);
4135		return (ARCHIVE_WARN);
4136	}
4137	written = write(fd, metadata, metadata_size);
4138	close(fd);
4139	if ((size_t)written != metadata_size) {
4140		archive_set_error(&a->archive, errno,
4141				  "Failed to restore metadata");
4142		ret = ARCHIVE_WARN;
4143	} else {
4144		int compressed;
4145
4146#if defined(UF_COMPRESSED)
4147		if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
4148		    (ret = lazy_stat(a)) == ARCHIVE_OK)
4149			compressed = a->st.st_flags & UF_COMPRESSED;
4150		else
4151#endif
4152			compressed = 0;
4153		ret = copy_metadata(a, tmp.s, pathname, compressed);
4154	}
4155	unlink(tmp.s);
4156	archive_string_free(&tmp);
4157	return (ret);
4158}
4159
4160static int
4161fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4162{
4163	char buff[8];
4164	struct stat st;
4165	const char *p;
4166	struct archive_string datafork;
4167	int fd = -1, ret = ARCHIVE_OK;
4168
4169	archive_string_init(&datafork);
4170	/* Check if the current file name is a type of the resource
4171	 * fork file. */
4172	p = strrchr(pathname, '/');
4173	if (p == NULL)
4174		p = pathname;
4175	else
4176		p++;
4177	if (p[0] != '.' || p[1] != '_')
4178		goto skip_appledouble;
4179
4180	/*
4181	 * Check if the data fork file exists.
4182	 *
4183	 * TODO: Check if this write disk object has handled it.
4184	 */
4185	archive_strncpy(&datafork, pathname, p - pathname);
4186	archive_strcat(&datafork, p + 2);
4187	if (lstat(datafork.s, &st) == -1 ||
4188	    (st.st_mode & AE_IFMT) != AE_IFREG)
4189		goto skip_appledouble;
4190
4191	/*
4192	 * Check if the file is in the AppleDouble form.
4193	 */
4194	fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
4195	__archive_ensure_cloexec_flag(fd);
4196	if (fd == -1) {
4197		archive_set_error(&a->archive, errno,
4198		    "Failed to open a restoring file");
4199		ret = ARCHIVE_WARN;
4200		goto skip_appledouble;
4201	}
4202	if (read(fd, buff, 8) == -1) {
4203		archive_set_error(&a->archive, errno,
4204		    "Failed to read a restoring file");
4205		close(fd);
4206		ret = ARCHIVE_WARN;
4207		goto skip_appledouble;
4208	}
4209	close(fd);
4210	/* Check AppleDouble Magic Code. */
4211	if (archive_be32dec(buff) != 0x00051607)
4212		goto skip_appledouble;
4213	/* Check AppleDouble Version. */
4214	if (archive_be32dec(buff+4) != 0x00020000)
4215		goto skip_appledouble;
4216
4217	ret = copy_metadata(a, pathname, datafork.s,
4218#if defined(UF_COMPRESSED)
4219	    st.st_flags & UF_COMPRESSED);
4220#else
4221	    0);
4222#endif
4223	if (ret == ARCHIVE_OK) {
4224		unlink(pathname);
4225		ret = ARCHIVE_EOF;
4226	}
4227skip_appledouble:
4228	archive_string_free(&datafork);
4229	return (ret);
4230}
4231#endif
4232
4233#if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
4234/*
4235 * Restore extended attributes -  Linux, Darwin and AIX implementations:
4236 * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
4237 */
4238static int
4239set_xattrs(struct archive_write_disk *a)
4240{
4241	struct archive_entry *entry = a->entry;
4242	struct archive_string errlist;
4243	int ret = ARCHIVE_OK;
4244	int i = archive_entry_xattr_reset(entry);
4245	short fail = 0;
4246
4247	archive_string_init(&errlist);
4248
4249	while (i--) {
4250		const char *name;
4251		const void *value;
4252		size_t size;
4253		int e;
4254
4255		archive_entry_xattr_next(entry, &name, &value, &size);
4256
4257		if (name == NULL)
4258			continue;
4259#if ARCHIVE_XATTR_LINUX
4260		/* Linux: quietly skip POSIX.1e ACL extended attributes */
4261		if (strncmp(name, "system.", 7) == 0 &&
4262		   (strcmp(name + 7, "posix_acl_access") == 0 ||
4263		    strcmp(name + 7, "posix_acl_default") == 0))
4264			continue;
4265		if (strncmp(name, "trusted.SGI_", 12) == 0 &&
4266		   (strcmp(name + 12, "ACL_DEFAULT") == 0 ||
4267		    strcmp(name + 12, "ACL_FILE") == 0))
4268			continue;
4269
4270		/* Linux: xfsroot namespace is obsolete and unsupported */
4271		if (strncmp(name, "xfsroot.", 8) == 0) {
4272			fail = 1;
4273			archive_strcat(&errlist, name);
4274			archive_strappend_char(&errlist, ' ');
4275			continue;
4276		}
4277#endif
4278
4279		if (a->fd >= 0) {
4280#if ARCHIVE_XATTR_LINUX
4281			e = fsetxattr(a->fd, name, value, size, 0);
4282#elif ARCHIVE_XATTR_DARWIN
4283			e = fsetxattr(a->fd, name, value, size, 0, 0);
4284#elif ARCHIVE_XATTR_AIX
4285			e = fsetea(a->fd, name, value, size, 0);
4286#endif
4287		} else {
4288#if ARCHIVE_XATTR_LINUX
4289			e = lsetxattr(archive_entry_pathname(entry),
4290			    name, value, size, 0);
4291#elif ARCHIVE_XATTR_DARWIN
4292			e = setxattr(archive_entry_pathname(entry),
4293			    name, value, size, 0, XATTR_NOFOLLOW);
4294#elif ARCHIVE_XATTR_AIX
4295			e = lsetea(archive_entry_pathname(entry),
4296			    name, value, size, 0);
4297#endif
4298		}
4299		if (e == -1) {
4300			ret = ARCHIVE_WARN;
4301			archive_strcat(&errlist, name);
4302			archive_strappend_char(&errlist, ' ');
4303			if (errno != ENOTSUP && errno != ENOSYS)
4304				fail = 1;
4305		}
4306	}
4307
4308	if (ret == ARCHIVE_WARN) {
4309		if (fail && errlist.length > 0) {
4310			errlist.length--;
4311			errlist.s[errlist.length] = '\0';
4312			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4313			    "Cannot restore extended attributes: %s",
4314			    errlist.s);
4315		} else
4316			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4317			    "Cannot restore extended "
4318			    "attributes on this file system.");
4319	}
4320
4321	archive_string_free(&errlist);
4322	return (ret);
4323}
4324#elif ARCHIVE_XATTR_FREEBSD
4325/*
4326 * Restore extended attributes -  FreeBSD implementation
4327 */
4328static int
4329set_xattrs(struct archive_write_disk *a)
4330{
4331	struct archive_entry *entry = a->entry;
4332	struct archive_string errlist;
4333	int ret = ARCHIVE_OK;
4334	int i = archive_entry_xattr_reset(entry);
4335	short fail = 0;
4336
4337	archive_string_init(&errlist);
4338
4339	while (i--) {
4340		const char *name;
4341		const void *value;
4342		size_t size;
4343		archive_entry_xattr_next(entry, &name, &value, &size);
4344		if (name != NULL) {
4345			ssize_t e;
4346			int namespace;
4347
4348			if (strncmp(name, "user.", 5) == 0) {
4349				/* "user." attributes go to user namespace */
4350				name += 5;
4351				namespace = EXTATTR_NAMESPACE_USER;
4352			} else {
4353				/* Other namespaces are unsupported */
4354				archive_strcat(&errlist, name);
4355				archive_strappend_char(&errlist, ' ');
4356				fail = 1;
4357				ret = ARCHIVE_WARN;
4358				continue;
4359			}
4360
4361			if (a->fd >= 0) {
4362				e = extattr_set_fd(a->fd, namespace, name,
4363				    value, size);
4364			} else {
4365				e = extattr_set_link(
4366				    archive_entry_pathname(entry), namespace,
4367				    name, value, size);
4368			}
4369			if (e != (ssize_t)size) {
4370				archive_strcat(&errlist, name);
4371				archive_strappend_char(&errlist, ' ');
4372				ret = ARCHIVE_WARN;
4373				if (errno != ENOTSUP && errno != ENOSYS)
4374					fail = 1;
4375			}
4376		}
4377	}
4378
4379	if (ret == ARCHIVE_WARN) {
4380		if (fail && errlist.length > 0) {
4381			errlist.length--;
4382			errlist.s[errlist.length] = '\0';
4383
4384			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4385			    "Cannot restore extended attributes: %s",
4386			    errlist.s);
4387		} else
4388			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4389			    "Cannot restore extended "
4390			    "attributes on this file system.");
4391	}
4392
4393	archive_string_free(&errlist);
4394	return (ret);
4395}
4396#else
4397/*
4398 * Restore extended attributes - stub implementation for unsupported systems
4399 */
4400static int
4401set_xattrs(struct archive_write_disk *a)
4402{
4403	static int warning_done = 0;
4404
4405	/* If there aren't any extended attributes, then it's okay not
4406	 * to extract them, otherwise, issue a single warning. */
4407	if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
4408		warning_done = 1;
4409		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4410		    "Cannot restore extended attributes on this system");
4411		return (ARCHIVE_WARN);
4412	}
4413	/* Warning was already emitted; suppress further warnings. */
4414	return (ARCHIVE_OK);
4415}
4416#endif
4417
4418/*
4419 * Test if file on disk is older than entry.
4420 */
4421static int
4422older(struct stat *st, struct archive_entry *entry)
4423{
4424	/* First, test the seconds and return if we have a definite answer. */
4425	/* Definitely older. */
4426	if (to_int64_time(st->st_mtime) < to_int64_time(archive_entry_mtime(entry)))
4427		return (1);
4428	/* Definitely younger. */
4429	if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry)))
4430		return (0);
4431	/* If this platform supports fractional seconds, try those. */
4432#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
4433	/* Definitely older. */
4434	if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
4435		return (1);
4436#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
4437	/* Definitely older. */
4438	if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
4439		return (1);
4440#elif HAVE_STRUCT_STAT_ST_MTIME_N
4441	/* older. */
4442	if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
4443		return (1);
4444#elif HAVE_STRUCT_STAT_ST_UMTIME
4445	/* older. */
4446	if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
4447		return (1);
4448#elif HAVE_STRUCT_STAT_ST_MTIME_USEC
4449	/* older. */
4450	if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
4451		return (1);
4452#else
4453	/* This system doesn't have high-res timestamps. */
4454#endif
4455	/* Same age or newer, so not older. */
4456	return (0);
4457}
4458
4459#ifndef ARCHIVE_ACL_SUPPORT
4460int
4461archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
4462    struct archive_acl *abstract_acl, __LA_MODE_T mode)
4463{
4464	(void)a; /* UNUSED */
4465	(void)fd; /* UNUSED */
4466	(void)name; /* UNUSED */
4467	(void)abstract_acl; /* UNUSED */
4468	(void)mode; /* UNUSED */
4469	return (ARCHIVE_OK);
4470}
4471#endif
4472
4473#endif /* !_WIN32 || __CYGWIN__ */
4474
4475