2 * Copyright (c) 2003-2007 Tim Kientzle
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD$");
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
36 #ifdef HAVE_ATTR_XATTR_H
37 #include <attr/xattr.h>
39 #ifdef HAVE_SYS_IOCTL_H
40 #include <sys/ioctl.h>
42 #ifdef HAVE_SYS_STAT_H
45 #ifdef HAVE_SYS_TIME_H
48 #ifdef HAVE_SYS_UTIME_H
49 #include <sys/utime.h>
52 #ifdef HAVE_EXT2FS_EXT2_FS_H
53 #include <ext2fs/ext2_fs.h> /* for Linux file flags */
64 #ifdef HAVE_LINUX_FS_H
65 #include <linux/fs.h> /* for Linux file flags */
88 #include "archive_string.h"
89 #include "archive_entry.h"
90 #include "archive_private.h"
97 struct fixup_entry *next;
101 unsigned long mtime_nanos;
102 unsigned long atime_nanos;
103 unsigned long fflags_set;
104 int fixup; /* bitmask of what needs fixing */
109 * We use a bitmask to track which operations remain to be done for
110 * this file. In particular, this helps us avoid unnecessary
111 * operations when it's possible to take care of one step as a
112 * side-effect of another. For example, mkdir() can specify the mode
113 * for the newly-created object but symlink() cannot. This means we
114 * can skip chmod() if mkdir() succeeded, but we must explicitly
115 * chmod() if we're trying to create a directory that already exists
116 * (mkdir() failed) or if we're restoring a symlink. Similarly, we
117 * need to verify UID/GID before trying to restore SUID/SGID bits;
118 * that verification can occur explicitly through a stat() call or
119 * implicitly because of a successful chown() call.
121 #define TODO_MODE_FORCE 0x40000000
122 #define TODO_MODE_BASE 0x20000000
123 #define TODO_SUID 0x10000000
124 #define TODO_SUID_CHECK 0x08000000
125 #define TODO_SGID 0x04000000
126 #define TODO_SGID_CHECK 0x02000000
127 #define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
128 #define TODO_TIMES ARCHIVE_EXTRACT_TIME
129 #define TODO_OWNER ARCHIVE_EXTRACT_OWNER
130 #define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS
131 #define TODO_ACLS ARCHIVE_EXTRACT_ACL
132 #define TODO_XATTR ARCHIVE_EXTRACT_XATTR
134 struct archive_write_disk {
135 struct archive archive;
138 struct fixup_entry *fixup_list;
139 struct fixup_entry *current_fixup;
145 gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid);
146 void (*cleanup_gid)(void *private);
147 void *lookup_gid_data;
148 uid_t (*lookup_uid)(void *private, const char *gname, gid_t gid);
149 void (*cleanup_uid)(void *private);
150 void *lookup_uid_data;
153 * Full path of last file to satisfy symlink checks.
155 struct archive_string path_safe;
158 * Cached stat data from disk for the current entry.
159 * If this is valid, pst points to st. Otherwise,
165 /* Information about the object being restored right now. */
166 struct archive_entry *entry; /* Entry being extracted. */
167 char *name; /* Name of entry, possibly edited. */
168 struct archive_string _name_data; /* backing store for 'name' */
169 /* Tasks remaining for this object. */
171 /* Tasks deferred until end-of-archive. */
173 /* Options requested by the client. */
175 /* Handle for the file we're restoring. */
177 /* Current offset for writing data to the file. */
179 /* Last offset actually written to disk. */
181 /* Maximum size of file, -1 if unknown. */
183 /* Dir we were in before this restore; only for deep paths. */
185 /* Mode we should use for this entry; affected by _PERM and umask. */
187 /* UID/GID to use in restoring this entry. */
193 * Default mode for dirs created automatically (will be modified by umask).
194 * Note that POSIX specifies 0777 for implicity-created dirs, "modified
195 * by the process' file creation mask."
197 #define DEFAULT_DIR_MODE 0777
199 * Dir modes are restored in two steps: During the extraction, the permissions
200 * in the archive are modified to match the following limits. During
201 * the post-extract fixup pass, the permissions from the archive are
204 #define MINIMUM_DIR_MODE 0700
205 #define MAXIMUM_DIR_MODE 0775
207 static int check_symlinks(struct archive_write_disk *);
208 static int create_filesystem_object(struct archive_write_disk *);
209 static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname);
211 static void edit_deep_directories(struct archive_write_disk *ad);
213 static int cleanup_pathname(struct archive_write_disk *);
214 static int create_dir(struct archive_write_disk *, char *);
215 static int create_parent_dir(struct archive_write_disk *, char *);
216 static int older(struct stat *, struct archive_entry *);
217 static int restore_entry(struct archive_write_disk *);
218 #ifdef HAVE_POSIX_ACL
219 static int set_acl(struct archive_write_disk *, int fd, struct archive_entry *,
220 acl_type_t, int archive_entry_acl_type, const char *tn);
222 static int set_acls(struct archive_write_disk *);
223 static int set_xattrs(struct archive_write_disk *);
224 static int set_fflags(struct archive_write_disk *);
225 static int set_fflags_platform(struct archive_write_disk *, int fd,
226 const char *name, mode_t mode,
227 unsigned long fflags_set, unsigned long fflags_clear);
228 static int set_ownership(struct archive_write_disk *);
229 static int set_mode(struct archive_write_disk *, int mode);
230 static int set_time(struct archive_write_disk *);
231 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
232 static gid_t trivial_lookup_gid(void *, const char *, gid_t);
233 static uid_t trivial_lookup_uid(void *, const char *, uid_t);
234 static ssize_t write_data_block(struct archive_write_disk *,
235 const char *, size_t);
237 static struct archive_vtable *archive_write_disk_vtable(void);
239 static int _archive_write_close(struct archive *);
240 static int _archive_write_finish(struct archive *);
241 static int _archive_write_header(struct archive *, struct archive_entry *);
242 static int _archive_write_finish_entry(struct archive *);
243 static ssize_t _archive_write_data(struct archive *, const void *, size_t);
244 static ssize_t _archive_write_data_block(struct archive *, const void *, size_t, off_t);
247 _archive_write_disk_lazy_stat(struct archive_write_disk *a)
249 if (a->pst != NULL) {
250 /* Already have stat() data available. */
254 if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
260 * XXX At this point, symlinks should not be hit, otherwise
261 * XXX a race occured. Do we want to check explicitly for that?
263 if (lstat(a->name, &a->st) == 0) {
267 archive_set_error(&a->archive, errno, "Couldn't stat file");
268 return (ARCHIVE_WARN);
271 static struct archive_vtable *
272 archive_write_disk_vtable(void)
274 static struct archive_vtable av;
275 static int inited = 0;
278 av.archive_write_close = _archive_write_close;
279 av.archive_write_finish = _archive_write_finish;
280 av.archive_write_header = _archive_write_header;
281 av.archive_write_finish_entry = _archive_write_finish_entry;
282 av.archive_write_data = _archive_write_data;
283 av.archive_write_data_block = _archive_write_data_block;
290 archive_write_disk_set_options(struct archive *_a, int flags)
292 struct archive_write_disk *a = (struct archive_write_disk *)_a;
300 * Extract this entry to disk.
302 * TODO: Validate hardlinks. According to the standards, we're
303 * supposed to check each extracted hardlink and squawk if it refers
304 * to a file that we didn't restore. I'm not entirely convinced this
305 * is a good idea, but more importantly: Is there any way to validate
306 * hardlinks without keeping a complete list of filenames from the
307 * entire archive?? Ugh.
311 _archive_write_header(struct archive *_a, struct archive_entry *entry)
313 struct archive_write_disk *a = (struct archive_write_disk *)_a;
314 struct fixup_entry *fe;
317 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
318 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
319 "archive_write_disk_header");
320 archive_clear_error(&a->archive);
321 if (a->archive.state & ARCHIVE_STATE_DATA) {
322 r = _archive_write_finish_entry(&a->archive);
323 if (r == ARCHIVE_FATAL)
327 /* Set up for this particular entry. */
329 a->current_fixup = NULL;
332 archive_entry_free(a->entry);
335 a->entry = archive_entry_clone(entry);
339 a->uid = a->user_uid;
340 a->mode = archive_entry_mode(a->entry);
341 if (archive_entry_size_is_set(a->entry))
342 a->filesize = archive_entry_size(a->entry);
345 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
346 a->name = a->_name_data.s;
347 archive_clear_error(&a->archive);
350 * Clean up the requested path. This is necessary for correct
351 * dir restores; the dir restore logic otherwise gets messed
352 * up by nonsense like "dir/.".
354 ret = cleanup_pathname(a);
355 if (ret != ARCHIVE_OK)
359 * Set the umask to zero so we get predictable mode settings.
360 * This gets done on every call to _write_header in case the
361 * user edits their umask during the extraction for some
362 * reason. This will be reset before we return. Note that we
363 * don't need to do this in _finish_entry, as the chmod(), etc,
364 * system calls don't obey umask.
366 a->user_umask = umask(0);
367 /* From here on, early exit requires "goto done" to clean up. */
369 /* Figure out what we need to do for this entry. */
370 a->todo = TODO_MODE_BASE;
371 if (a->flags & ARCHIVE_EXTRACT_PERM) {
372 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
374 * SGID requires an extra "check" step because we
375 * cannot easily predict the GID that the system will
376 * assign. (Different systems assign GIDs to files
377 * based on a variety of criteria, including process
378 * credentials and the gid of the enclosing
379 * directory.) We can only restore the SGID bit if
380 * the file has the right GID, and we only know the
381 * GID if we either set it (see set_ownership) or if
382 * we've actually called stat() on the file after it
383 * was restored. Since there are several places at
384 * which we might verify the GID, we need a TODO bit
387 if (a->mode & S_ISGID)
388 a->todo |= TODO_SGID | TODO_SGID_CHECK;
390 * Verifying the SUID is simpler, but can still be
391 * done in multiple ways, hence the separate "check" bit.
393 if (a->mode & S_ISUID)
394 a->todo |= TODO_SUID | TODO_SUID_CHECK;
397 * User didn't request full permissions, so don't
398 * restore SUID, SGID bits and obey umask.
403 a->mode &= ~a->user_umask;
405 if (a->flags & ARCHIVE_EXTRACT_OWNER)
406 a->todo |= TODO_OWNER;
407 if (a->flags & ARCHIVE_EXTRACT_TIME)
408 a->todo |= TODO_TIMES;
409 if (a->flags & ARCHIVE_EXTRACT_ACL)
410 a->todo |= TODO_ACLS;
411 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
412 a->todo |= TODO_FFLAGS;
413 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
414 ret = check_symlinks(a);
415 if (ret != ARCHIVE_OK)
419 /* If path exceeds PATH_MAX, shorten the path. */
420 edit_deep_directories(a);
423 ret = restore_entry(a);
426 /* If we changed directory above, restore it here. */
427 if (a->restore_pwd >= 0) {
428 fchdir(a->restore_pwd);
429 close(a->restore_pwd);
435 * Fixup uses the unedited pathname from archive_entry_pathname(),
436 * because it is relative to the base dir and the edited path
437 * might be relative to some intermediate dir as a result of the
438 * deep restore logic.
440 if (a->deferred & TODO_MODE) {
441 fe = current_fixup(a, archive_entry_pathname(entry));
442 fe->fixup |= TODO_MODE_BASE;
446 if ((a->deferred & TODO_TIMES)
447 && (archive_entry_mtime_is_set(entry)
448 || archive_entry_atime_is_set(entry))) {
449 fe = current_fixup(a, archive_entry_pathname(entry));
450 fe->fixup |= TODO_TIMES;
451 if (archive_entry_mtime_is_set(entry)) {
452 fe->mtime = archive_entry_mtime(entry);
453 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
455 fe->mtime = a->start_time;
458 if (archive_entry_atime_is_set(entry)) {
459 fe->atime = archive_entry_atime(entry);
460 fe->atime_nanos = archive_entry_atime_nsec(entry);
462 fe->atime = a->start_time;
467 if (a->deferred & TODO_FFLAGS) {
468 fe = current_fixup(a, archive_entry_pathname(entry));
469 fe->fixup |= TODO_FFLAGS;
470 /* TODO: Complete this.. defer fflags from below. */
473 /* We've created the object and are ready to pour data into it. */
474 if (ret == ARCHIVE_OK)
475 a->archive.state = ARCHIVE_STATE_DATA;
477 * If it's not open, tell our client not to try writing.
478 * In particular, dirs, links, etc, don't get written to.
481 archive_entry_set_size(entry, 0);
485 /* Restore the user's umask before returning. */
486 umask(a->user_umask);
492 archive_write_disk_set_skip_file(struct archive *_a, dev_t d, ino_t i)
494 struct archive_write_disk *a = (struct archive_write_disk *)_a;
495 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
496 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
497 a->skip_file_dev = d;
498 a->skip_file_ino = i;
503 write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
505 uint64_t start_size = size;
506 ssize_t bytes_written = 0;
507 ssize_t block_size = 0, bytes_to_write;
510 if (a->filesize == 0 || a->fd < 0) {
511 archive_set_error(&a->archive, 0,
512 "Attempt to write to an empty file");
513 return (ARCHIVE_WARN);
516 if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
517 if ((r = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
519 block_size = a->pst->st_blksize;
522 /* If this write would run beyond the file size, truncate it. */
523 if (a->filesize >= 0 && (off_t)(a->offset + size) > a->filesize)
524 start_size = size = (size_t)(a->filesize - a->offset);
526 /* Write the data. */
528 if (block_size == 0) {
529 bytes_to_write = size;
531 /* We're sparsifying the file. */
535 /* Skip leading zero bytes. */
536 for (p = buff, end = buff + size; p < end; ++p) {
540 a->offset += p - buff;
546 /* Calculate next block boundary after offset. */
548 = (a->offset / block_size + 1) * block_size;
550 /* If the adjusted write would cross block boundary,
551 * truncate it to the block boundary. */
552 bytes_to_write = size;
553 if (a->offset + bytes_to_write > block_end)
554 bytes_to_write = block_end - a->offset;
557 /* Seek if necessary to the specified offset. */
558 if (a->offset != a->fd_offset) {
559 if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
560 archive_set_error(&a->archive, errno,
562 return (ARCHIVE_FATAL);
564 a->fd_offset = a->offset;
565 a->archive.file_position = a->offset;
566 a->archive.raw_position = a->offset;
568 bytes_written = write(a->fd, buff, bytes_to_write);
569 if (bytes_written < 0) {
570 archive_set_error(&a->archive, errno, "Write failed");
571 return (ARCHIVE_WARN);
573 buff += bytes_written;
574 size -= bytes_written;
575 a->offset += bytes_written;
576 a->archive.file_position += bytes_written;
577 a->archive.raw_position += bytes_written;
578 a->fd_offset = a->offset;
580 return (start_size - size);
584 _archive_write_data_block(struct archive *_a,
585 const void *buff, size_t size, off_t offset)
587 struct archive_write_disk *a = (struct archive_write_disk *)_a;
590 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
591 ARCHIVE_STATE_DATA, "archive_write_disk_block");
594 r = write_data_block(a, buff, size);
597 if ((size_t)r < size) {
598 archive_set_error(&a->archive, 0,
599 "Write request too large");
600 return (ARCHIVE_WARN);
606 _archive_write_data(struct archive *_a, const void *buff, size_t size)
608 struct archive_write_disk *a = (struct archive_write_disk *)_a;
610 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
611 ARCHIVE_STATE_DATA, "archive_write_data");
613 return (write_data_block(a, buff, size));
617 _archive_write_finish_entry(struct archive *_a)
619 struct archive_write_disk *a = (struct archive_write_disk *)_a;
620 int ret = ARCHIVE_OK;
622 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
623 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
624 "archive_write_finish_entry");
625 if (a->archive.state & ARCHIVE_STATE_HEADER)
627 archive_clear_error(&a->archive);
629 /* Pad or truncate file to the right size. */
631 /* There's no file. */
632 } else if (a->filesize < 0) {
633 /* File size is unknown, so we can't set the size. */
634 } else if (a->fd_offset == a->filesize) {
635 /* Last write ended at exactly the filesize; we're done. */
636 /* Hopefully, this is the common case. */
638 if (ftruncate(a->fd, a->filesize) == -1 &&
640 archive_set_error(&a->archive, errno,
641 "File size could not be restored");
642 return (ARCHIVE_FAILED);
645 * Explicitly stat the file as some platforms might not
646 * implement the XSI option to extend files via ftruncate.
649 if ((ret = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
651 if (a->st.st_size != a->filesize) {
652 const char nul = '\0';
653 if (lseek(a->fd, a->st.st_size - 1, SEEK_SET) < 0) {
654 archive_set_error(&a->archive, errno,
656 return (ARCHIVE_FATAL);
658 if (write(a->fd, &nul, 1) < 0) {
659 archive_set_error(&a->archive, errno,
660 "Write to restore size failed");
661 return (ARCHIVE_FATAL);
667 /* Restore metadata. */
670 * Look up the "real" UID only if we're going to need it.
671 * TODO: the TODO_SGID condition can be dropped here, can't it?
673 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
674 a->uid = a->lookup_uid(a->lookup_uid_data,
675 archive_entry_uname(a->entry),
676 archive_entry_uid(a->entry));
678 /* Look up the "real" GID only if we're going to need it. */
679 /* TODO: the TODO_SUID condition can be dropped here, can't it? */
680 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
681 a->gid = a->lookup_gid(a->lookup_gid_data,
682 archive_entry_gname(a->entry),
683 archive_entry_gid(a->entry));
686 * If restoring ownership, do it before trying to restore suid/sgid
687 * bits. If we set the owner, we know what it is and can skip
688 * a stat() call to examine the ownership of the file on disk.
690 if (a->todo & TODO_OWNER)
691 ret = set_ownership(a);
692 if (a->todo & TODO_MODE) {
693 int r2 = set_mode(a, a->mode);
694 if (r2 < ret) ret = r2;
696 if (a->todo & TODO_ACLS) {
697 int r2 = set_acls(a);
698 if (r2 < ret) ret = r2;
700 if (a->todo & TODO_XATTR) {
701 int r2 = set_xattrs(a);
702 if (r2 < ret) ret = r2;
704 if (a->todo & TODO_FFLAGS) {
705 int r2 = set_fflags(a);
706 if (r2 < ret) ret = r2;
708 if (a->todo & TODO_TIMES) {
709 int r2 = set_time(a);
710 if (r2 < ret) ret = r2;
713 /* If there's an fd, we can close it now. */
718 /* If there's an entry, we can release it now. */
720 archive_entry_free(a->entry);
723 a->archive.state = ARCHIVE_STATE_HEADER;
728 archive_write_disk_set_group_lookup(struct archive *_a,
730 gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid),
731 void (*cleanup_gid)(void *private))
733 struct archive_write_disk *a = (struct archive_write_disk *)_a;
734 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
735 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
737 a->lookup_gid = lookup_gid;
738 a->cleanup_gid = cleanup_gid;
739 a->lookup_gid_data = private_data;
744 archive_write_disk_set_user_lookup(struct archive *_a,
746 uid_t (*lookup_uid)(void *private, const char *uname, uid_t uid),
747 void (*cleanup_uid)(void *private))
749 struct archive_write_disk *a = (struct archive_write_disk *)_a;
750 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
751 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
753 a->lookup_uid = lookup_uid;
754 a->cleanup_uid = cleanup_uid;
755 a->lookup_uid_data = private_data;
761 * Create a new archive_write_disk object and initialize it with global state.
764 archive_write_disk_new(void)
766 struct archive_write_disk *a;
768 a = (struct archive_write_disk *)malloc(sizeof(*a));
771 memset(a, 0, sizeof(*a));
772 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
773 /* We're ready to write a header immediately. */
774 a->archive.state = ARCHIVE_STATE_HEADER;
775 a->archive.vtable = archive_write_disk_vtable();
776 a->lookup_uid = trivial_lookup_uid;
777 a->lookup_gid = trivial_lookup_gid;
778 a->start_time = time(NULL);
780 a->user_uid = geteuid();
781 #endif /* HAVE_GETEUID */
782 if (archive_string_ensure(&a->path_safe, 512) == NULL) {
786 return (&a->archive);
791 * If pathname is longer than PATH_MAX, chdir to a suitable
792 * intermediate dir and edit the path down to a shorter suffix. Note
793 * that this routine never returns an error; if the chdir() attempt
794 * fails for any reason, we just go ahead with the long pathname. The
795 * object creation is likely to fail, but any error will get handled
800 edit_deep_directories(struct archive_write_disk *a)
803 char *tail = a->name;
807 /* If path is short, avoid the open() below. */
808 if (strlen(tail) <= PATH_MAX)
811 /* Try to record our starting dir. */
812 a->restore_pwd = open(".", O_RDONLY | O_BINARY);
813 if (a->restore_pwd < 0)
816 /* As long as the path is too long... */
817 while (strlen(tail) > PATH_MAX) {
818 /* Locate a dir prefix shorter than PATH_MAX. */
819 tail += PATH_MAX - 8;
820 while (tail > a->name && *tail != '/')
822 /* Exit if we find a too-long path component. */
825 /* Create the intermediate dir and chdir to it. */
826 *tail = '\0'; /* Terminate dir portion */
827 ret = create_dir(a, a->name);
828 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
830 *tail = '/'; /* Restore the / we removed. */
831 if (ret != ARCHIVE_OK)
834 /* The chdir() succeeded; we've now shortened the path. */
842 * The main restore function.
845 restore_entry(struct archive_write_disk *a)
847 int ret = ARCHIVE_OK, en;
849 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
851 * TODO: Fix this. Apparently, there are platforms
852 * that still allow root to hose the entire filesystem
853 * by unlinking a dir. The S_ISDIR() test above
854 * prevents us from using unlink() here if the new
855 * object is a dir, but that doesn't mean the old
856 * object isn't a dir.
858 if (unlink(a->name) == 0) {
859 /* We removed it, reset cached stat. */
861 } else if (errno == ENOENT) {
862 /* File didn't exist, that's just as good. */
863 } else if (rmdir(a->name) == 0) {
864 /* It was a dir, but now it's gone. */
867 /* We tried, but couldn't get rid of it. */
868 archive_set_error(&a->archive, errno,
870 return(ARCHIVE_WARN);
874 /* Try creating it first; if this fails, we'll try to recover. */
875 en = create_filesystem_object(a);
877 if ((en == ENOTDIR || en == ENOENT)
878 && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
879 /* If the parent dir doesn't exist, try creating it. */
880 create_parent_dir(a, a->name);
881 /* Now try to create the object again. */
882 en = create_filesystem_object(a);
885 if ((en == EISDIR || en == EEXIST)
886 && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
887 /* If we're not overwriting, we're done. */
888 archive_set_error(&a->archive, en, "Already exists");
889 return (ARCHIVE_WARN);
893 * Some platforms return EISDIR if you call
894 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
895 * return EEXIST. POSIX is ambiguous, requiring EISDIR
896 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
897 * on an existing item.
900 /* A dir is in the way of a non-dir, rmdir it. */
901 if (rmdir(a->name) != 0) {
902 archive_set_error(&a->archive, errno,
903 "Can't remove already-existing dir");
904 return (ARCHIVE_WARN);
908 en = create_filesystem_object(a);
909 } else if (en == EEXIST) {
911 * We know something is in the way, but we don't know what;
912 * we need to find out before we go any further.
916 * The SECURE_SYMLINK logic has already removed a
917 * symlink to a dir if the client wants that. So
918 * follow the symlink if we're creating a dir.
920 if (S_ISDIR(a->mode))
921 r = stat(a->name, &a->st);
923 * If it's not a dir (or it's a broken symlink),
924 * then don't follow it.
926 if (r != 0 || !S_ISDIR(a->mode))
927 r = lstat(a->name, &a->st);
929 archive_set_error(&a->archive, errno,
930 "Can't stat existing object");
931 return (ARCHIVE_WARN);
935 * NO_OVERWRITE_NEWER doesn't apply to directories.
937 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
938 && !S_ISDIR(a->st.st_mode)) {
939 if (!older(&(a->st), a->entry)) {
940 archive_set_error(&a->archive, 0,
941 "File on disk is not older; skipping.");
942 return (ARCHIVE_FAILED);
946 /* If it's our archive, we're done. */
947 if (a->skip_file_dev > 0 &&
948 a->skip_file_ino > 0 &&
949 a->st.st_dev == a->skip_file_dev &&
950 a->st.st_ino == a->skip_file_ino) {
951 archive_set_error(&a->archive, 0, "Refusing to overwrite archive");
952 return (ARCHIVE_FAILED);
955 if (!S_ISDIR(a->st.st_mode)) {
956 /* A non-dir is in the way, unlink it. */
957 if (unlink(a->name) != 0) {
958 archive_set_error(&a->archive, errno,
959 "Can't unlink already-existing object");
960 return (ARCHIVE_WARN);
964 en = create_filesystem_object(a);
965 } else if (!S_ISDIR(a->mode)) {
966 /* A dir is in the way of a non-dir, rmdir it. */
967 if (rmdir(a->name) != 0) {
968 archive_set_error(&a->archive, errno,
969 "Can't remove already-existing dir");
970 return (ARCHIVE_WARN);
973 en = create_filesystem_object(a);
976 * There's a dir in the way of a dir. Don't
977 * waste time with rmdir()/mkdir(), just fix
978 * up the permissions on the existing dir.
979 * Note that we don't change perms on existing
980 * dirs unless _EXTRACT_PERM is specified.
982 if ((a->mode != a->st.st_mode)
983 && (a->todo & TODO_MODE_FORCE))
984 a->deferred |= (a->todo & TODO_MODE);
985 /* Ownership doesn't need deferred fixup. */
986 en = 0; /* Forget the EEXIST. */
991 /* Everything failed; give up here. */
992 archive_set_error(&a->archive, en, "Can't create '%s'", a->name);
993 return (ARCHIVE_WARN);
996 a->pst = NULL; /* Cached stat data no longer valid. */
1001 * Returns 0 if creation succeeds, or else returns errno value from
1002 * the failed system call. Note: This function should only ever perform
1003 * a single system call.
1006 create_filesystem_object(struct archive_write_disk *a)
1008 /* Create the entry. */
1009 const char *linkname;
1010 mode_t final_mode, mode;
1013 /* We identify hard/symlinks according to the link names. */
1014 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
1015 linkname = archive_entry_hardlink(a->entry);
1016 if (linkname != NULL) {
1017 r = link(linkname, a->name) ? errno : 0;
1019 * New cpio and pax formats allow hardlink entries
1020 * to carry data, so we may have to open the file
1021 * for hardlink entries.
1023 * If the hardlink was successfully created and
1024 * the archive doesn't have carry data for it,
1025 * consider it to be non-authoritive for meta data.
1026 * This is consistent with GNU tar and BSD pax.
1027 * If the hardlink does carry data, let the last
1028 * archive entry decide ownership.
1030 if (r == 0 && a->filesize <= 0) {
1033 } if (r == 0 && a->filesize > 0) {
1034 a->fd = open(a->name, O_WRONLY | O_TRUNC | O_BINARY);
1040 linkname = archive_entry_symlink(a->entry);
1041 if (linkname != NULL)
1042 return symlink(linkname, a->name) ? errno : 0;
1045 * The remaining system calls all set permissions, so let's
1046 * try to take advantage of that to avoid an extra chmod()
1047 * call. (Recall that umask is set to zero right now!)
1050 /* Mode we want for the final restored object (w/o file type bits). */
1051 final_mode = a->mode & 07777;
1053 * The mode that will actually be restored in this step. Note
1054 * that SUID, SGID, etc, require additional work to ensure
1055 * security, so we never restore them at this point.
1057 mode = final_mode & 0777;
1059 switch (a->mode & AE_IFMT) {
1061 /* POSIX requires that we fall through here. */
1064 a->fd = open(a->name,
1065 O_WRONLY | O_CREAT | O_EXCL | O_BINARY, mode);
1070 /* Note: we use AE_IFCHR for the case label, and
1071 * S_IFCHR for the mknod() call. This is correct. */
1072 r = mknod(a->name, mode | S_IFCHR,
1073 archive_entry_rdev(a->entry));
1075 /* TODO: Find a better way to warn about our inability
1076 * to restore a char device node. */
1078 #endif /* HAVE_MKNOD */
1082 r = mknod(a->name, mode | S_IFBLK,
1083 archive_entry_rdev(a->entry));
1085 /* TODO: Find a better way to warn about our inability
1086 * to restore a block device node. */
1088 #endif /* HAVE_MKNOD */
1091 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
1092 r = mkdir(a->name, mode);
1094 /* Defer setting dir times. */
1095 a->deferred |= (a->todo & TODO_TIMES);
1096 a->todo &= ~TODO_TIMES;
1097 /* Never use an immediate chmod(). */
1098 /* We can't avoid the chmod() entirely if EXTRACT_PERM
1099 * because of SysV SGID inheritance. */
1100 if ((mode != final_mode)
1101 || (a->flags & ARCHIVE_EXTRACT_PERM))
1102 a->deferred |= (a->todo & TODO_MODE);
1103 a->todo &= ~TODO_MODE;
1108 r = mkfifo(a->name, mode);
1110 /* TODO: Find a better way to warn about our inability
1111 * to restore a fifo. */
1113 #endif /* HAVE_MKFIFO */
1117 /* All the system calls above set errno on failure. */
1121 /* If we managed to set the final mode, we've avoided a chmod(). */
1122 if (mode == final_mode)
1123 a->todo &= ~TODO_MODE;
1128 * Cleanup function for archive_extract. Mostly, this involves processing
1129 * the fixup list, which is used to address a number of problems:
1130 * * Dir permissions might prevent us from restoring a file in that
1131 * dir, so we restore the dir with minimum 0700 permissions first,
1132 * then correct the mode at the end.
1133 * * Similarly, the act of restoring a file touches the directory
1134 * and changes the timestamp on the dir, so we have to touch-up dir
1135 * timestamps at the end as well.
1136 * * Some file flags can interfere with the restore by, for example,
1137 * preventing the creation of hardlinks to those files.
1139 * Note that tar/cpio do not require that archives be in a particular
1140 * order; there is no way to know when the last file has been restored
1141 * within a directory, so there's no way to optimize the memory usage
1142 * here by fixing up the directory any earlier than the
1145 * XXX TODO: Directory ACLs should be restored here, for the same
1146 * reason we set directory perms here. XXX
1149 _archive_write_close(struct archive *_a)
1151 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1152 struct fixup_entry *next, *p;
1155 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1156 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1157 "archive_write_disk_close");
1158 ret = _archive_write_finish_entry(&a->archive);
1160 /* Sort dir list so directories are fixed up in depth-first order. */
1161 p = sort_dir_list(a->fixup_list);
1164 a->pst = NULL; /* Mark stat cache as out-of-date. */
1165 if (p->fixup & TODO_TIMES) {
1167 /* {f,l,}utimes() are preferred, when available. */
1168 struct timeval times[2];
1169 times[1].tv_sec = p->mtime;
1170 times[1].tv_usec = p->mtime_nanos / 1000;
1171 times[0].tv_sec = p->atime;
1172 times[0].tv_usec = p->atime_nanos / 1000;
1174 lutimes(p->name, times);
1176 utimes(p->name, times);
1179 /* utime() is more portable, but less precise. */
1180 struct utimbuf times;
1181 times.modtime = p->mtime;
1182 times.actime = p->atime;
1184 utime(p->name, ×);
1187 if (p->fixup & TODO_MODE_BASE)
1188 chmod(p->name, p->mode);
1190 if (p->fixup & TODO_FFLAGS)
1191 set_fflags_platform(a, -1, p->name,
1192 p->mode, p->fflags_set, 0);
1199 a->fixup_list = NULL;
1204 _archive_write_finish(struct archive *_a)
1206 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1208 ret = _archive_write_close(&a->archive);
1209 if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1210 (a->cleanup_gid)(a->lookup_gid_data);
1211 if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1212 (a->cleanup_uid)(a->lookup_uid_data);
1213 archive_string_free(&a->_name_data);
1214 archive_string_free(&a->archive.error_string);
1215 archive_string_free(&a->path_safe);
1221 * Simple O(n log n) merge sort to order the fixup list. In
1222 * particular, we want to restore dir timestamps depth-first.
1224 static struct fixup_entry *
1225 sort_dir_list(struct fixup_entry *p)
1227 struct fixup_entry *a, *b, *t;
1231 /* A one-item list is already sorted. */
1232 if (p->next == NULL)
1235 /* Step 1: split the list. */
1239 /* Step a twice, t once. */
1245 /* Now, t is at the mid-point, so break the list here. */
1250 /* Step 2: Recursively sort the two sub-lists. */
1251 a = sort_dir_list(a);
1252 b = sort_dir_list(b);
1254 /* Step 3: Merge the returned lists. */
1255 /* Pick the first element for the merged list. */
1256 if (strcmp(a->name, b->name) > 0) {
1264 /* Always put the later element on the list first. */
1265 while (a != NULL && b != NULL) {
1266 if (strcmp(a->name, b->name) > 0) {
1276 /* Only one list is non-empty, so just splice it on. */
1286 * Returns a new, initialized fixup entry.
1288 * TODO: Reduce the memory requirements for this list by using a tree
1289 * structure rather than a simple list of names.
1291 static struct fixup_entry *
1292 new_fixup(struct archive_write_disk *a, const char *pathname)
1294 struct fixup_entry *fe;
1296 fe = (struct fixup_entry *)malloc(sizeof(struct fixup_entry));
1299 fe->next = a->fixup_list;
1302 fe->name = strdup(pathname);
1307 * Returns a fixup structure for the current entry.
1309 static struct fixup_entry *
1310 current_fixup(struct archive_write_disk *a, const char *pathname)
1312 if (a->current_fixup == NULL)
1313 a->current_fixup = new_fixup(a, pathname);
1314 return (a->current_fixup);
1317 /* TODO: Make this work. */
1319 * TODO: The deep-directory support bypasses this; disable deep directory
1320 * support if we're doing symlink checks.
1323 * TODO: Someday, integrate this with the deep dir support; they both
1324 * scan the path and both can be optimized by comparing against other
1328 check_symlinks(struct archive_write_disk *a)
1336 * Guard against symlink tricks. Reject any archive entry whose
1337 * destination would be altered by a symlink.
1339 /* Whatever we checked last time doesn't need to be re-checked. */
1342 while ((*pn != '\0') && (*p == *pn))
1345 /* Keep going until we've checked the entire name. */
1346 while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
1347 /* Skip the next path element. */
1348 while (*pn != '\0' && *pn != '/')
1352 /* Check that we haven't hit a symlink. */
1353 r = lstat(a->name, &st);
1355 /* We've hit a dir that doesn't exist; stop now. */
1356 if (errno == ENOENT)
1358 } else if (S_ISLNK(st.st_mode)) {
1361 * Last element is symlink; remove it
1362 * so we can overwrite it with the
1363 * item being extracted.
1365 if (unlink(a->name)) {
1366 archive_set_error(&a->archive, errno,
1367 "Could not remove symlink %s",
1370 return (ARCHIVE_WARN);
1374 * Even if we did remove it, a warning
1375 * is in order. The warning is silly,
1376 * though, if we're just replacing one
1377 * symlink with another symlink.
1379 if (!S_ISLNK(a->mode)) {
1380 archive_set_error(&a->archive, 0,
1381 "Removing symlink %s",
1384 /* Symlink gone. No more problem! */
1387 } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
1388 /* User asked us to remove problems. */
1389 if (unlink(a->name) != 0) {
1390 archive_set_error(&a->archive, 0,
1391 "Cannot remove intervening symlink %s",
1394 return (ARCHIVE_WARN);
1398 archive_set_error(&a->archive, 0,
1399 "Cannot extract through symlink %s",
1402 return (ARCHIVE_WARN);
1407 /* We've checked and/or cleaned the whole path, so remember it. */
1408 archive_strcpy(&a->path_safe, a->name);
1409 return (ARCHIVE_OK);
1413 * Canonicalize the pathname. In particular, this strips duplicate
1414 * '/' characters, '.' elements, and trailing '/'. It also raises an
1415 * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
1416 * set) any '..' in the path.
1419 cleanup_pathname(struct archive_write_disk *a)
1422 char separator = '\0';
1424 dest = src = a->name;
1426 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1427 "Invalid empty pathname");
1428 return (ARCHIVE_FAILED);
1431 /* Skip leading '/'. */
1435 /* Scan the pathname one element at a time. */
1437 /* src points to first char after '/' */
1438 if (src[0] == '\0') {
1440 } else if (src[0] == '/') {
1441 /* Found '//', ignore second one. */
1444 } else if (src[0] == '.') {
1445 if (src[1] == '\0') {
1446 /* Ignore trailing '.' */
1448 } else if (src[1] == '/') {
1452 } else if (src[1] == '.') {
1453 if (src[2] == '/' || src[2] == '\0') {
1454 /* Conditionally warn about '..' */
1455 if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
1456 archive_set_error(&a->archive,
1458 "Path contains '..'");
1459 return (ARCHIVE_FAILED);
1463 * Note: Under no circumstances do we
1464 * remove '..' elements. In
1465 * particular, restoring
1466 * '/foo/../bar/' should create the
1467 * 'foo' dir as a side-effect.
1472 /* Copy current element, including leading '/'. */
1475 while (*src != '\0' && *src != '/') {
1482 /* Skip '/' separator. */
1486 * We've just copied zero or more path elements, not including the
1489 if (dest == a->name) {
1491 * Nothing got copied. The path must have been something
1492 * like '.' or '/' or './' or '/././././/./'.
1499 /* Terminate the result. */
1501 return (ARCHIVE_OK);
1505 * Create the parent directory of the specified path, assuming path
1506 * is already in mutable storage.
1509 create_parent_dir(struct archive_write_disk *a, char *path)
1514 /* Remove tail element to obtain parent name. */
1515 slash = strrchr(path, '/');
1517 return (ARCHIVE_OK);
1519 r = create_dir(a, path);
1525 * Create the specified dir, recursing to create parents as necessary.
1527 * Returns ARCHIVE_OK if the path exists when we're done here.
1528 * Otherwise, returns ARCHIVE_WARN.
1529 * Assumes path is in mutable storage; path is unchanged on exit.
1532 create_dir(struct archive_write_disk *a, char *path)
1535 struct fixup_entry *le;
1537 mode_t mode_final, mode;
1542 /* Check for special names and just skip them. */
1543 slash = strrchr(path, '/');
1549 if (base[0] == '\0' ||
1550 (base[0] == '.' && base[1] == '\0') ||
1551 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
1552 /* Don't bother trying to create null path, '.', or '..'. */
1553 if (slash != NULL) {
1555 r = create_dir(a, path);
1559 return (ARCHIVE_OK);
1563 * Yes, this should be stat() and not lstat(). Using lstat()
1564 * here loses the ability to extract through symlinks. Also note
1565 * that this should not use the a->st cache.
1567 if (stat(path, &st) == 0) {
1568 if (S_ISDIR(st.st_mode))
1569 return (ARCHIVE_OK);
1570 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1571 archive_set_error(&a->archive, EEXIST,
1572 "Can't create directory '%s'", path);
1573 return (ARCHIVE_WARN);
1575 if (unlink(path) != 0) {
1576 archive_set_error(&a->archive, errno,
1577 "Can't create directory '%s': "
1578 "Conflicting file cannot be removed");
1579 return (ARCHIVE_WARN);
1581 } else if (errno != ENOENT && errno != ENOTDIR) {
1583 archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
1584 return (ARCHIVE_WARN);
1585 } else if (slash != NULL) {
1587 r = create_dir(a, path);
1589 if (r != ARCHIVE_OK)
1594 * Mode we want for the final restored directory. Per POSIX,
1595 * implicitly-created dirs must be created obeying the umask.
1596 * There's no mention whether this is different for privileged
1597 * restores (which the rest of this code handles by pretending
1598 * umask=0). I've chosen here to always obey the user's umask for
1599 * implicit dirs, even if _EXTRACT_PERM was specified.
1601 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
1602 /* Mode we want on disk during the restore process. */
1604 mode |= MINIMUM_DIR_MODE;
1605 mode &= MAXIMUM_DIR_MODE;
1606 if (mkdir(path, mode) == 0) {
1607 if (mode != mode_final) {
1608 le = new_fixup(a, path);
1609 le->fixup |=TODO_MODE_BASE;
1610 le->mode = mode_final;
1612 return (ARCHIVE_OK);
1616 * Without the following check, a/b/../b/c/d fails at the
1617 * second visit to 'b', so 'd' can't be created. Note that we
1618 * don't add it to the fixup list here, as it's already been
1621 if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1622 return (ARCHIVE_OK);
1624 archive_set_error(&a->archive, errno, "Failed to create dir '%s'", path);
1625 return (ARCHIVE_WARN);
1629 * Note: Although we can skip setting the user id if the desired user
1630 * id matches the current user, we cannot skip setting the group, as
1631 * many systems set the gid based on the containing directory. So
1632 * we have to perform a chown syscall if we want to set the SGID
1633 * bit. (The alternative is to stat() and then possibly chown(); it's
1634 * more efficient to skip the stat() and just always chown().) Note
1635 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
1636 * allows set_mode to skip the stat() check for the GID.
1639 set_ownership(struct archive_write_disk *a)
1641 /* If we know we can't change it, don't bother trying. */
1642 if (a->user_uid != 0 && a->user_uid != a->uid) {
1643 archive_set_error(&a->archive, errno,
1644 "Can't set UID=%d", a->uid);
1645 return (ARCHIVE_WARN);
1649 /* If we have an fd, we can avoid a race. */
1650 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
1651 /* We've set owner and know uid/gid are correct. */
1652 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1653 return (ARCHIVE_OK);
1657 /* We prefer lchown() but will use chown() if that's all we have. */
1658 /* Of course, if we have neither, this will always fail. */
1660 if (lchown(a->name, a->uid, a->gid) == 0) {
1661 /* We've set owner and know uid/gid are correct. */
1662 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1663 return (ARCHIVE_OK);
1666 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
1667 /* We've set owner and know uid/gid are correct. */
1668 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1669 return (ARCHIVE_OK);
1673 archive_set_error(&a->archive, errno,
1674 "Can't set user=%d/group=%d for %s", a->uid, a->gid,
1676 return (ARCHIVE_WARN);
1681 * The utimes()-family functions provide high resolution and
1682 * a way to set time on an fd or a symlink. We prefer them
1683 * when they're available.
1686 set_time(struct archive_write_disk *a)
1688 struct timeval times[2];
1690 /* If no time was provided, we're done. */
1691 if (!archive_entry_atime_is_set(a->entry)
1692 && !archive_entry_mtime_is_set(a->entry))
1693 return (ARCHIVE_OK);
1695 /* We know at least one is set, so... */
1696 if (archive_entry_mtime_is_set(a->entry)) {
1697 times[1].tv_sec = archive_entry_mtime(a->entry);
1698 times[1].tv_usec = archive_entry_mtime_nsec(a->entry) / 1000;
1700 times[1].tv_sec = a->start_time;
1701 times[1].tv_usec = 0;
1704 /* If no atime was specified, use start time instead. */
1705 /* In theory, it would be marginally more correct to use
1706 * time(NULL) here, but that would cost us an extra syscall
1707 * for little gain. */
1708 if (archive_entry_atime_is_set(a->entry)) {
1709 times[0].tv_sec = archive_entry_atime(a->entry);
1710 times[0].tv_usec = archive_entry_atime_nsec(a->entry) / 1000;
1712 times[0].tv_sec = a->start_time;
1713 times[0].tv_usec = 0;
1717 if (a->fd >= 0 && futimes(a->fd, times) == 0) {
1718 return (ARCHIVE_OK);
1723 if (lutimes(a->name, times) != 0)
1725 if (!S_ISLNK(a->mode) && utimes(a->name, times) != 0)
1728 archive_set_error(&a->archive, errno, "Can't update time for %s",
1730 return (ARCHIVE_WARN);
1734 * Note: POSIX does not provide a portable way to restore ctime.
1735 * (Apart from resetting the system clock, which is distasteful.)
1736 * So, any restoration of ctime will necessarily be OS-specific.
1739 /* XXX TODO: Can FreeBSD restore ctime? XXX */
1740 return (ARCHIVE_OK);
1742 #elif defined(HAVE_UTIME)
1744 * utime() is an older, more standard interface that we'll use
1745 * if utimes() isn't available.
1748 set_time(struct archive_write_disk *a)
1750 struct utimbuf times;
1752 /* If no time was provided, we're done. */
1753 if (!archive_entry_atime_is_set(a->entry)
1754 && !archive_entry_mtime_is_set(a->entry))
1755 return (ARCHIVE_OK);
1757 /* We know at least one is set, so... */
1758 /* Set mtime from mtime if set, else start time. */
1759 if (archive_entry_mtime_is_set(a->entry))
1760 times.modtime = archive_entry_mtime(a->entry);
1762 times.modtime = a->start_time;
1764 /* Set atime from provided atime, else mtime. */
1765 if (archive_entry_atime_is_set(a->entry))
1766 times.actime = archive_entry_atime(a->entry);
1768 times.actime = a->start_time;
1770 if (!S_ISLNK(a->mode) && utime(a->name, ×) != 0) {
1771 archive_set_error(&a->archive, errno,
1772 "Can't update time for %s", a->name);
1773 return (ARCHIVE_WARN);
1775 return (ARCHIVE_OK);
1778 /* This platform doesn't give us a way to restore the time. */
1780 set_time(struct archive_write_disk *a)
1782 (void)a; /* UNUSED */
1783 archive_set_error(&a->archive, errno,
1784 "Can't update time for %s", a->name);
1785 return (ARCHIVE_WARN);
1791 set_mode(struct archive_write_disk *a, int mode)
1794 mode &= 07777; /* Strip off file type bits. */
1796 if (a->todo & TODO_SGID_CHECK) {
1798 * If we don't know the GID is right, we must stat()
1799 * to verify it. We can't just check the GID of this
1800 * process, since systems sometimes set GID from
1801 * the enclosing dir or based on ACLs.
1803 if ((r = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
1805 if (a->pst->st_gid != a->gid) {
1807 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1809 * This is only an error if you
1810 * requested owner restore. If you
1811 * didn't, we'll try to restore
1812 * sgid/suid, but won't consider it a
1813 * problem if we can't.
1815 archive_set_error(&a->archive, -1,
1816 "Can't restore SGID bit");
1820 /* While we're here, double-check the UID. */
1821 if (a->pst->st_uid != a->uid
1822 && (a->todo & TODO_SUID)) {
1824 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1825 archive_set_error(&a->archive, -1,
1826 "Can't restore SUID bit");
1830 a->todo &= ~TODO_SGID_CHECK;
1831 a->todo &= ~TODO_SUID_CHECK;
1832 } else if (a->todo & TODO_SUID_CHECK) {
1834 * If we don't know the UID is right, we can just check
1835 * the user, since all systems set the file UID from
1838 if (a->user_uid != a->uid) {
1840 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1841 archive_set_error(&a->archive, -1,
1842 "Can't make file SUID");
1846 a->todo &= ~TODO_SUID_CHECK;
1849 if (S_ISLNK(a->mode)) {
1852 * If this is a symlink, use lchmod(). If the
1853 * platform doesn't support lchmod(), just skip it. A
1854 * platform that doesn't provide a way to set
1855 * permissions on symlinks probably ignores
1856 * permissions on symlinks, so a failure here has no
1859 if (lchmod(a->name, mode) != 0) {
1860 archive_set_error(&a->archive, errno,
1861 "Can't set permissions to 0%o", (int)mode);
1865 } else if (!S_ISDIR(a->mode)) {
1867 * If it's not a symlink and not a dir, then use
1868 * fchmod() or chmod(), depending on whether we have
1869 * an fd. Dirs get their perms set during the
1870 * post-extract fixup, which is handled elsewhere.
1874 if (fchmod(a->fd, mode) != 0) {
1875 archive_set_error(&a->archive, errno,
1876 "Can't set permissions to 0%o", (int)mode);
1881 /* If this platform lacks fchmod(), then
1882 * we'll just use chmod(). */
1883 if (chmod(a->name, mode) != 0) {
1884 archive_set_error(&a->archive, errno,
1885 "Can't set permissions to 0%o", (int)mode);
1893 set_fflags(struct archive_write_disk *a)
1895 struct fixup_entry *le;
1896 unsigned long set, clear;
1899 mode_t mode = archive_entry_mode(a->entry);
1902 * Make 'critical_flags' hold all file flags that can't be
1903 * immediately restored. For example, on BSD systems,
1904 * SF_IMMUTABLE prevents hardlinks from being created, so
1905 * should not be set until after any hardlinks are created. To
1906 * preserve some semblance of portability, this uses #ifdef
1907 * extensively. Ugly, but it works.
1909 * Yes, Virginia, this does create a security race. It's mitigated
1910 * somewhat by the practice of creating dirs 0700 until the extract
1911 * is done, but it would be nice if we could do more than that.
1912 * People restoring critical file systems should be wary of
1913 * other programs that might try to muck with files as they're
1916 /* Hopefully, the compiler will optimize this mess into a constant. */
1919 critical_flags |= SF_IMMUTABLE;
1922 critical_flags |= UF_IMMUTABLE;
1925 critical_flags |= SF_APPEND;
1928 critical_flags |= UF_APPEND;
1930 #ifdef EXT2_APPEND_FL
1931 critical_flags |= EXT2_APPEND_FL;
1933 #ifdef EXT2_IMMUTABLE_FL
1934 critical_flags |= EXT2_IMMUTABLE_FL;
1937 if (a->todo & TODO_FFLAGS) {
1938 archive_entry_fflags(a->entry, &set, &clear);
1941 * The first test encourages the compiler to eliminate
1942 * all of this if it's not necessary.
1944 if ((critical_flags != 0) && (set & critical_flags)) {
1945 le = current_fixup(a, a->name);
1946 le->fixup |= TODO_FFLAGS;
1947 le->fflags_set = set;
1948 /* Store the mode if it's not already there. */
1949 if ((le->fixup & TODO_MODE) == 0)
1952 r = set_fflags_platform(a, a->fd,
1953 a->name, mode, set, clear);
1954 if (r != ARCHIVE_OK)
1958 return (ARCHIVE_OK);
1962 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && !defined(__linux)
1964 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1965 mode_t mode, unsigned long set, unsigned long clear)
1969 (void)mode; /* UNUSED */
1970 if (set == 0 && clear == 0)
1971 return (ARCHIVE_OK);
1974 * XXX Is the stat here really necessary? Or can I just use
1975 * the 'set' flags directly? In particular, I'm not sure
1976 * about the correct approach if we're overwriting an existing
1977 * file that already has flags on it. XXX
1979 if ((r = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
1982 a->st.st_flags &= ~clear;
1983 a->st.st_flags |= set;
1984 #ifdef HAVE_FCHFLAGS
1985 /* If platform has fchflags() and we were given an fd, use it. */
1986 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
1987 return (ARCHIVE_OK);
1990 * If we can't use the fd to set the flags, we'll use the
1991 * pathname to set flags. We prefer lchflags() but will use
1992 * chflags() if we must.
1994 #ifdef HAVE_LCHFLAGS
1995 if (lchflags(name, a->st.st_flags) == 0)
1996 return (ARCHIVE_OK);
1997 #elif defined(HAVE_CHFLAGS)
1998 if (S_ISLNK(a->st.st_mode)) {
1999 archive_set_error(&a->archive, errno,
2000 "Can't set file flags on symlink.");
2001 return (ARCHIVE_WARN);
2003 if (chflags(name, a->st.st_flags) == 0)
2004 return (ARCHIVE_OK);
2006 archive_set_error(&a->archive, errno,
2007 "Failed to set file flags");
2008 return (ARCHIVE_WARN);
2011 #elif defined(__linux) && defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS)
2014 * Linux has flags too, but uses ioctl() to access them instead of
2015 * having a separate chflags() system call.
2018 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2019 mode_t mode, unsigned long set, unsigned long clear)
2023 unsigned long newflags, oldflags;
2024 unsigned long sf_mask = 0;
2026 if (set == 0 && clear == 0)
2027 return (ARCHIVE_OK);
2028 /* Only regular files and dirs can have flags. */
2029 if (!S_ISREG(mode) && !S_ISDIR(mode))
2030 return (ARCHIVE_OK);
2032 /* If we weren't given an fd, open it ourselves. */
2034 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY);
2036 return (ARCHIVE_OK);
2039 * Linux has no define for the flags that are only settable by
2040 * the root user. This code may seem a little complex, but
2041 * there seem to be some Linux systems that lack these
2042 * defines. (?) The code below degrades reasonably gracefully
2043 * if sf_mask is incomplete.
2045 #ifdef EXT2_IMMUTABLE_FL
2046 sf_mask |= EXT2_IMMUTABLE_FL;
2048 #ifdef EXT2_APPEND_FL
2049 sf_mask |= EXT2_APPEND_FL;
2052 * XXX As above, this would be way simpler if we didn't have
2053 * to read the current flags from disk. XXX
2056 /* Try setting the flags as given. */
2057 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
2058 newflags = (oldflags & ~clear) | set;
2059 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
2064 /* If we couldn't set all the flags, try again with a subset. */
2065 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
2066 newflags &= ~sf_mask;
2067 oldflags &= sf_mask;
2068 newflags |= oldflags;
2069 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
2072 /* We couldn't set the flags, so report the failure. */
2074 archive_set_error(&a->archive, errno,
2075 "Failed to set file flags");
2083 #else /* Not HAVE_CHFLAGS && Not __linux */
2086 * Of course, some systems have neither BSD chflags() nor Linux' flags
2087 * support through ioctl().
2090 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2091 mode_t mode, unsigned long set, unsigned long clear)
2093 (void)a; /* UNUSED */
2094 (void)fd; /* UNUSED */
2095 (void)name; /* UNUSED */
2096 (void)mode; /* UNUSED */
2097 (void)set; /* UNUSED */
2098 (void)clear; /* UNUSED */
2099 return (ARCHIVE_OK);
2102 #endif /* __linux */
2104 #ifndef HAVE_POSIX_ACL
2105 /* Default empty function body to satisfy mainline code. */
2107 set_acls(struct archive_write_disk *a)
2109 (void)a; /* UNUSED */
2110 return (ARCHIVE_OK);
2116 * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
2119 set_acls(struct archive_write_disk *a)
2123 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_ACCESS,
2124 ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
2125 if (ret != ARCHIVE_OK)
2127 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_DEFAULT,
2128 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
2134 set_acl(struct archive_write_disk *a, int fd, struct archive_entry *entry,
2135 acl_type_t acl_type, int ae_requested_type, const char *tname)
2138 acl_entry_t acl_entry;
2139 acl_permset_t acl_permset;
2141 int ae_type, ae_permset, ae_tag, ae_id;
2144 const char *ae_name;
2149 entries = archive_entry_acl_reset(entry, ae_requested_type);
2151 return (ARCHIVE_OK);
2152 acl = acl_init(entries);
2153 while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
2154 &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
2155 acl_create_entry(&acl, &acl_entry);
2158 case ARCHIVE_ENTRY_ACL_USER:
2159 acl_set_tag_type(acl_entry, ACL_USER);
2160 ae_uid = a->lookup_uid(a->lookup_uid_data,
2162 acl_set_qualifier(acl_entry, &ae_uid);
2164 case ARCHIVE_ENTRY_ACL_GROUP:
2165 acl_set_tag_type(acl_entry, ACL_GROUP);
2166 ae_gid = a->lookup_gid(a->lookup_gid_data,
2168 acl_set_qualifier(acl_entry, &ae_gid);
2170 case ARCHIVE_ENTRY_ACL_USER_OBJ:
2171 acl_set_tag_type(acl_entry, ACL_USER_OBJ);
2173 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
2174 acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
2176 case ARCHIVE_ENTRY_ACL_MASK:
2177 acl_set_tag_type(acl_entry, ACL_MASK);
2179 case ARCHIVE_ENTRY_ACL_OTHER:
2180 acl_set_tag_type(acl_entry, ACL_OTHER);
2187 acl_get_permset(acl_entry, &acl_permset);
2188 acl_clear_perms(acl_permset);
2189 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
2190 acl_add_perm(acl_permset, ACL_EXECUTE);
2191 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
2192 acl_add_perm(acl_permset, ACL_WRITE);
2193 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
2194 acl_add_perm(acl_permset, ACL_READ);
2197 name = archive_entry_pathname(entry);
2199 /* Try restoring the ACL through 'fd' if we can. */
2201 if (fd >= 0 && acl_type == ACL_TYPE_ACCESS && acl_set_fd(fd, acl) == 0)
2205 #if HAVE_ACL_SET_FD_NP
2206 if (fd >= 0 && acl_set_fd_np(fd, acl, acl_type) == 0)
2211 if (acl_set_file(name, acl_type, acl) != 0) {
2212 archive_set_error(&a->archive, errno, "Failed to set %s acl", tname);
2222 * Restore extended attributes - Linux implementation
2225 set_xattrs(struct archive_write_disk *a)
2227 struct archive_entry *entry = a->entry;
2228 static int warning_done = 0;
2229 int ret = ARCHIVE_OK;
2230 int i = archive_entry_xattr_reset(entry);
2236 archive_entry_xattr_next(entry, &name, &value, &size);
2238 strncmp(name, "xfsroot.", 8) != 0 &&
2239 strncmp(name, "system.", 7) != 0) {
2243 e = fsetxattr(a->fd, name, value, size, 0);
2247 e = lsetxattr(archive_entry_pathname(entry),
2248 name, value, size, 0);
2251 if (errno == ENOTSUP) {
2252 if (!warning_done) {
2254 archive_set_error(&a->archive, errno,
2255 "Cannot restore extended "
2256 "attributes on this file "
2260 archive_set_error(&a->archive, errno,
2261 "Failed to set extended attribute");
2265 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2266 "Invalid extended attribute encountered");
2274 * Restore extended attributes - stub implementation for unsupported systems
2277 set_xattrs(struct archive_write_disk *a)
2279 static int warning_done = 0;
2281 /* If there aren't any extended attributes, then it's okay not
2282 * to extract them, otherwise, issue a single warning. */
2283 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
2285 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2286 "Cannot restore extended attributes on this system");
2287 return (ARCHIVE_WARN);
2289 /* Warning was already emitted; suppress further warnings. */
2290 return (ARCHIVE_OK);
2296 * Trivial implementations of gid/uid lookup functions.
2297 * These are normally overridden by the client, but these stub
2298 * versions ensure that we always have something that works.
2301 trivial_lookup_gid(void *private_data, const char *gname, gid_t gid)
2303 (void)private_data; /* UNUSED */
2304 (void)gname; /* UNUSED */
2309 trivial_lookup_uid(void *private_data, const char *uname, uid_t uid)
2311 (void)private_data; /* UNUSED */
2312 (void)uname; /* UNUSED */
2317 * Test if file on disk is older than entry.
2320 older(struct stat *st, struct archive_entry *entry)
2322 /* First, test the seconds and return if we have a definite answer. */
2323 /* Definitely older. */
2324 if (st->st_mtime < archive_entry_mtime(entry))
2326 /* Definitely younger. */
2327 if (st->st_mtime > archive_entry_mtime(entry))
2329 /* If this platform supports fractional seconds, try those. */
2330 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
2331 /* Definitely older. */
2332 if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
2334 /* Definitely younger. */
2335 if (st->st_mtimespec.tv_nsec > archive_entry_mtime_nsec(entry))
2337 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
2338 /* Definitely older. */
2339 if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
2341 /* Definitely older. */
2342 if (st->st_mtim.tv_nsec > archive_entry_mtime_nsec(entry))
2345 /* This system doesn't have high-res timestamps. */
2347 /* Same age, so not older. */