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