archive_write_disk_posix.c revision 238909
1/*-
2 * Copyright (c) 2003-2010 Tim Kientzle
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer
10 *    in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include "archive_platform.h"
28__FBSDID("$FreeBSD$");
29
30#if !defined(_WIN32) || defined(__CYGWIN__)
31
32#ifdef HAVE_SYS_TYPES_H
33#include <sys/types.h>
34#endif
35#ifdef HAVE_SYS_EXTATTR_H
36#include <sys/extattr.h>
37#endif
38#ifdef HAVE_SYS_XATTR_H
39#include <sys/xattr.h>
40#endif
41#ifdef HAVE_SYS_EA_H
42#include <sys/ea.h>
43#endif
44#ifdef HAVE_ATTR_XATTR_H
45#include <attr/xattr.h>
46#endif
47#ifdef HAVE_SYS_IOCTL_H
48#include <sys/ioctl.h>
49#endif
50#ifdef HAVE_SYS_STAT_H
51#include <sys/stat.h>
52#endif
53#ifdef HAVE_SYS_TIME_H
54#include <sys/time.h>
55#endif
56#ifdef HAVE_SYS_UTIME_H
57#include <sys/utime.h>
58#endif
59#ifdef HAVE_COPYFILE_H
60#include <copyfile.h>
61#endif
62#ifdef HAVE_ERRNO_H
63#include <errno.h>
64#endif
65#ifdef HAVE_FCNTL_H
66#include <fcntl.h>
67#endif
68#ifdef HAVE_GRP_H
69#include <grp.h>
70#endif
71#ifdef HAVE_LANGINFO_H
72#include <langinfo.h>
73#endif
74#ifdef HAVE_LINUX_FS_H
75#include <linux/fs.h>	/* for Linux file flags */
76#endif
77/*
78 * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
79 * As the include guards don't agree, the order of include is important.
80 */
81#ifdef HAVE_LINUX_EXT2_FS_H
82#include <linux/ext2_fs.h>	/* for Linux file flags */
83#endif
84#if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
85#include <ext2fs/ext2_fs.h>	/* Linux file flags, broken on Cygwin */
86#endif
87#ifdef HAVE_LIMITS_H
88#include <limits.h>
89#endif
90#ifdef HAVE_PWD_H
91#include <pwd.h>
92#endif
93#include <stdio.h>
94#ifdef HAVE_STDLIB_H
95#include <stdlib.h>
96#endif
97#ifdef HAVE_STRING_H
98#include <string.h>
99#endif
100#ifdef HAVE_UNISTD_H
101#include <unistd.h>
102#endif
103#ifdef HAVE_UTIME_H
104#include <utime.h>
105#endif
106#ifdef F_GETTIMES /* Tru64 specific */
107#include <sys/fcntl1.h>
108#endif
109
110#if __APPLE__
111#include <TargetConditionals.h>
112#if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H
113#include <quarantine.h>
114#define HAVE_QUARANTINE 1
115#endif
116#endif
117
118/* TODO: Support Mac OS 'quarantine' feature.  This is really just a
119 * standard tag to mark files that have been downloaded as "tainted".
120 * On Mac OS, we should mark the extracted files as tainted if the
121 * archive being read was tainted.  Windows has a similar feature; we
122 * should investigate ways to support this generically. */
123
124#include "archive.h"
125#include "archive_acl_private.h"
126#include "archive_string.h"
127#include "archive_entry.h"
128#include "archive_private.h"
129#include "archive_write_disk_private.h"
130
131#ifndef O_BINARY
132#define O_BINARY 0
133#endif
134
135struct fixup_entry {
136	struct fixup_entry	*next;
137	struct archive_acl	 acl;
138	mode_t			 mode;
139	int64_t			 atime;
140	int64_t                  birthtime;
141	int64_t			 mtime;
142	int64_t			 ctime;
143	unsigned long		 atime_nanos;
144	unsigned long            birthtime_nanos;
145	unsigned long		 mtime_nanos;
146	unsigned long		 ctime_nanos;
147	unsigned long		 fflags_set;
148	size_t			 mac_metadata_size;
149	void			*mac_metadata;
150	int			 fixup; /* bitmask of what needs fixing */
151	char			*name;
152};
153
154/*
155 * We use a bitmask to track which operations remain to be done for
156 * this file.  In particular, this helps us avoid unnecessary
157 * operations when it's possible to take care of one step as a
158 * side-effect of another.  For example, mkdir() can specify the mode
159 * for the newly-created object but symlink() cannot.  This means we
160 * can skip chmod() if mkdir() succeeded, but we must explicitly
161 * chmod() if we're trying to create a directory that already exists
162 * (mkdir() failed) or if we're restoring a symlink.  Similarly, we
163 * need to verify UID/GID before trying to restore SUID/SGID bits;
164 * that verification can occur explicitly through a stat() call or
165 * implicitly because of a successful chown() call.
166 */
167#define	TODO_MODE_FORCE		0x40000000
168#define	TODO_MODE_BASE		0x20000000
169#define	TODO_SUID		0x10000000
170#define	TODO_SUID_CHECK		0x08000000
171#define	TODO_SGID		0x04000000
172#define	TODO_SGID_CHECK		0x02000000
173#define	TODO_MODE		(TODO_MODE_BASE|TODO_SUID|TODO_SGID)
174#define	TODO_TIMES		ARCHIVE_EXTRACT_TIME
175#define	TODO_OWNER		ARCHIVE_EXTRACT_OWNER
176#define	TODO_FFLAGS		ARCHIVE_EXTRACT_FFLAGS
177#define	TODO_ACLS		ARCHIVE_EXTRACT_ACL
178#define	TODO_XATTR		ARCHIVE_EXTRACT_XATTR
179#define	TODO_MAC_METADATA	ARCHIVE_EXTRACT_MAC_METADATA
180
181struct archive_write_disk {
182	struct archive	archive;
183
184	mode_t			 user_umask;
185	struct fixup_entry	*fixup_list;
186	struct fixup_entry	*current_fixup;
187	int64_t			 user_uid;
188	int			 skip_file_set;
189	int64_t			 skip_file_dev;
190	int64_t			 skip_file_ino;
191	time_t			 start_time;
192
193	int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid);
194	void  (*cleanup_gid)(void *private);
195	void			*lookup_gid_data;
196	int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid);
197	void  (*cleanup_uid)(void *private);
198	void			*lookup_uid_data;
199
200	/*
201	 * Full path of last file to satisfy symlink checks.
202	 */
203	struct archive_string	path_safe;
204
205	/*
206	 * Cached stat data from disk for the current entry.
207	 * If this is valid, pst points to st.  Otherwise,
208	 * pst is null.
209	 */
210	struct stat		 st;
211	struct stat		*pst;
212
213	/* Information about the object being restored right now. */
214	struct archive_entry	*entry; /* Entry being extracted. */
215	char			*name; /* Name of entry, possibly edited. */
216	struct archive_string	 _name_data; /* backing store for 'name' */
217	/* Tasks remaining for this object. */
218	int			 todo;
219	/* Tasks deferred until end-of-archive. */
220	int			 deferred;
221	/* Options requested by the client. */
222	int			 flags;
223	/* Handle for the file we're restoring. */
224	int			 fd;
225	/* Current offset for writing data to the file. */
226	int64_t			 offset;
227	/* Last offset actually written to disk. */
228	int64_t			 fd_offset;
229	/* Total bytes actually written to files. */
230	int64_t			 total_bytes_written;
231	/* Maximum size of file, -1 if unknown. */
232	int64_t			 filesize;
233	/* Dir we were in before this restore; only for deep paths. */
234	int			 restore_pwd;
235	/* Mode we should use for this entry; affected by _PERM and umask. */
236	mode_t			 mode;
237	/* UID/GID to use in restoring this entry. */
238	int64_t			 uid;
239	int64_t			 gid;
240};
241
242/*
243 * Default mode for dirs created automatically (will be modified by umask).
244 * Note that POSIX specifies 0777 for implicitly-created dirs, "modified
245 * by the process' file creation mask."
246 */
247#define	DEFAULT_DIR_MODE 0777
248/*
249 * Dir modes are restored in two steps:  During the extraction, the permissions
250 * in the archive are modified to match the following limits.  During
251 * the post-extract fixup pass, the permissions from the archive are
252 * applied.
253 */
254#define	MINIMUM_DIR_MODE 0700
255#define	MAXIMUM_DIR_MODE 0775
256
257static int	check_symlinks(struct archive_write_disk *);
258static int	create_filesystem_object(struct archive_write_disk *);
259static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname);
260#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
261static void	edit_deep_directories(struct archive_write_disk *ad);
262#endif
263static int	cleanup_pathname(struct archive_write_disk *);
264static int	create_dir(struct archive_write_disk *, char *);
265static int	create_parent_dir(struct archive_write_disk *, char *);
266static int	older(struct stat *, struct archive_entry *);
267static int	restore_entry(struct archive_write_disk *);
268static int	set_mac_metadata(struct archive_write_disk *, const char *,
269				 const void *, size_t);
270static int	set_xattrs(struct archive_write_disk *);
271static int	set_fflags(struct archive_write_disk *);
272static int	set_fflags_platform(struct archive_write_disk *, int fd,
273		    const char *name, mode_t mode,
274		    unsigned long fflags_set, unsigned long fflags_clear);
275static int	set_ownership(struct archive_write_disk *);
276static int	set_mode(struct archive_write_disk *, int mode);
277static int	set_time(int, int, const char *, time_t, long, time_t, long);
278static int	set_times(struct archive_write_disk *, int, int, const char *,
279		    time_t, long, time_t, long, time_t, long, time_t, long);
280static int	set_times_from_entry(struct archive_write_disk *);
281static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
282static ssize_t	write_data_block(struct archive_write_disk *,
283		    const char *, size_t);
284
285static struct archive_vtable *archive_write_disk_vtable(void);
286
287static int	_archive_write_disk_close(struct archive *);
288static int	_archive_write_disk_free(struct archive *);
289static int	_archive_write_disk_header(struct archive *, struct archive_entry *);
290static int64_t	_archive_write_disk_filter_bytes(struct archive *, int);
291static int	_archive_write_disk_finish_entry(struct archive *);
292static ssize_t	_archive_write_disk_data(struct archive *, const void *, size_t);
293static ssize_t	_archive_write_disk_data_block(struct archive *, const void *, size_t, int64_t);
294
295static int
296lazy_stat(struct archive_write_disk *a)
297{
298	if (a->pst != NULL) {
299		/* Already have stat() data available. */
300		return (ARCHIVE_OK);
301	}
302#ifdef HAVE_FSTAT
303	if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
304		a->pst = &a->st;
305		return (ARCHIVE_OK);
306	}
307#endif
308	/*
309	 * XXX At this point, symlinks should not be hit, otherwise
310	 * XXX a race occurred.  Do we want to check explicitly for that?
311	 */
312	if (lstat(a->name, &a->st) == 0) {
313		a->pst = &a->st;
314		return (ARCHIVE_OK);
315	}
316	archive_set_error(&a->archive, errno, "Couldn't stat file");
317	return (ARCHIVE_WARN);
318}
319
320static struct archive_vtable *
321archive_write_disk_vtable(void)
322{
323	static struct archive_vtable av;
324	static int inited = 0;
325
326	if (!inited) {
327		av.archive_close = _archive_write_disk_close;
328		av.archive_filter_bytes = _archive_write_disk_filter_bytes;
329		av.archive_free = _archive_write_disk_free;
330		av.archive_write_header = _archive_write_disk_header;
331		av.archive_write_finish_entry
332		    = _archive_write_disk_finish_entry;
333		av.archive_write_data = _archive_write_disk_data;
334		av.archive_write_data_block = _archive_write_disk_data_block;
335		inited = 1;
336	}
337	return (&av);
338}
339
340static int64_t
341_archive_write_disk_filter_bytes(struct archive *_a, int n)
342{
343	struct archive_write_disk *a = (struct archive_write_disk *)_a;
344	(void)n; /* UNUSED */
345	if (n == -1 || n == 0)
346		return (a->total_bytes_written);
347	return (-1);
348}
349
350
351int
352archive_write_disk_set_options(struct archive *_a, int flags)
353{
354	struct archive_write_disk *a = (struct archive_write_disk *)_a;
355
356	a->flags = flags;
357	return (ARCHIVE_OK);
358}
359
360
361/*
362 * Extract this entry to disk.
363 *
364 * TODO: Validate hardlinks.  According to the standards, we're
365 * supposed to check each extracted hardlink and squawk if it refers
366 * to a file that we didn't restore.  I'm not entirely convinced this
367 * is a good idea, but more importantly: Is there any way to validate
368 * hardlinks without keeping a complete list of filenames from the
369 * entire archive?? Ugh.
370 *
371 */
372static int
373_archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
374{
375	struct archive_write_disk *a = (struct archive_write_disk *)_a;
376	struct fixup_entry *fe;
377	int ret, r;
378
379	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
380	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
381	    "archive_write_disk_header");
382	archive_clear_error(&a->archive);
383	if (a->archive.state & ARCHIVE_STATE_DATA) {
384		r = _archive_write_disk_finish_entry(&a->archive);
385		if (r == ARCHIVE_FATAL)
386			return (r);
387	}
388
389	/* Set up for this particular entry. */
390	a->pst = NULL;
391	a->current_fixup = NULL;
392	a->deferred = 0;
393	if (a->entry) {
394		archive_entry_free(a->entry);
395		a->entry = NULL;
396	}
397	a->entry = archive_entry_clone(entry);
398	a->fd = -1;
399	a->fd_offset = 0;
400	a->offset = 0;
401	a->restore_pwd = -1;
402	a->uid = a->user_uid;
403	a->mode = archive_entry_mode(a->entry);
404	if (archive_entry_size_is_set(a->entry))
405		a->filesize = archive_entry_size(a->entry);
406	else
407		a->filesize = -1;
408	archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
409	a->name = a->_name_data.s;
410	archive_clear_error(&a->archive);
411
412	/*
413	 * Clean up the requested path.  This is necessary for correct
414	 * dir restores; the dir restore logic otherwise gets messed
415	 * up by nonsense like "dir/.".
416	 */
417	ret = cleanup_pathname(a);
418	if (ret != ARCHIVE_OK)
419		return (ret);
420
421	/*
422	 * Query the umask so we get predictable mode settings.
423	 * This gets done on every call to _write_header in case the
424	 * user edits their umask during the extraction for some
425	 * reason.
426	 */
427	umask(a->user_umask = umask(0));
428
429	/* Figure out what we need to do for this entry. */
430	a->todo = TODO_MODE_BASE;
431	if (a->flags & ARCHIVE_EXTRACT_PERM) {
432		a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
433		/*
434		 * SGID requires an extra "check" step because we
435		 * cannot easily predict the GID that the system will
436		 * assign.  (Different systems assign GIDs to files
437		 * based on a variety of criteria, including process
438		 * credentials and the gid of the enclosing
439		 * directory.)  We can only restore the SGID bit if
440		 * the file has the right GID, and we only know the
441		 * GID if we either set it (see set_ownership) or if
442		 * we've actually called stat() on the file after it
443		 * was restored.  Since there are several places at
444		 * which we might verify the GID, we need a TODO bit
445		 * to keep track.
446		 */
447		if (a->mode & S_ISGID)
448			a->todo |= TODO_SGID | TODO_SGID_CHECK;
449		/*
450		 * Verifying the SUID is simpler, but can still be
451		 * done in multiple ways, hence the separate "check" bit.
452		 */
453		if (a->mode & S_ISUID)
454			a->todo |= TODO_SUID | TODO_SUID_CHECK;
455	} else {
456		/*
457		 * User didn't request full permissions, so don't
458		 * restore SUID, SGID bits and obey umask.
459		 */
460		a->mode &= ~S_ISUID;
461		a->mode &= ~S_ISGID;
462		a->mode &= ~S_ISVTX;
463		a->mode &= ~a->user_umask;
464	}
465	if (a->flags & ARCHIVE_EXTRACT_OWNER)
466		a->todo |= TODO_OWNER;
467	if (a->flags & ARCHIVE_EXTRACT_TIME)
468		a->todo |= TODO_TIMES;
469	if (a->flags & ARCHIVE_EXTRACT_ACL) {
470		if (archive_entry_filetype(a->entry) == AE_IFDIR)
471			a->deferred |= TODO_ACLS;
472		else
473			a->todo |= TODO_ACLS;
474	}
475	if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
476		if (archive_entry_filetype(a->entry) == AE_IFDIR)
477			a->deferred |= TODO_MAC_METADATA;
478		else
479			a->todo |= TODO_MAC_METADATA;
480	}
481	if (a->flags & ARCHIVE_EXTRACT_XATTR)
482		a->todo |= TODO_XATTR;
483	if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
484		a->todo |= TODO_FFLAGS;
485	if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
486		ret = check_symlinks(a);
487		if (ret != ARCHIVE_OK)
488			return (ret);
489	}
490#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
491	/* If path exceeds PATH_MAX, shorten the path. */
492	edit_deep_directories(a);
493#endif
494
495	ret = restore_entry(a);
496
497	/*
498	 * TODO: There are rumours that some extended attributes must
499	 * be restored before file data is written.  If this is true,
500	 * then we either need to write all extended attributes both
501	 * before and after restoring the data, or find some rule for
502	 * determining which must go first and which last.  Due to the
503	 * many ways people are using xattrs, this may prove to be an
504	 * intractable problem.
505	 */
506
507#ifdef HAVE_FCHDIR
508	/* If we changed directory above, restore it here. */
509	if (a->restore_pwd >= 0) {
510		r = fchdir(a->restore_pwd);
511		if (r != 0) {
512			archive_set_error(&a->archive, errno, "chdir() failure");
513			ret = ARCHIVE_FATAL;
514		}
515		close(a->restore_pwd);
516		a->restore_pwd = -1;
517	}
518#endif
519
520	/*
521	 * Fixup uses the unedited pathname from archive_entry_pathname(),
522	 * because it is relative to the base dir and the edited path
523	 * might be relative to some intermediate dir as a result of the
524	 * deep restore logic.
525	 */
526	if (a->deferred & TODO_MODE) {
527		fe = current_fixup(a, archive_entry_pathname(entry));
528		fe->fixup |= TODO_MODE_BASE;
529		fe->mode = a->mode;
530	}
531
532	if ((a->deferred & TODO_TIMES)
533		&& (archive_entry_mtime_is_set(entry)
534		    || archive_entry_atime_is_set(entry))) {
535		fe = current_fixup(a, archive_entry_pathname(entry));
536		fe->mode = a->mode;
537		fe->fixup |= TODO_TIMES;
538		if (archive_entry_atime_is_set(entry)) {
539			fe->atime = archive_entry_atime(entry);
540			fe->atime_nanos = archive_entry_atime_nsec(entry);
541		} else {
542			/* If atime is unset, use start time. */
543			fe->atime = a->start_time;
544			fe->atime_nanos = 0;
545		}
546		if (archive_entry_mtime_is_set(entry)) {
547			fe->mtime = archive_entry_mtime(entry);
548			fe->mtime_nanos = archive_entry_mtime_nsec(entry);
549		} else {
550			/* If mtime is unset, use start time. */
551			fe->mtime = a->start_time;
552			fe->mtime_nanos = 0;
553		}
554		if (archive_entry_birthtime_is_set(entry)) {
555			fe->birthtime = archive_entry_birthtime(entry);
556			fe->birthtime_nanos = archive_entry_birthtime_nsec(entry);
557		} else {
558			/* If birthtime is unset, use mtime. */
559			fe->birthtime = fe->mtime;
560			fe->birthtime_nanos = fe->mtime_nanos;
561		}
562	}
563
564	if (a->deferred & TODO_ACLS) {
565		fe = current_fixup(a, archive_entry_pathname(entry));
566		fe->fixup |= TODO_ACLS;
567		archive_acl_copy(&fe->acl, archive_entry_acl(entry));
568	}
569
570	if (a->deferred & TODO_MAC_METADATA) {
571		const void *metadata;
572		size_t metadata_size;
573		metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
574		if (metadata != NULL && metadata_size > 0) {
575			fe = current_fixup(a, archive_entry_pathname(entry));
576			fe->mac_metadata = malloc(metadata_size);
577			if (fe->mac_metadata != NULL) {
578				memcpy(fe->mac_metadata, metadata, metadata_size);
579				fe->mac_metadata_size = metadata_size;
580				fe->fixup |= TODO_MAC_METADATA;
581			}
582		}
583	}
584
585	if (a->deferred & TODO_FFLAGS) {
586		fe = current_fixup(a, archive_entry_pathname(entry));
587		fe->fixup |= TODO_FFLAGS;
588		/* TODO: Complete this.. defer fflags from below. */
589	}
590
591	/* We've created the object and are ready to pour data into it. */
592	if (ret >= ARCHIVE_WARN)
593		a->archive.state = ARCHIVE_STATE_DATA;
594	/*
595	 * If it's not open, tell our client not to try writing.
596	 * In particular, dirs, links, etc, don't get written to.
597	 */
598	if (a->fd < 0) {
599		archive_entry_set_size(entry, 0);
600		a->filesize = 0;
601	}
602
603	return (ret);
604}
605
606int
607archive_write_disk_set_skip_file(struct archive *_a, int64_t d, int64_t i)
608{
609	struct archive_write_disk *a = (struct archive_write_disk *)_a;
610	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
611	    ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
612	a->skip_file_set = 1;
613	a->skip_file_dev = d;
614	a->skip_file_ino = i;
615	return (ARCHIVE_OK);
616}
617
618static ssize_t
619write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
620{
621	uint64_t start_size = size;
622	ssize_t bytes_written = 0;
623	ssize_t block_size = 0, bytes_to_write;
624
625	if (size == 0)
626		return (ARCHIVE_OK);
627
628	if (a->filesize == 0 || a->fd < 0) {
629		archive_set_error(&a->archive, 0,
630		    "Attempt to write to an empty file");
631		return (ARCHIVE_WARN);
632	}
633
634	if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
635#if HAVE_STRUCT_STAT_ST_BLKSIZE
636		int r;
637		if ((r = lazy_stat(a)) != ARCHIVE_OK)
638			return (r);
639		block_size = a->pst->st_blksize;
640#else
641		/* XXX TODO XXX Is there a more appropriate choice here ? */
642		/* This needn't match the filesystem allocation size. */
643		block_size = 16*1024;
644#endif
645	}
646
647	/* If this write would run beyond the file size, truncate it. */
648	if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
649		start_size = size = (size_t)(a->filesize - a->offset);
650
651	/* Write the data. */
652	while (size > 0) {
653		if (block_size == 0) {
654			bytes_to_write = size;
655		} else {
656			/* We're sparsifying the file. */
657			const char *p, *end;
658			int64_t block_end;
659
660			/* Skip leading zero bytes. */
661			for (p = buff, end = buff + size; p < end; ++p) {
662				if (*p != '\0')
663					break;
664			}
665			a->offset += p - buff;
666			size -= p - buff;
667			buff = p;
668			if (size == 0)
669				break;
670
671			/* Calculate next block boundary after offset. */
672			block_end
673			    = (a->offset / block_size + 1) * block_size;
674
675			/* If the adjusted write would cross block boundary,
676			 * truncate it to the block boundary. */
677			bytes_to_write = size;
678			if (a->offset + bytes_to_write > block_end)
679				bytes_to_write = block_end - a->offset;
680		}
681		/* Seek if necessary to the specified offset. */
682		if (a->offset != a->fd_offset) {
683			if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
684				archive_set_error(&a->archive, errno,
685				    "Seek failed");
686				return (ARCHIVE_FATAL);
687			}
688			a->fd_offset = a->offset;
689		}
690		bytes_written = write(a->fd, buff, bytes_to_write);
691		if (bytes_written < 0) {
692			archive_set_error(&a->archive, errno, "Write failed");
693			return (ARCHIVE_WARN);
694		}
695		buff += bytes_written;
696		size -= bytes_written;
697		a->total_bytes_written += bytes_written;
698		a->offset += bytes_written;
699		a->fd_offset = a->offset;
700	}
701	return (start_size - size);
702}
703
704static ssize_t
705_archive_write_disk_data_block(struct archive *_a,
706    const void *buff, size_t size, int64_t offset)
707{
708	struct archive_write_disk *a = (struct archive_write_disk *)_a;
709	ssize_t r;
710
711	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
712	    ARCHIVE_STATE_DATA, "archive_write_data_block");
713
714	a->offset = offset;
715	r = write_data_block(a, buff, size);
716	if (r < ARCHIVE_OK)
717		return (r);
718	if ((size_t)r < size) {
719		archive_set_error(&a->archive, 0,
720		    "Write request too large");
721		return (ARCHIVE_WARN);
722	}
723	return (ARCHIVE_OK);
724}
725
726static ssize_t
727_archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
728{
729	struct archive_write_disk *a = (struct archive_write_disk *)_a;
730
731	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
732	    ARCHIVE_STATE_DATA, "archive_write_data");
733
734	return (write_data_block(a, buff, size));
735}
736
737static int
738_archive_write_disk_finish_entry(struct archive *_a)
739{
740	struct archive_write_disk *a = (struct archive_write_disk *)_a;
741	int ret = ARCHIVE_OK;
742
743	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
744	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
745	    "archive_write_finish_entry");
746	if (a->archive.state & ARCHIVE_STATE_HEADER)
747		return (ARCHIVE_OK);
748	archive_clear_error(&a->archive);
749
750	/* Pad or truncate file to the right size. */
751	if (a->fd < 0) {
752		/* There's no file. */
753	} else if (a->filesize < 0) {
754		/* File size is unknown, so we can't set the size. */
755	} else if (a->fd_offset == a->filesize) {
756		/* Last write ended at exactly the filesize; we're done. */
757		/* Hopefully, this is the common case. */
758	} else {
759#if HAVE_FTRUNCATE
760		if (ftruncate(a->fd, a->filesize) == -1 &&
761		    a->filesize == 0) {
762			archive_set_error(&a->archive, errno,
763			    "File size could not be restored");
764			return (ARCHIVE_FAILED);
765		}
766#endif
767		/*
768		 * Not all platforms implement the XSI option to
769		 * extend files via ftruncate.  Stat() the file again
770		 * to see what happened.
771		 */
772		a->pst = NULL;
773		if ((ret = lazy_stat(a)) != ARCHIVE_OK)
774			return (ret);
775		/* We can use lseek()/write() to extend the file if
776		 * ftruncate didn't work or isn't available. */
777		if (a->st.st_size < a->filesize) {
778			const char nul = '\0';
779			if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) {
780				archive_set_error(&a->archive, errno,
781				    "Seek failed");
782				return (ARCHIVE_FATAL);
783			}
784			if (write(a->fd, &nul, 1) < 0) {
785				archive_set_error(&a->archive, errno,
786				    "Write to restore size failed");
787				return (ARCHIVE_FATAL);
788			}
789			a->pst = NULL;
790		}
791	}
792
793	/* Restore metadata. */
794
795	/*
796	 * Look up the "real" UID only if we're going to need it.
797	 * TODO: the TODO_SGID condition can be dropped here, can't it?
798	 */
799	if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
800		a->uid = archive_write_disk_uid(&a->archive,
801		    archive_entry_uname(a->entry),
802		    archive_entry_uid(a->entry));
803	}
804	/* Look up the "real" GID only if we're going to need it. */
805	/* TODO: the TODO_SUID condition can be dropped here, can't it? */
806	if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
807		a->gid = archive_write_disk_gid(&a->archive,
808		    archive_entry_gname(a->entry),
809		    archive_entry_gid(a->entry));
810	 }
811
812	/*
813	 * Restore ownership before set_mode tries to restore suid/sgid
814	 * bits.  If we set the owner, we know what it is and can skip
815	 * a stat() call to examine the ownership of the file on disk.
816	 */
817	if (a->todo & TODO_OWNER)
818		ret = set_ownership(a);
819
820	/*
821	 * set_mode must precede ACLs on systems such as Solaris and
822	 * FreeBSD where setting the mode implicitly clears extended ACLs
823	 */
824	if (a->todo & TODO_MODE) {
825		int r2 = set_mode(a, a->mode);
826		if (r2 < ret) ret = r2;
827	}
828
829	/*
830	 * Security-related extended attributes (such as
831	 * security.capability on Linux) have to be restored last,
832	 * since they're implicitly removed by other file changes.
833	 */
834	if (a->todo & TODO_XATTR) {
835		int r2 = set_xattrs(a);
836		if (r2 < ret) ret = r2;
837	}
838
839	/*
840	 * Some flags prevent file modification; they must be restored after
841	 * file contents are written.
842	 */
843	if (a->todo & TODO_FFLAGS) {
844		int r2 = set_fflags(a);
845		if (r2 < ret) ret = r2;
846	}
847
848	/*
849	 * Time must follow most other metadata;
850	 * otherwise atime will get changed.
851	 */
852	if (a->todo & TODO_TIMES) {
853		int r2 = set_times_from_entry(a);
854		if (r2 < ret) ret = r2;
855	}
856
857	/*
858	 * Mac extended metadata includes ACLs.
859	 */
860	if (a->todo & TODO_MAC_METADATA) {
861		const void *metadata;
862		size_t metadata_size;
863		metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
864		if (metadata != NULL && metadata_size > 0) {
865			int r2 = set_mac_metadata(a, archive_entry_pathname(a->entry), metadata, metadata_size);
866			if (r2 < ret) ret = r2;
867		}
868	}
869
870	/*
871	 * ACLs must be restored after timestamps because there are
872	 * ACLs that prevent attribute changes (including time).
873	 */
874	if (a->todo & TODO_ACLS) {
875		int r2 = archive_write_disk_set_acls(&a->archive, a->fd,
876				  archive_entry_pathname(a->entry),
877				  archive_entry_acl(a->entry));
878		if (r2 < ret) ret = r2;
879	}
880
881	/* If there's an fd, we can close it now. */
882	if (a->fd >= 0) {
883		close(a->fd);
884		a->fd = -1;
885	}
886	/* If there's an entry, we can release it now. */
887	if (a->entry) {
888		archive_entry_free(a->entry);
889		a->entry = NULL;
890	}
891	a->archive.state = ARCHIVE_STATE_HEADER;
892	return (ret);
893}
894
895int
896archive_write_disk_set_group_lookup(struct archive *_a,
897    void *private_data,
898    int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid),
899    void (*cleanup_gid)(void *private))
900{
901	struct archive_write_disk *a = (struct archive_write_disk *)_a;
902	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
903	    ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
904
905	if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
906		(a->cleanup_gid)(a->lookup_gid_data);
907
908	a->lookup_gid = lookup_gid;
909	a->cleanup_gid = cleanup_gid;
910	a->lookup_gid_data = private_data;
911	return (ARCHIVE_OK);
912}
913
914int
915archive_write_disk_set_user_lookup(struct archive *_a,
916    void *private_data,
917    int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
918    void (*cleanup_uid)(void *private))
919{
920	struct archive_write_disk *a = (struct archive_write_disk *)_a;
921	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
922	    ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
923
924	if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
925		(a->cleanup_uid)(a->lookup_uid_data);
926
927	a->lookup_uid = lookup_uid;
928	a->cleanup_uid = cleanup_uid;
929	a->lookup_uid_data = private_data;
930	return (ARCHIVE_OK);
931}
932
933int64_t
934archive_write_disk_gid(struct archive *_a, const char *name, int64_t id)
935{
936       struct archive_write_disk *a = (struct archive_write_disk *)_a;
937       archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
938           ARCHIVE_STATE_ANY, "archive_write_disk_gid");
939       if (a->lookup_gid)
940               return (a->lookup_gid)(a->lookup_gid_data, name, id);
941       return (id);
942}
943
944int64_t
945archive_write_disk_uid(struct archive *_a, const char *name, int64_t id)
946{
947	struct archive_write_disk *a = (struct archive_write_disk *)_a;
948	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
949	    ARCHIVE_STATE_ANY, "archive_write_disk_uid");
950	if (a->lookup_uid)
951		return (a->lookup_uid)(a->lookup_uid_data, name, id);
952	return (id);
953}
954
955/*
956 * Create a new archive_write_disk object and initialize it with global state.
957 */
958struct archive *
959archive_write_disk_new(void)
960{
961	struct archive_write_disk *a;
962
963	a = (struct archive_write_disk *)malloc(sizeof(*a));
964	if (a == NULL)
965		return (NULL);
966	memset(a, 0, sizeof(*a));
967	a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
968	/* We're ready to write a header immediately. */
969	a->archive.state = ARCHIVE_STATE_HEADER;
970	a->archive.vtable = archive_write_disk_vtable();
971	a->start_time = time(NULL);
972	/* Query and restore the umask. */
973	umask(a->user_umask = umask(0));
974#ifdef HAVE_GETEUID
975	a->user_uid = geteuid();
976#endif /* HAVE_GETEUID */
977	if (archive_string_ensure(&a->path_safe, 512) == NULL) {
978		free(a);
979		return (NULL);
980	}
981	return (&a->archive);
982}
983
984
985/*
986 * If pathname is longer than PATH_MAX, chdir to a suitable
987 * intermediate dir and edit the path down to a shorter suffix.  Note
988 * that this routine never returns an error; if the chdir() attempt
989 * fails for any reason, we just go ahead with the long pathname.  The
990 * object creation is likely to fail, but any error will get handled
991 * at that time.
992 */
993#if defined(HAVE_FCHDIR) && defined(PATH_MAX)
994static void
995edit_deep_directories(struct archive_write_disk *a)
996{
997	int ret;
998	char *tail = a->name;
999
1000	/* If path is short, avoid the open() below. */
1001	if (strlen(tail) <= PATH_MAX)
1002		return;
1003
1004	/* Try to record our starting dir. */
1005	a->restore_pwd = open(".", O_RDONLY | O_BINARY);
1006	if (a->restore_pwd < 0)
1007		return;
1008
1009	/* As long as the path is too long... */
1010	while (strlen(tail) > PATH_MAX) {
1011		/* Locate a dir prefix shorter than PATH_MAX. */
1012		tail += PATH_MAX - 8;
1013		while (tail > a->name && *tail != '/')
1014			tail--;
1015		/* Exit if we find a too-long path component. */
1016		if (tail <= a->name)
1017			return;
1018		/* Create the intermediate dir and chdir to it. */
1019		*tail = '\0'; /* Terminate dir portion */
1020		ret = create_dir(a, a->name);
1021		if (ret == ARCHIVE_OK && chdir(a->name) != 0)
1022			ret = ARCHIVE_FAILED;
1023		*tail = '/'; /* Restore the / we removed. */
1024		if (ret != ARCHIVE_OK)
1025			return;
1026		tail++;
1027		/* The chdir() succeeded; we've now shortened the path. */
1028		a->name = tail;
1029	}
1030	return;
1031}
1032#endif
1033
1034/*
1035 * The main restore function.
1036 */
1037static int
1038restore_entry(struct archive_write_disk *a)
1039{
1040	int ret = ARCHIVE_OK, en;
1041
1042	if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
1043		/*
1044		 * TODO: Fix this.  Apparently, there are platforms
1045		 * that still allow root to hose the entire filesystem
1046		 * by unlinking a dir.  The S_ISDIR() test above
1047		 * prevents us from using unlink() here if the new
1048		 * object is a dir, but that doesn't mean the old
1049		 * object isn't a dir.
1050		 */
1051		if (unlink(a->name) == 0) {
1052			/* We removed it, reset cached stat. */
1053			a->pst = NULL;
1054		} else if (errno == ENOENT) {
1055			/* File didn't exist, that's just as good. */
1056		} else if (rmdir(a->name) == 0) {
1057			/* It was a dir, but now it's gone. */
1058			a->pst = NULL;
1059		} else {
1060			/* We tried, but couldn't get rid of it. */
1061			archive_set_error(&a->archive, errno,
1062			    "Could not unlink");
1063			return(ARCHIVE_FAILED);
1064		}
1065	}
1066
1067	/* Try creating it first; if this fails, we'll try to recover. */
1068	en = create_filesystem_object(a);
1069
1070	if ((en == ENOTDIR || en == ENOENT)
1071	    && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
1072		/* If the parent dir doesn't exist, try creating it. */
1073		create_parent_dir(a, a->name);
1074		/* Now try to create the object again. */
1075		en = create_filesystem_object(a);
1076	}
1077
1078	if ((en == EISDIR || en == EEXIST)
1079	    && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1080		/* If we're not overwriting, we're done. */
1081		archive_entry_unset_size(a->entry);
1082		return (ARCHIVE_OK);
1083	}
1084
1085	/*
1086	 * Some platforms return EISDIR if you call
1087	 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
1088	 * return EEXIST.  POSIX is ambiguous, requiring EISDIR
1089	 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
1090	 * on an existing item.
1091	 */
1092	if (en == EISDIR) {
1093		/* A dir is in the way of a non-dir, rmdir it. */
1094		if (rmdir(a->name) != 0) {
1095			archive_set_error(&a->archive, errno,
1096			    "Can't remove already-existing dir");
1097			return (ARCHIVE_FAILED);
1098		}
1099		a->pst = NULL;
1100		/* Try again. */
1101		en = create_filesystem_object(a);
1102	} else if (en == EEXIST) {
1103		/*
1104		 * We know something is in the way, but we don't know what;
1105		 * we need to find out before we go any further.
1106		 */
1107		int r = 0;
1108		/*
1109		 * The SECURE_SYMLINKS logic has already removed a
1110		 * symlink to a dir if the client wants that.  So
1111		 * follow the symlink if we're creating a dir.
1112		 */
1113		if (S_ISDIR(a->mode))
1114			r = stat(a->name, &a->st);
1115		/*
1116		 * If it's not a dir (or it's a broken symlink),
1117		 * then don't follow it.
1118		 */
1119		if (r != 0 || !S_ISDIR(a->mode))
1120			r = lstat(a->name, &a->st);
1121		if (r != 0) {
1122			archive_set_error(&a->archive, errno,
1123			    "Can't stat existing object");
1124			return (ARCHIVE_FAILED);
1125		}
1126
1127		/*
1128		 * NO_OVERWRITE_NEWER doesn't apply to directories.
1129		 */
1130		if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
1131		    &&  !S_ISDIR(a->st.st_mode)) {
1132			if (!older(&(a->st), a->entry)) {
1133				archive_entry_unset_size(a->entry);
1134				return (ARCHIVE_OK);
1135			}
1136		}
1137
1138		/* If it's our archive, we're done. */
1139		if (a->skip_file_set &&
1140		    a->st.st_dev == (dev_t)a->skip_file_dev &&
1141		    a->st.st_ino == (ino_t)a->skip_file_ino) {
1142			archive_set_error(&a->archive, 0,
1143			    "Refusing to overwrite archive");
1144			return (ARCHIVE_FAILED);
1145		}
1146
1147		if (!S_ISDIR(a->st.st_mode)) {
1148			/* A non-dir is in the way, unlink it. */
1149			if (unlink(a->name) != 0) {
1150				archive_set_error(&a->archive, errno,
1151				    "Can't unlink already-existing object");
1152				return (ARCHIVE_FAILED);
1153			}
1154			a->pst = NULL;
1155			/* Try again. */
1156			en = create_filesystem_object(a);
1157		} else if (!S_ISDIR(a->mode)) {
1158			/* A dir is in the way of a non-dir, rmdir it. */
1159			if (rmdir(a->name) != 0) {
1160				archive_set_error(&a->archive, errno,
1161				    "Can't replace existing directory with non-directory");
1162				return (ARCHIVE_FAILED);
1163			}
1164			/* Try again. */
1165			en = create_filesystem_object(a);
1166		} else {
1167			/*
1168			 * There's a dir in the way of a dir.  Don't
1169			 * waste time with rmdir()/mkdir(), just fix
1170			 * up the permissions on the existing dir.
1171			 * Note that we don't change perms on existing
1172			 * dirs unless _EXTRACT_PERM is specified.
1173			 */
1174			if ((a->mode != a->st.st_mode)
1175			    && (a->todo & TODO_MODE_FORCE))
1176				a->deferred |= (a->todo & TODO_MODE);
1177			/* Ownership doesn't need deferred fixup. */
1178			en = 0; /* Forget the EEXIST. */
1179		}
1180	}
1181
1182	if (en) {
1183		/* Everything failed; give up here. */
1184		archive_set_error(&a->archive, en, "Can't create '%s'",
1185		    a->name);
1186		return (ARCHIVE_FAILED);
1187	}
1188
1189	a->pst = NULL; /* Cached stat data no longer valid. */
1190	return (ret);
1191}
1192
1193/*
1194 * Returns 0 if creation succeeds, or else returns errno value from
1195 * the failed system call.   Note:  This function should only ever perform
1196 * a single system call.
1197 */
1198static int
1199create_filesystem_object(struct archive_write_disk *a)
1200{
1201	/* Create the entry. */
1202	const char *linkname;
1203	mode_t final_mode, mode;
1204	int r;
1205
1206	/* We identify hard/symlinks according to the link names. */
1207	/* Since link(2) and symlink(2) don't handle modes, we're done here. */
1208	linkname = archive_entry_hardlink(a->entry);
1209	if (linkname != NULL) {
1210#if !HAVE_LINK
1211		return (EPERM);
1212#else
1213		r = link(linkname, a->name) ? errno : 0;
1214		/*
1215		 * New cpio and pax formats allow hardlink entries
1216		 * to carry data, so we may have to open the file
1217		 * for hardlink entries.
1218		 *
1219		 * If the hardlink was successfully created and
1220		 * the archive doesn't have carry data for it,
1221		 * consider it to be non-authoritative for meta data.
1222		 * This is consistent with GNU tar and BSD pax.
1223		 * If the hardlink does carry data, let the last
1224		 * archive entry decide ownership.
1225		 */
1226		if (r == 0 && a->filesize <= 0) {
1227			a->todo = 0;
1228			a->deferred = 0;
1229		} else if (r == 0 && a->filesize > 0) {
1230			a->fd = open(a->name, O_WRONLY | O_TRUNC | O_BINARY);
1231			if (a->fd < 0)
1232				r = errno;
1233		}
1234		return (r);
1235#endif
1236	}
1237	linkname = archive_entry_symlink(a->entry);
1238	if (linkname != NULL) {
1239#if HAVE_SYMLINK
1240		return symlink(linkname, a->name) ? errno : 0;
1241#else
1242		return (EPERM);
1243#endif
1244	}
1245
1246	/*
1247	 * The remaining system calls all set permissions, so let's
1248	 * try to take advantage of that to avoid an extra chmod()
1249	 * call.  (Recall that umask is set to zero right now!)
1250	 */
1251
1252	/* Mode we want for the final restored object (w/o file type bits). */
1253	final_mode = a->mode & 07777;
1254	/*
1255	 * The mode that will actually be restored in this step.  Note
1256	 * that SUID, SGID, etc, require additional work to ensure
1257	 * security, so we never restore them at this point.
1258	 */
1259	mode = final_mode & 0777 & a->user_umask;
1260
1261	switch (a->mode & AE_IFMT) {
1262	default:
1263		/* POSIX requires that we fall through here. */
1264		/* FALLTHROUGH */
1265	case AE_IFREG:
1266		a->fd = open(a->name,
1267		    O_WRONLY | O_CREAT | O_EXCL | O_BINARY, mode);
1268		r = (a->fd < 0);
1269		break;
1270	case AE_IFCHR:
1271#ifdef HAVE_MKNOD
1272		/* Note: we use AE_IFCHR for the case label, and
1273		 * S_IFCHR for the mknod() call.  This is correct.  */
1274		r = mknod(a->name, mode | S_IFCHR,
1275		    archive_entry_rdev(a->entry));
1276		break;
1277#else
1278		/* TODO: Find a better way to warn about our inability
1279		 * to restore a char device node. */
1280		return (EINVAL);
1281#endif /* HAVE_MKNOD */
1282	case AE_IFBLK:
1283#ifdef HAVE_MKNOD
1284		r = mknod(a->name, mode | S_IFBLK,
1285		    archive_entry_rdev(a->entry));
1286		break;
1287#else
1288		/* TODO: Find a better way to warn about our inability
1289		 * to restore a block device node. */
1290		return (EINVAL);
1291#endif /* HAVE_MKNOD */
1292	case AE_IFDIR:
1293		mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
1294		r = mkdir(a->name, mode);
1295		if (r == 0) {
1296			/* Defer setting dir times. */
1297			a->deferred |= (a->todo & TODO_TIMES);
1298			a->todo &= ~TODO_TIMES;
1299			/* Never use an immediate chmod(). */
1300			/* We can't avoid the chmod() entirely if EXTRACT_PERM
1301			 * because of SysV SGID inheritance. */
1302			if ((mode != final_mode)
1303			    || (a->flags & ARCHIVE_EXTRACT_PERM))
1304				a->deferred |= (a->todo & TODO_MODE);
1305			a->todo &= ~TODO_MODE;
1306		}
1307		break;
1308	case AE_IFIFO:
1309#ifdef HAVE_MKFIFO
1310		r = mkfifo(a->name, mode);
1311		break;
1312#else
1313		/* TODO: Find a better way to warn about our inability
1314		 * to restore a fifo. */
1315		return (EINVAL);
1316#endif /* HAVE_MKFIFO */
1317	}
1318
1319	/* All the system calls above set errno on failure. */
1320	if (r)
1321		return (errno);
1322
1323	/* If we managed to set the final mode, we've avoided a chmod(). */
1324	if (mode == final_mode)
1325		a->todo &= ~TODO_MODE;
1326	return (0);
1327}
1328
1329/*
1330 * Cleanup function for archive_extract.  Mostly, this involves processing
1331 * the fixup list, which is used to address a number of problems:
1332 *   * Dir permissions might prevent us from restoring a file in that
1333 *     dir, so we restore the dir with minimum 0700 permissions first,
1334 *     then correct the mode at the end.
1335 *   * Similarly, the act of restoring a file touches the directory
1336 *     and changes the timestamp on the dir, so we have to touch-up dir
1337 *     timestamps at the end as well.
1338 *   * Some file flags can interfere with the restore by, for example,
1339 *     preventing the creation of hardlinks to those files.
1340 *   * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
1341 *
1342 * Note that tar/cpio do not require that archives be in a particular
1343 * order; there is no way to know when the last file has been restored
1344 * within a directory, so there's no way to optimize the memory usage
1345 * here by fixing up the directory any earlier than the
1346 * end-of-archive.
1347 *
1348 * XXX TODO: Directory ACLs should be restored here, for the same
1349 * reason we set directory perms here. XXX
1350 */
1351static int
1352_archive_write_disk_close(struct archive *_a)
1353{
1354	struct archive_write_disk *a = (struct archive_write_disk *)_a;
1355	struct fixup_entry *next, *p;
1356	int ret;
1357
1358	archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1359	    ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1360	    "archive_write_disk_close");
1361	ret = _archive_write_disk_finish_entry(&a->archive);
1362
1363	/* Sort dir list so directories are fixed up in depth-first order. */
1364	p = sort_dir_list(a->fixup_list);
1365
1366	while (p != NULL) {
1367		a->pst = NULL; /* Mark stat cache as out-of-date. */
1368		if (p->fixup & TODO_TIMES) {
1369			set_times(a, -1, p->mode, p->name,
1370			    p->atime, p->atime_nanos,
1371			    p->birthtime, p->birthtime_nanos,
1372			    p->mtime, p->mtime_nanos,
1373			    p->ctime, p->ctime_nanos);
1374		}
1375		if (p->fixup & TODO_MODE_BASE)
1376			chmod(p->name, p->mode);
1377		if (p->fixup & TODO_ACLS)
1378			archive_write_disk_set_acls(&a->archive,
1379						    -1, p->name, &p->acl);
1380		if (p->fixup & TODO_FFLAGS)
1381			set_fflags_platform(a, -1, p->name,
1382			    p->mode, p->fflags_set, 0);
1383		if (p->fixup & TODO_MAC_METADATA)
1384			set_mac_metadata(a, p->name, p->mac_metadata,
1385					 p->mac_metadata_size);
1386		next = p->next;
1387		archive_acl_clear(&p->acl);
1388		free(p->mac_metadata);
1389		free(p->name);
1390		free(p);
1391		p = next;
1392	}
1393	a->fixup_list = NULL;
1394	return (ret);
1395}
1396
1397static int
1398_archive_write_disk_free(struct archive *_a)
1399{
1400	struct archive_write_disk *a;
1401	int ret;
1402	if (_a == NULL)
1403		return (ARCHIVE_OK);
1404	archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
1405	    ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
1406	a = (struct archive_write_disk *)_a;
1407	ret = _archive_write_disk_close(&a->archive);
1408	archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
1409	archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
1410	if (a->entry)
1411		archive_entry_free(a->entry);
1412	archive_string_free(&a->_name_data);
1413	archive_string_free(&a->archive.error_string);
1414	archive_string_free(&a->path_safe);
1415	a->archive.magic = 0;
1416	__archive_clean(&a->archive);
1417	free(a);
1418	return (ret);
1419}
1420
1421/*
1422 * Simple O(n log n) merge sort to order the fixup list.  In
1423 * particular, we want to restore dir timestamps depth-first.
1424 */
1425static struct fixup_entry *
1426sort_dir_list(struct fixup_entry *p)
1427{
1428	struct fixup_entry *a, *b, *t;
1429
1430	if (p == NULL)
1431		return (NULL);
1432	/* A one-item list is already sorted. */
1433	if (p->next == NULL)
1434		return (p);
1435
1436	/* Step 1: split the list. */
1437	t = p;
1438	a = p->next->next;
1439	while (a != NULL) {
1440		/* Step a twice, t once. */
1441		a = a->next;
1442		if (a != NULL)
1443			a = a->next;
1444		t = t->next;
1445	}
1446	/* Now, t is at the mid-point, so break the list here. */
1447	b = t->next;
1448	t->next = NULL;
1449	a = p;
1450
1451	/* Step 2: Recursively sort the two sub-lists. */
1452	a = sort_dir_list(a);
1453	b = sort_dir_list(b);
1454
1455	/* Step 3: Merge the returned lists. */
1456	/* Pick the first element for the merged list. */
1457	if (strcmp(a->name, b->name) > 0) {
1458		t = p = a;
1459		a = a->next;
1460	} else {
1461		t = p = b;
1462		b = b->next;
1463	}
1464
1465	/* Always put the later element on the list first. */
1466	while (a != NULL && b != NULL) {
1467		if (strcmp(a->name, b->name) > 0) {
1468			t->next = a;
1469			a = a->next;
1470		} else {
1471			t->next = b;
1472			b = b->next;
1473		}
1474		t = t->next;
1475	}
1476
1477	/* Only one list is non-empty, so just splice it on. */
1478	if (a != NULL)
1479		t->next = a;
1480	if (b != NULL)
1481		t->next = b;
1482
1483	return (p);
1484}
1485
1486/*
1487 * Returns a new, initialized fixup entry.
1488 *
1489 * TODO: Reduce the memory requirements for this list by using a tree
1490 * structure rather than a simple list of names.
1491 */
1492static struct fixup_entry *
1493new_fixup(struct archive_write_disk *a, const char *pathname)
1494{
1495	struct fixup_entry *fe;
1496
1497	fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
1498	if (fe == NULL)
1499		return (NULL);
1500	fe->next = a->fixup_list;
1501	a->fixup_list = fe;
1502	fe->fixup = 0;
1503	fe->name = strdup(pathname);
1504	return (fe);
1505}
1506
1507/*
1508 * Returns a fixup structure for the current entry.
1509 */
1510static struct fixup_entry *
1511current_fixup(struct archive_write_disk *a, const char *pathname)
1512{
1513	if (a->current_fixup == NULL)
1514		a->current_fixup = new_fixup(a, pathname);
1515	return (a->current_fixup);
1516}
1517
1518/* TODO: Make this work. */
1519/*
1520 * TODO: The deep-directory support bypasses this; disable deep directory
1521 * support if we're doing symlink checks.
1522 */
1523/*
1524 * TODO: Someday, integrate this with the deep dir support; they both
1525 * scan the path and both can be optimized by comparing against other
1526 * recent paths.
1527 */
1528/* TODO: Extend this to support symlinks on Windows Vista and later. */
1529static int
1530check_symlinks(struct archive_write_disk *a)
1531{
1532#if !defined(HAVE_LSTAT)
1533	/* Platform doesn't have lstat, so we can't look for symlinks. */
1534	(void)a; /* UNUSED */
1535	return (ARCHIVE_OK);
1536#else
1537	char *pn;
1538	char c;
1539	int r;
1540	struct stat st;
1541
1542	/*
1543	 * Guard against symlink tricks.  Reject any archive entry whose
1544	 * destination would be altered by a symlink.
1545	 */
1546	/* Whatever we checked last time doesn't need to be re-checked. */
1547	pn = a->name;
1548	if (archive_strlen(&(a->path_safe)) > 0) {
1549		char *p = a->path_safe.s;
1550		while ((*pn != '\0') && (*p == *pn))
1551			++p, ++pn;
1552	}
1553	c = pn[0];
1554	/* Keep going until we've checked the entire name. */
1555	while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
1556		/* Skip the next path element. */
1557		while (*pn != '\0' && *pn != '/')
1558			++pn;
1559		c = pn[0];
1560		pn[0] = '\0';
1561		/* Check that we haven't hit a symlink. */
1562		r = lstat(a->name, &st);
1563		if (r != 0) {
1564			/* We've hit a dir that doesn't exist; stop now. */
1565			if (errno == ENOENT)
1566				break;
1567		} else if (S_ISLNK(st.st_mode)) {
1568			if (c == '\0') {
1569				/*
1570				 * Last element is symlink; remove it
1571				 * so we can overwrite it with the
1572				 * item being extracted.
1573				 */
1574				if (unlink(a->name)) {
1575					archive_set_error(&a->archive, errno,
1576					    "Could not remove symlink %s",
1577					    a->name);
1578					pn[0] = c;
1579					return (ARCHIVE_FAILED);
1580				}
1581				a->pst = NULL;
1582				/*
1583				 * Even if we did remove it, a warning
1584				 * is in order.  The warning is silly,
1585				 * though, if we're just replacing one
1586				 * symlink with another symlink.
1587				 */
1588				if (!S_ISLNK(a->mode)) {
1589					archive_set_error(&a->archive, 0,
1590					    "Removing symlink %s",
1591					    a->name);
1592				}
1593				/* Symlink gone.  No more problem! */
1594				pn[0] = c;
1595				return (0);
1596			} else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
1597				/* User asked us to remove problems. */
1598				if (unlink(a->name) != 0) {
1599					archive_set_error(&a->archive, 0,
1600					    "Cannot remove intervening symlink %s",
1601					    a->name);
1602					pn[0] = c;
1603					return (ARCHIVE_FAILED);
1604				}
1605				a->pst = NULL;
1606			} else {
1607				archive_set_error(&a->archive, 0,
1608				    "Cannot extract through symlink %s",
1609				    a->name);
1610				pn[0] = c;
1611				return (ARCHIVE_FAILED);
1612			}
1613		}
1614	}
1615	pn[0] = c;
1616	/* We've checked and/or cleaned the whole path, so remember it. */
1617	archive_strcpy(&a->path_safe, a->name);
1618	return (ARCHIVE_OK);
1619#endif
1620}
1621
1622#if defined(__CYGWIN__)
1623/*
1624 * 1. Convert a path separator from '\' to '/' .
1625 *    We shouldn't check multibyte character directly because some
1626 *    character-set have been using the '\' character for a part of
1627 *    its multibyte character code.
1628 * 2. Replace unusable characters in Windows with underscore('_').
1629 * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
1630 */
1631static void
1632cleanup_pathname_win(struct archive_write_disk *a)
1633{
1634	wchar_t wc;
1635	char *p;
1636	size_t alen, l;
1637	int mb, complete, utf8;
1638
1639	alen = 0;
1640	mb = 0;
1641	complete = 1;
1642	utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
1643	for (p = a->name; *p != '\0'; p++) {
1644		++alen;
1645		if (*p == '\\') {
1646			/* If previous byte is smaller than 128,
1647			 * this is not second byte of multibyte characters,
1648			 * so we can replace '\' with '/'. */
1649			if (utf8 || !mb)
1650				*p = '/';
1651			else
1652				complete = 0;/* uncompleted. */
1653		} else if (*(unsigned char *)p > 127)
1654			mb = 1;
1655		else
1656			mb = 0;
1657		/* Rewrite the path name if its next character is unusable. */
1658		if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
1659		    *p == '<' || *p == '>' || *p == '|')
1660			*p = '_';
1661	}
1662	if (complete)
1663		return;
1664
1665	/*
1666	 * Convert path separator in wide-character.
1667	 */
1668	p = a->name;
1669	while (*p != '\0' && alen) {
1670		l = mbtowc(&wc, p, alen);
1671		if (l == (size_t)-1) {
1672			while (*p != '\0') {
1673				if (*p == '\\')
1674					*p = '/';
1675				++p;
1676			}
1677			break;
1678		}
1679		if (l == 1 && wc == L'\\')
1680			*p = '/';
1681		p += l;
1682		alen -= l;
1683	}
1684}
1685#endif
1686
1687/*
1688 * Canonicalize the pathname.  In particular, this strips duplicate
1689 * '/' characters, '.' elements, and trailing '/'.  It also raises an
1690 * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
1691 * set) any '..' in the path.
1692 */
1693static int
1694cleanup_pathname(struct archive_write_disk *a)
1695{
1696	char *dest, *src;
1697	char separator = '\0';
1698
1699	dest = src = a->name;
1700	if (*src == '\0') {
1701		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1702		    "Invalid empty pathname");
1703		return (ARCHIVE_FAILED);
1704	}
1705
1706#if defined(__CYGWIN__)
1707	cleanup_pathname_win(a);
1708#endif
1709	/* Skip leading '/'. */
1710	if (*src == '/')
1711		separator = *src++;
1712
1713	/* Scan the pathname one element at a time. */
1714	for (;;) {
1715		/* src points to first char after '/' */
1716		if (src[0] == '\0') {
1717			break;
1718		} else if (src[0] == '/') {
1719			/* Found '//', ignore second one. */
1720			src++;
1721			continue;
1722		} else if (src[0] == '.') {
1723			if (src[1] == '\0') {
1724				/* Ignore trailing '.' */
1725				break;
1726			} else if (src[1] == '/') {
1727				/* Skip './'. */
1728				src += 2;
1729				continue;
1730			} else if (src[1] == '.') {
1731				if (src[2] == '/' || src[2] == '\0') {
1732					/* Conditionally warn about '..' */
1733					if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
1734						archive_set_error(&a->archive,
1735						    ARCHIVE_ERRNO_MISC,
1736						    "Path contains '..'");
1737						return (ARCHIVE_FAILED);
1738					}
1739				}
1740				/*
1741				 * Note: Under no circumstances do we
1742				 * remove '..' elements.  In
1743				 * particular, restoring
1744				 * '/foo/../bar/' should create the
1745				 * 'foo' dir as a side-effect.
1746				 */
1747			}
1748		}
1749
1750		/* Copy current element, including leading '/'. */
1751		if (separator)
1752			*dest++ = '/';
1753		while (*src != '\0' && *src != '/') {
1754			*dest++ = *src++;
1755		}
1756
1757		if (*src == '\0')
1758			break;
1759
1760		/* Skip '/' separator. */
1761		separator = *src++;
1762	}
1763	/*
1764	 * We've just copied zero or more path elements, not including the
1765	 * final '/'.
1766	 */
1767	if (dest == a->name) {
1768		/*
1769		 * Nothing got copied.  The path must have been something
1770		 * like '.' or '/' or './' or '/././././/./'.
1771		 */
1772		if (separator)
1773			*dest++ = '/';
1774		else
1775			*dest++ = '.';
1776	}
1777	/* Terminate the result. */
1778	*dest = '\0';
1779	return (ARCHIVE_OK);
1780}
1781
1782/*
1783 * Create the parent directory of the specified path, assuming path
1784 * is already in mutable storage.
1785 */
1786static int
1787create_parent_dir(struct archive_write_disk *a, char *path)
1788{
1789	char *slash;
1790	int r;
1791
1792	/* Remove tail element to obtain parent name. */
1793	slash = strrchr(path, '/');
1794	if (slash == NULL)
1795		return (ARCHIVE_OK);
1796	*slash = '\0';
1797	r = create_dir(a, path);
1798	*slash = '/';
1799	return (r);
1800}
1801
1802/*
1803 * Create the specified dir, recursing to create parents as necessary.
1804 *
1805 * Returns ARCHIVE_OK if the path exists when we're done here.
1806 * Otherwise, returns ARCHIVE_FAILED.
1807 * Assumes path is in mutable storage; path is unchanged on exit.
1808 */
1809static int
1810create_dir(struct archive_write_disk *a, char *path)
1811{
1812	struct stat st;
1813	struct fixup_entry *le;
1814	char *slash, *base;
1815	mode_t mode_final, mode;
1816	int r;
1817
1818	/* Check for special names and just skip them. */
1819	slash = strrchr(path, '/');
1820	if (slash == NULL)
1821		base = path;
1822	else
1823		base = slash + 1;
1824
1825	if (base[0] == '\0' ||
1826	    (base[0] == '.' && base[1] == '\0') ||
1827	    (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
1828		/* Don't bother trying to create null path, '.', or '..'. */
1829		if (slash != NULL) {
1830			*slash = '\0';
1831			r = create_dir(a, path);
1832			*slash = '/';
1833			return (r);
1834		}
1835		return (ARCHIVE_OK);
1836	}
1837
1838	/*
1839	 * Yes, this should be stat() and not lstat().  Using lstat()
1840	 * here loses the ability to extract through symlinks.  Also note
1841	 * that this should not use the a->st cache.
1842	 */
1843	if (stat(path, &st) == 0) {
1844		if (S_ISDIR(st.st_mode))
1845			return (ARCHIVE_OK);
1846		if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1847			archive_set_error(&a->archive, EEXIST,
1848			    "Can't create directory '%s'", path);
1849			return (ARCHIVE_FAILED);
1850		}
1851		if (unlink(path) != 0) {
1852			archive_set_error(&a->archive, errno,
1853			    "Can't create directory '%s': "
1854			    "Conflicting file cannot be removed",
1855			    path);
1856			return (ARCHIVE_FAILED);
1857		}
1858	} else if (errno != ENOENT && errno != ENOTDIR) {
1859		/* Stat failed? */
1860		archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
1861		return (ARCHIVE_FAILED);
1862	} else if (slash != NULL) {
1863		*slash = '\0';
1864		r = create_dir(a, path);
1865		*slash = '/';
1866		if (r != ARCHIVE_OK)
1867			return (r);
1868	}
1869
1870	/*
1871	 * Mode we want for the final restored directory.  Per POSIX,
1872	 * implicitly-created dirs must be created obeying the umask.
1873	 * There's no mention whether this is different for privileged
1874	 * restores (which the rest of this code handles by pretending
1875	 * umask=0).  I've chosen here to always obey the user's umask for
1876	 * implicit dirs, even if _EXTRACT_PERM was specified.
1877	 */
1878	mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
1879	/* Mode we want on disk during the restore process. */
1880	mode = mode_final;
1881	mode |= MINIMUM_DIR_MODE;
1882	mode &= MAXIMUM_DIR_MODE;
1883	if (mkdir(path, mode) == 0) {
1884		if (mode != mode_final) {
1885			le = new_fixup(a, path);
1886			le->fixup |=TODO_MODE_BASE;
1887			le->mode = mode_final;
1888		}
1889		return (ARCHIVE_OK);
1890	}
1891
1892	/*
1893	 * Without the following check, a/b/../b/c/d fails at the
1894	 * second visit to 'b', so 'd' can't be created.  Note that we
1895	 * don't add it to the fixup list here, as it's already been
1896	 * added.
1897	 */
1898	if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1899		return (ARCHIVE_OK);
1900
1901	archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
1902	    path);
1903	return (ARCHIVE_FAILED);
1904}
1905
1906/*
1907 * Note: Although we can skip setting the user id if the desired user
1908 * id matches the current user, we cannot skip setting the group, as
1909 * many systems set the gid based on the containing directory.  So
1910 * we have to perform a chown syscall if we want to set the SGID
1911 * bit.  (The alternative is to stat() and then possibly chown(); it's
1912 * more efficient to skip the stat() and just always chown().)  Note
1913 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
1914 * allows set_mode to skip the stat() check for the GID.
1915 */
1916static int
1917set_ownership(struct archive_write_disk *a)
1918{
1919#ifndef __CYGWIN__
1920/* unfortunately, on win32 there is no 'root' user with uid 0,
1921   so we just have to try the chown and see if it works */
1922
1923	/* If we know we can't change it, don't bother trying. */
1924	if (a->user_uid != 0  &&  a->user_uid != a->uid) {
1925		archive_set_error(&a->archive, errno,
1926		    "Can't set UID=%jd", (intmax_t)a->uid);
1927		return (ARCHIVE_WARN);
1928	}
1929#endif
1930
1931#ifdef HAVE_FCHOWN
1932	/* If we have an fd, we can avoid a race. */
1933	if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
1934		/* We've set owner and know uid/gid are correct. */
1935		a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1936		return (ARCHIVE_OK);
1937	}
1938#endif
1939
1940	/* We prefer lchown() but will use chown() if that's all we have. */
1941	/* Of course, if we have neither, this will always fail. */
1942#ifdef HAVE_LCHOWN
1943	if (lchown(a->name, a->uid, a->gid) == 0) {
1944		/* We've set owner and know uid/gid are correct. */
1945		a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1946		return (ARCHIVE_OK);
1947	}
1948#elif HAVE_CHOWN
1949	if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
1950		/* We've set owner and know uid/gid are correct. */
1951		a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1952		return (ARCHIVE_OK);
1953	}
1954#endif
1955
1956	archive_set_error(&a->archive, errno,
1957	    "Can't set user=%jd/group=%jd for %s",
1958	    (intmax_t)a->uid, (intmax_t)a->gid, a->name);
1959	return (ARCHIVE_WARN);
1960}
1961
1962/*
1963 * Note: Returns 0 on success, non-zero on failure.
1964 */
1965static int
1966set_time(int fd, int mode, const char *name,
1967    time_t atime, long atime_nsec,
1968    time_t mtime, long mtime_nsec)
1969{
1970	/* Select the best implementation for this platform. */
1971#if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
1972	/*
1973	 * utimensat() and futimens() are defined in
1974	 * POSIX.1-2008. They support ns resolution and setting times
1975	 * on fds and symlinks.
1976	 */
1977	struct timespec ts[2];
1978	(void)mode; /* UNUSED */
1979	ts[0].tv_sec = atime;
1980	ts[0].tv_nsec = atime_nsec;
1981	ts[1].tv_sec = mtime;
1982	ts[1].tv_nsec = mtime_nsec;
1983	if (fd >= 0)
1984		return futimens(fd, ts);
1985	return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
1986
1987#elif HAVE_UTIMES
1988	/*
1989	 * The utimes()-family functions support ��s-resolution and
1990	 * setting times fds and symlinks.  utimes() is documented as
1991	 * LEGACY by POSIX, futimes() and lutimes() are not described
1992	 * in POSIX.
1993	 */
1994	struct timeval times[2];
1995
1996	times[0].tv_sec = atime;
1997	times[0].tv_usec = atime_nsec / 1000;
1998	times[1].tv_sec = mtime;
1999	times[1].tv_usec = mtime_nsec / 1000;
2000
2001#ifdef HAVE_FUTIMES
2002	if (fd >= 0)
2003		return (futimes(fd, times));
2004#else
2005	(void)fd; /* UNUSED */
2006#endif
2007#ifdef HAVE_LUTIMES
2008	(void)mode; /* UNUSED */
2009	return (lutimes(name, times));
2010#else
2011	if (S_ISLNK(mode))
2012		return (0);
2013	return (utimes(name, times));
2014#endif
2015
2016#elif defined(HAVE_UTIME)
2017	/*
2018	 * utime() is POSIX-standard but only supports 1s resolution and
2019	 * does not support fds or symlinks.
2020	 */
2021	struct utimbuf times;
2022	(void)fd; /* UNUSED */
2023	(void)name; /* UNUSED */
2024	(void)atime_nsec; /* UNUSED */
2025	(void)mtime_nsec; /* UNUSED */
2026	times.actime = atime;
2027	times.modtime = mtime;
2028	if (S_ISLNK(mode))
2029		return (ARCHIVE_OK);
2030	return (utime(name, &times));
2031
2032#else
2033	/*
2034	 * We don't know how to set the time on this platform.
2035	 */
2036	(void)fd; /* UNUSED */
2037	(void)mode; /* UNUSED */
2038	(void)name; /* UNUSED */
2039	(void)atime_nsec; /* UNUSED */
2040	(void)mtime_nsec; /* UNUSED */
2041	return (ARCHIVE_WARN);
2042#endif
2043}
2044
2045#ifdef F_SETTIMES /* Tru64 */
2046static int
2047set_time_tru64(int fd, int mode, const char *name,
2048    time_t atime, long atime_nsec,
2049    time_t mtime, long mtime_nsec,
2050    time_t ctime, long ctime_nsec)
2051{
2052	struct attr_timbuf tstamp;
2053	struct timeval times[3];
2054	times[0].tv_sec = atime;
2055	times[0].tv_usec = atime_nsec / 1000;
2056	times[1].tv_sec = mtime;
2057	times[1].tv_usec = mtime_nsec / 1000;
2058	times[2].tv_sec = ctime;
2059	times[2].tv_usec = ctime_nsec / 1000;
2060	tstamp.atime = times[0];
2061	tstamp.mtime = times[1];
2062	tstamp.ctime = times[2];
2063	return (fcntl(fd,F_SETTIMES,&tstamp));
2064}
2065#endif /* Tru64 */
2066
2067static int
2068set_times(struct archive_write_disk *a,
2069    int fd, int mode, const char *name,
2070    time_t atime, long atime_nanos,
2071    time_t birthtime, long birthtime_nanos,
2072    time_t mtime, long mtime_nanos,
2073    time_t cctime, long ctime_nanos)
2074{
2075	/* Note: set_time doesn't use libarchive return conventions!
2076	 * It uses syscall conventions.  So 0 here instead of ARCHIVE_OK. */
2077	int r1 = 0, r2 = 0;
2078
2079#ifdef F_SETTIMES
2080	 /*
2081	 * on Tru64 try own fcntl first which can restore even the
2082	 * ctime, fall back to default code path below if it fails
2083	 * or if we are not running as root
2084	 */
2085	if (a->user_uid == 0 &&
2086	    set_time_tru64(fd, mode, name,
2087			   atime, atime_nanos, mtime,
2088			   mtime_nanos, cctime, ctime_nanos) == 0) {
2089		return (ARCHIVE_OK);
2090	}
2091#else /* Tru64 */
2092	(void)cctime; /* UNUSED */
2093	(void)ctime_nanos; /* UNUSED */
2094#endif /* Tru64 */
2095
2096#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2097	/*
2098	 * If you have struct stat.st_birthtime, we assume BSD
2099	 * birthtime semantics, in which {f,l,}utimes() updates
2100	 * birthtime to earliest mtime.  So we set the time twice,
2101	 * first using the birthtime, then using the mtime.  If
2102	 * birthtime == mtime, this isn't necessary, so we skip it.
2103	 * If birthtime > mtime, then this won't work, so we skip it.
2104	 */
2105	if (birthtime < mtime
2106	    || (birthtime == mtime && birthtime_nanos < mtime_nanos))
2107		r1 = set_time(fd, mode, name,
2108			      atime, atime_nanos,
2109			      birthtime, birthtime_nanos);
2110#else
2111	(void)birthtime; /* UNUSED */
2112	(void)birthtime_nanos; /* UNUSED */
2113#endif
2114	r2 = set_time(fd, mode, name,
2115		      atime, atime_nanos,
2116		      mtime, mtime_nanos);
2117	if (r1 != 0 || r2 != 0) {
2118		archive_set_error(&a->archive, errno,
2119				  "Can't restore time");
2120		return (ARCHIVE_WARN);
2121	}
2122	return (ARCHIVE_OK);
2123}
2124
2125static int
2126set_times_from_entry(struct archive_write_disk *a)
2127{
2128	time_t atime, birthtime, mtime, cctime;
2129	long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
2130
2131	/* Suitable defaults. */
2132	atime = birthtime = mtime = cctime = a->start_time;
2133	atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
2134
2135	/* If no time was provided, we're done. */
2136	if (!archive_entry_atime_is_set(a->entry)
2137#if HAVE_STRUCT_STAT_ST_BIRTHTIME
2138	    && !archive_entry_birthtime_is_set(a->entry)
2139#endif
2140	    && !archive_entry_mtime_is_set(a->entry))
2141		return (ARCHIVE_OK);
2142
2143	if (archive_entry_atime_is_set(a->entry)) {
2144		atime = archive_entry_atime(a->entry);
2145		atime_nsec = archive_entry_atime_nsec(a->entry);
2146	}
2147	if (archive_entry_birthtime_is_set(a->entry)) {
2148		birthtime = archive_entry_birthtime(a->entry);
2149		birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
2150	}
2151	if (archive_entry_mtime_is_set(a->entry)) {
2152		mtime = archive_entry_mtime(a->entry);
2153		mtime_nsec = archive_entry_mtime_nsec(a->entry);
2154	}
2155	if (archive_entry_ctime_is_set(a->entry)) {
2156		cctime = archive_entry_ctime(a->entry);
2157		ctime_nsec = archive_entry_ctime_nsec(a->entry);
2158	}
2159
2160	return set_times(a, a->fd, a->mode, a->name,
2161			 atime, atime_nsec,
2162			 birthtime, birthtime_nsec,
2163			 mtime, mtime_nsec,
2164			 cctime, ctime_nsec);
2165}
2166
2167static int
2168set_mode(struct archive_write_disk *a, int mode)
2169{
2170	int r = ARCHIVE_OK;
2171	mode &= 07777; /* Strip off file type bits. */
2172
2173	if (a->todo & TODO_SGID_CHECK) {
2174		/*
2175		 * If we don't know the GID is right, we must stat()
2176		 * to verify it.  We can't just check the GID of this
2177		 * process, since systems sometimes set GID from
2178		 * the enclosing dir or based on ACLs.
2179		 */
2180		if ((r = lazy_stat(a)) != ARCHIVE_OK)
2181			return (r);
2182		if (a->pst->st_gid != a->gid) {
2183			mode &= ~ S_ISGID;
2184			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
2185				/*
2186				 * This is only an error if you
2187				 * requested owner restore.  If you
2188				 * didn't, we'll try to restore
2189				 * sgid/suid, but won't consider it a
2190				 * problem if we can't.
2191				 */
2192				archive_set_error(&a->archive, -1,
2193				    "Can't restore SGID bit");
2194				r = ARCHIVE_WARN;
2195			}
2196		}
2197		/* While we're here, double-check the UID. */
2198		if (a->pst->st_uid != a->uid
2199		    && (a->todo & TODO_SUID)) {
2200			mode &= ~ S_ISUID;
2201			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
2202				archive_set_error(&a->archive, -1,
2203				    "Can't restore SUID bit");
2204				r = ARCHIVE_WARN;
2205			}
2206		}
2207		a->todo &= ~TODO_SGID_CHECK;
2208		a->todo &= ~TODO_SUID_CHECK;
2209	} else if (a->todo & TODO_SUID_CHECK) {
2210		/*
2211		 * If we don't know the UID is right, we can just check
2212		 * the user, since all systems set the file UID from
2213		 * the process UID.
2214		 */
2215		if (a->user_uid != a->uid) {
2216			mode &= ~ S_ISUID;
2217			if (a->flags & ARCHIVE_EXTRACT_OWNER) {
2218				archive_set_error(&a->archive, -1,
2219				    "Can't make file SUID");
2220				r = ARCHIVE_WARN;
2221			}
2222		}
2223		a->todo &= ~TODO_SUID_CHECK;
2224	}
2225
2226	if (S_ISLNK(a->mode)) {
2227#ifdef HAVE_LCHMOD
2228		/*
2229		 * If this is a symlink, use lchmod().  If the
2230		 * platform doesn't support lchmod(), just skip it.  A
2231		 * platform that doesn't provide a way to set
2232		 * permissions on symlinks probably ignores
2233		 * permissions on symlinks, so a failure here has no
2234		 * impact.
2235		 */
2236		if (lchmod(a->name, mode) != 0) {
2237			archive_set_error(&a->archive, errno,
2238			    "Can't set permissions to 0%o", (int)mode);
2239			r = ARCHIVE_WARN;
2240		}
2241#endif
2242	} else if (!S_ISDIR(a->mode)) {
2243		/*
2244		 * If it's not a symlink and not a dir, then use
2245		 * fchmod() or chmod(), depending on whether we have
2246		 * an fd.  Dirs get their perms set during the
2247		 * post-extract fixup, which is handled elsewhere.
2248		 */
2249#ifdef HAVE_FCHMOD
2250		if (a->fd >= 0) {
2251			if (fchmod(a->fd, mode) != 0) {
2252				archive_set_error(&a->archive, errno,
2253				    "Can't set permissions to 0%o", (int)mode);
2254				r = ARCHIVE_WARN;
2255			}
2256		} else
2257#endif
2258			/* If this platform lacks fchmod(), then
2259			 * we'll just use chmod(). */
2260			if (chmod(a->name, mode) != 0) {
2261				archive_set_error(&a->archive, errno,
2262				    "Can't set permissions to 0%o", (int)mode);
2263				r = ARCHIVE_WARN;
2264			}
2265	}
2266	return (r);
2267}
2268
2269static int
2270set_fflags(struct archive_write_disk *a)
2271{
2272	struct fixup_entry *le;
2273	unsigned long	set, clear;
2274	int		r;
2275	int		critical_flags;
2276	mode_t		mode = archive_entry_mode(a->entry);
2277
2278	/*
2279	 * Make 'critical_flags' hold all file flags that can't be
2280	 * immediately restored.  For example, on BSD systems,
2281	 * SF_IMMUTABLE prevents hardlinks from being created, so
2282	 * should not be set until after any hardlinks are created.  To
2283	 * preserve some semblance of portability, this uses #ifdef
2284	 * extensively.  Ugly, but it works.
2285	 *
2286	 * Yes, Virginia, this does create a security race.  It's mitigated
2287	 * somewhat by the practice of creating dirs 0700 until the extract
2288	 * is done, but it would be nice if we could do more than that.
2289	 * People restoring critical file systems should be wary of
2290	 * other programs that might try to muck with files as they're
2291	 * being restored.
2292	 */
2293	/* Hopefully, the compiler will optimize this mess into a constant. */
2294	critical_flags = 0;
2295#ifdef SF_IMMUTABLE
2296	critical_flags |= SF_IMMUTABLE;
2297#endif
2298#ifdef UF_IMMUTABLE
2299	critical_flags |= UF_IMMUTABLE;
2300#endif
2301#ifdef SF_APPEND
2302	critical_flags |= SF_APPEND;
2303#endif
2304#ifdef UF_APPEND
2305	critical_flags |= UF_APPEND;
2306#endif
2307#ifdef EXT2_APPEND_FL
2308	critical_flags |= EXT2_APPEND_FL;
2309#endif
2310#ifdef EXT2_IMMUTABLE_FL
2311	critical_flags |= EXT2_IMMUTABLE_FL;
2312#endif
2313
2314	if (a->todo & TODO_FFLAGS) {
2315		archive_entry_fflags(a->entry, &set, &clear);
2316
2317		/*
2318		 * The first test encourages the compiler to eliminate
2319		 * all of this if it's not necessary.
2320		 */
2321		if ((critical_flags != 0)  &&  (set & critical_flags)) {
2322			le = current_fixup(a, a->name);
2323			le->fixup |= TODO_FFLAGS;
2324			le->fflags_set = set;
2325			/* Store the mode if it's not already there. */
2326			if ((le->fixup & TODO_MODE) == 0)
2327				le->mode = mode;
2328		} else {
2329			r = set_fflags_platform(a, a->fd,
2330			    a->name, mode, set, clear);
2331			if (r != ARCHIVE_OK)
2332				return (r);
2333		}
2334	}
2335	return (ARCHIVE_OK);
2336}
2337
2338
2339#if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
2340/*
2341 * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
2342 */
2343static int
2344set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2345    mode_t mode, unsigned long set, unsigned long clear)
2346{
2347	int r;
2348
2349	(void)mode; /* UNUSED */
2350	if (set == 0  && clear == 0)
2351		return (ARCHIVE_OK);
2352
2353	/*
2354	 * XXX Is the stat here really necessary?  Or can I just use
2355	 * the 'set' flags directly?  In particular, I'm not sure
2356	 * about the correct approach if we're overwriting an existing
2357	 * file that already has flags on it. XXX
2358	 */
2359	if ((r = lazy_stat(a)) != ARCHIVE_OK)
2360		return (r);
2361
2362	a->st.st_flags &= ~clear;
2363	a->st.st_flags |= set;
2364#ifdef HAVE_FCHFLAGS
2365	/* If platform has fchflags() and we were given an fd, use it. */
2366	if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
2367		return (ARCHIVE_OK);
2368#endif
2369	/*
2370	 * If we can't use the fd to set the flags, we'll use the
2371	 * pathname to set flags.  We prefer lchflags() but will use
2372	 * chflags() if we must.
2373	 */
2374#ifdef HAVE_LCHFLAGS
2375	if (lchflags(name, a->st.st_flags) == 0)
2376		return (ARCHIVE_OK);
2377#elif defined(HAVE_CHFLAGS)
2378	if (S_ISLNK(a->st.st_mode)) {
2379		archive_set_error(&a->archive, errno,
2380		    "Can't set file flags on symlink.");
2381		return (ARCHIVE_WARN);
2382	}
2383	if (chflags(name, a->st.st_flags) == 0)
2384		return (ARCHIVE_OK);
2385#endif
2386	archive_set_error(&a->archive, errno,
2387	    "Failed to set file flags");
2388	return (ARCHIVE_WARN);
2389}
2390
2391#elif defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)
2392/*
2393 * Linux uses ioctl() to read and write file flags.
2394 */
2395static int
2396set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2397    mode_t mode, unsigned long set, unsigned long clear)
2398{
2399	int		 ret;
2400	int		 myfd = fd;
2401	unsigned long newflags, oldflags;
2402	unsigned long sf_mask = 0;
2403
2404	if (set == 0  && clear == 0)
2405		return (ARCHIVE_OK);
2406	/* Only regular files and dirs can have flags. */
2407	if (!S_ISREG(mode) && !S_ISDIR(mode))
2408		return (ARCHIVE_OK);
2409
2410	/* If we weren't given an fd, open it ourselves. */
2411	if (myfd < 0)
2412		myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY);
2413	if (myfd < 0)
2414		return (ARCHIVE_OK);
2415
2416	/*
2417	 * Linux has no define for the flags that are only settable by
2418	 * the root user.  This code may seem a little complex, but
2419	 * there seem to be some Linux systems that lack these
2420	 * defines. (?)  The code below degrades reasonably gracefully
2421	 * if sf_mask is incomplete.
2422	 */
2423#ifdef EXT2_IMMUTABLE_FL
2424	sf_mask |= EXT2_IMMUTABLE_FL;
2425#endif
2426#ifdef EXT2_APPEND_FL
2427	sf_mask |= EXT2_APPEND_FL;
2428#endif
2429	/*
2430	 * XXX As above, this would be way simpler if we didn't have
2431	 * to read the current flags from disk. XXX
2432	 */
2433	ret = ARCHIVE_OK;
2434
2435	/* Read the current file flags. */
2436	if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) < 0)
2437		goto fail;
2438
2439	/* Try setting the flags as given. */
2440	newflags = (oldflags & ~clear) | set;
2441	if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
2442		goto cleanup;
2443	if (errno != EPERM)
2444		goto fail;
2445
2446	/* If we couldn't set all the flags, try again with a subset. */
2447	newflags &= ~sf_mask;
2448	oldflags &= sf_mask;
2449	newflags |= oldflags;
2450	if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
2451		goto cleanup;
2452
2453	/* We couldn't set the flags, so report the failure. */
2454fail:
2455	archive_set_error(&a->archive, errno,
2456	    "Failed to set file flags");
2457	ret = ARCHIVE_WARN;
2458cleanup:
2459	if (fd < 0)
2460		close(myfd);
2461	return (ret);
2462}
2463
2464#else
2465
2466/*
2467 * Of course, some systems have neither BSD chflags() nor Linux' flags
2468 * support through ioctl().
2469 */
2470static int
2471set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2472    mode_t mode, unsigned long set, unsigned long clear)
2473{
2474	(void)a; /* UNUSED */
2475	(void)fd; /* UNUSED */
2476	(void)name; /* UNUSED */
2477	(void)mode; /* UNUSED */
2478	(void)set; /* UNUSED */
2479	(void)clear; /* UNUSED */
2480	return (ARCHIVE_OK);
2481}
2482
2483#endif /* __linux */
2484
2485#ifndef HAVE_COPYFILE_H
2486/* Default is to simply drop Mac extended metadata. */
2487static int
2488set_mac_metadata(struct archive_write_disk *a, const char *pathname,
2489		 const void *metadata, size_t metadata_size)
2490{
2491	(void)a; /* UNUSED */
2492	(void)pathname; /* UNUSED */
2493	(void)metadata; /* UNUSED */
2494	(void)metadata_size; /* UNUSED */
2495	return (ARCHIVE_OK);
2496}
2497#else
2498
2499/*
2500 * On Mac OS, we use copyfile() to unpack the metadata and
2501 * apply it to the target file.
2502 */
2503static int
2504set_mac_metadata(struct archive_write_disk *a, const char *pathname,
2505		 const void *metadata, size_t metadata_size)
2506{
2507	struct archive_string tmp;
2508	ssize_t written;
2509	int fd;
2510	int ret = ARCHIVE_OK;
2511
2512	/* This would be simpler if copyfile() could just accept the
2513	 * metadata as a block of memory; then we could sidestep this
2514	 * silly dance of writing the data to disk just so that
2515	 * copyfile() can read it back in again. */
2516	archive_string_init(&tmp);
2517	archive_strcpy(&tmp, pathname);
2518	archive_strcat(&tmp, ".XXXXXX");
2519	fd = mkstemp(tmp.s);
2520
2521	if (fd < 0) {
2522		archive_set_error(&a->archive, errno,
2523				  "Failed to restore metadata");
2524		return (ARCHIVE_WARN);
2525	}
2526	written = write(fd, metadata, metadata_size);
2527	close(fd);
2528	if ((size_t)written != metadata_size
2529	    || copyfile(tmp.s, pathname, 0,
2530			COPYFILE_UNPACK | COPYFILE_NOFOLLOW
2531			| COPYFILE_ACL | COPYFILE_XATTR)) {
2532		archive_set_error(&a->archive, errno,
2533				  "Failed to restore metadata");
2534		ret = ARCHIVE_WARN;
2535	}
2536	unlink(tmp.s);
2537	return (ret);
2538}
2539#endif
2540
2541
2542#if HAVE_LSETXATTR || HAVE_LSETEA
2543/*
2544 * Restore extended attributes -  Linux and AIX implementations:
2545 * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
2546 */
2547static int
2548set_xattrs(struct archive_write_disk *a)
2549{
2550	struct archive_entry *entry = a->entry;
2551	static int warning_done = 0;
2552	int ret = ARCHIVE_OK;
2553	int i = archive_entry_xattr_reset(entry);
2554
2555	while (i--) {
2556		const char *name;
2557		const void *value;
2558		size_t size;
2559		archive_entry_xattr_next(entry, &name, &value, &size);
2560		if (name != NULL &&
2561				strncmp(name, "xfsroot.", 8) != 0 &&
2562				strncmp(name, "system.", 7) != 0) {
2563			int e;
2564#if HAVE_FSETXATTR
2565			if (a->fd >= 0)
2566				e = fsetxattr(a->fd, name, value, size, 0);
2567			else
2568#elif HAVE_FSETEA
2569			if (a->fd >= 0)
2570				e = fsetea(a->fd, name, value, size, 0);
2571			else
2572#endif
2573			{
2574#if HAVE_LSETXATTR
2575				e = lsetxattr(archive_entry_pathname(entry),
2576				    name, value, size, 0);
2577#elif HAVE_LSETEA
2578				e = lsetea(archive_entry_pathname(entry),
2579				    name, value, size, 0);
2580#endif
2581			}
2582			if (e == -1) {
2583				if (errno == ENOTSUP || errno == ENOSYS) {
2584					if (!warning_done) {
2585						warning_done = 1;
2586						archive_set_error(&a->archive, errno,
2587						    "Cannot restore extended "
2588						    "attributes on this file "
2589						    "system");
2590					}
2591				} else
2592					archive_set_error(&a->archive, errno,
2593					    "Failed to set extended attribute");
2594				ret = ARCHIVE_WARN;
2595			}
2596		} else {
2597			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2598			    "Invalid extended attribute encountered");
2599			ret = ARCHIVE_WARN;
2600		}
2601	}
2602	return (ret);
2603}
2604#elif HAVE_EXTATTR_SET_FILE && HAVE_DECL_EXTATTR_NAMESPACE_USER
2605/*
2606 * Restore extended attributes -  FreeBSD implementation
2607 */
2608static int
2609set_xattrs(struct archive_write_disk *a)
2610{
2611	struct archive_entry *entry = a->entry;
2612	static int warning_done = 0;
2613	int ret = ARCHIVE_OK;
2614	int i = archive_entry_xattr_reset(entry);
2615
2616	while (i--) {
2617		const char *name;
2618		const void *value;
2619		size_t size;
2620		archive_entry_xattr_next(entry, &name, &value, &size);
2621		if (name != NULL) {
2622			int e;
2623			int namespace;
2624
2625			if (strncmp(name, "user.", 5) == 0) {
2626				/* "user." attributes go to user namespace */
2627				name += 5;
2628				namespace = EXTATTR_NAMESPACE_USER;
2629			} else {
2630				/* Warn about other extended attributes. */
2631				archive_set_error(&a->archive,
2632				    ARCHIVE_ERRNO_FILE_FORMAT,
2633				    "Can't restore extended attribute ``%s''",
2634				    name);
2635				ret = ARCHIVE_WARN;
2636				continue;
2637			}
2638			errno = 0;
2639#if HAVE_EXTATTR_SET_FD
2640			if (a->fd >= 0)
2641				e = extattr_set_fd(a->fd, namespace, name, value, size);
2642			else
2643#endif
2644			/* TODO: should we use extattr_set_link() instead? */
2645			{
2646				e = extattr_set_file(archive_entry_pathname(entry),
2647				    namespace, name, value, size);
2648			}
2649			if (e != (int)size) {
2650				if (errno == ENOTSUP || errno == ENOSYS) {
2651					if (!warning_done) {
2652						warning_done = 1;
2653						archive_set_error(&a->archive, errno,
2654						    "Cannot restore extended "
2655						    "attributes on this file "
2656						    "system");
2657					}
2658				} else {
2659					archive_set_error(&a->archive, errno,
2660					    "Failed to set extended attribute");
2661				}
2662
2663				ret = ARCHIVE_WARN;
2664			}
2665		}
2666	}
2667	return (ret);
2668}
2669#else
2670/*
2671 * Restore extended attributes - stub implementation for unsupported systems
2672 */
2673static int
2674set_xattrs(struct archive_write_disk *a)
2675{
2676	static int warning_done = 0;
2677
2678	/* If there aren't any extended attributes, then it's okay not
2679	 * to extract them, otherwise, issue a single warning. */
2680	if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
2681		warning_done = 1;
2682		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2683		    "Cannot restore extended attributes on this system");
2684		return (ARCHIVE_WARN);
2685	}
2686	/* Warning was already emitted; suppress further warnings. */
2687	return (ARCHIVE_OK);
2688}
2689#endif
2690
2691/*
2692 * Test if file on disk is older than entry.
2693 */
2694static int
2695older(struct stat *st, struct archive_entry *entry)
2696{
2697	/* First, test the seconds and return if we have a definite answer. */
2698	/* Definitely older. */
2699	if (st->st_mtime < archive_entry_mtime(entry))
2700		return (1);
2701	/* Definitely younger. */
2702	if (st->st_mtime > archive_entry_mtime(entry))
2703		return (0);
2704	/* If this platform supports fractional seconds, try those. */
2705#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
2706	/* Definitely older. */
2707	if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
2708		return (1);
2709#elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
2710	/* Definitely older. */
2711	if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
2712		return (1);
2713#elif HAVE_STRUCT_STAT_ST_MTIME_N
2714	/* older. */
2715	if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
2716		return (1);
2717#elif HAVE_STRUCT_STAT_ST_UMTIME
2718	/* older. */
2719	if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
2720		return (1);
2721#elif HAVE_STRUCT_STAT_ST_MTIME_USEC
2722	/* older. */
2723	if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
2724		return (1);
2725#else
2726	/* This system doesn't have high-res timestamps. */
2727#endif
2728	/* Same age or newer, so not older. */
2729	return (0);
2730}
2731
2732#endif /* !_WIN32 || __CYGWIN__ */
2733
2734