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