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