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 */
67 #ifdef HAVE_LINUX_EXT2_FS_H
68 #include <linux/ext2_fs.h> /* for Linux file flags */
91 #include "archive_string.h"
92 #include "archive_entry.h"
93 #include "archive_private.h"
100 struct fixup_entry *next;
104 unsigned long mtime_nanos;
105 unsigned long atime_nanos;
106 unsigned long fflags_set;
107 int fixup; /* bitmask of what needs fixing */
112 * We use a bitmask to track which operations remain to be done for
113 * this file. In particular, this helps us avoid unnecessary
114 * operations when it's possible to take care of one step as a
115 * side-effect of another. For example, mkdir() can specify the mode
116 * for the newly-created object but symlink() cannot. This means we
117 * can skip chmod() if mkdir() succeeded, but we must explicitly
118 * chmod() if we're trying to create a directory that already exists
119 * (mkdir() failed) or if we're restoring a symlink. Similarly, we
120 * need to verify UID/GID before trying to restore SUID/SGID bits;
121 * that verification can occur explicitly through a stat() call or
122 * implicitly because of a successful chown() call.
124 #define TODO_MODE_FORCE 0x40000000
125 #define TODO_MODE_BASE 0x20000000
126 #define TODO_SUID 0x10000000
127 #define TODO_SUID_CHECK 0x08000000
128 #define TODO_SGID 0x04000000
129 #define TODO_SGID_CHECK 0x02000000
130 #define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
131 #define TODO_TIMES ARCHIVE_EXTRACT_TIME
132 #define TODO_OWNER ARCHIVE_EXTRACT_OWNER
133 #define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS
134 #define TODO_ACLS ARCHIVE_EXTRACT_ACL
135 #define TODO_XATTR ARCHIVE_EXTRACT_XATTR
137 struct archive_write_disk {
138 struct archive archive;
141 struct fixup_entry *fixup_list;
142 struct fixup_entry *current_fixup;
147 gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid);
148 void (*cleanup_gid)(void *private);
149 void *lookup_gid_data;
150 uid_t (*lookup_uid)(void *private, const char *gname, gid_t gid);
151 void (*cleanup_uid)(void *private);
152 void *lookup_uid_data;
155 * Full path of last file to satisfy symlink checks.
157 struct archive_string path_safe;
160 * Cached stat data from disk for the current entry.
161 * If this is valid, pst points to st. Otherwise,
167 /* Information about the object being restored right now. */
168 struct archive_entry *entry; /* Entry being extracted. */
169 char *name; /* Name of entry, possibly edited. */
170 struct archive_string _name_data; /* backing store for 'name' */
171 /* Tasks remaining for this object. */
173 /* Tasks deferred until end-of-archive. */
175 /* Options requested by the client. */
177 /* Handle for the file we're restoring. */
179 /* Current offset for writing data to the file. */
181 /* Maximum size of file. */
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);
236 static struct archive_vtable *archive_write_disk_vtable(void);
238 static int _archive_write_close(struct archive *);
239 static int _archive_write_finish(struct archive *);
240 static int _archive_write_header(struct archive *, struct archive_entry *);
241 static int _archive_write_finish_entry(struct archive *);
242 static ssize_t _archive_write_data(struct archive *, const void *, size_t);
243 static ssize_t _archive_write_data_block(struct archive *, const void *, size_t, off_t);
245 static struct archive_vtable *
246 archive_write_disk_vtable(void)
248 static struct archive_vtable av;
249 static int inited = 0;
252 av.archive_write_close = _archive_write_close;
253 av.archive_write_finish = _archive_write_finish;
254 av.archive_write_header = _archive_write_header;
255 av.archive_write_finish_entry = _archive_write_finish_entry;
256 av.archive_write_data = _archive_write_data;
257 av.archive_write_data_block = _archive_write_data_block;
264 archive_write_disk_set_options(struct archive *_a, int flags)
266 struct archive_write_disk *a = (struct archive_write_disk *)_a;
274 * Extract this entry to disk.
276 * TODO: Validate hardlinks. According to the standards, we're
277 * supposed to check each extracted hardlink and squawk if it refers
278 * to a file that we didn't restore. I'm not entirely convinced this
279 * is a good idea, but more importantly: Is there any way to validate
280 * hardlinks without keeping a complete list of filenames from the
281 * entire archive?? Ugh.
285 _archive_write_header(struct archive *_a, struct archive_entry *entry)
287 struct archive_write_disk *a = (struct archive_write_disk *)_a;
288 struct fixup_entry *fe;
291 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
292 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
293 "archive_write_disk_header");
294 archive_clear_error(&a->archive);
295 if (a->archive.state & ARCHIVE_STATE_DATA) {
296 r = _archive_write_finish_entry(&a->archive);
301 /* Set up for this particular entry. */
303 a->current_fixup = NULL;
306 archive_entry_free(a->entry);
309 a->entry = archive_entry_clone(entry);
312 a->uid = a->user_uid;
313 a->mode = archive_entry_mode(a->entry);
314 a->filesize = archive_entry_size(a->entry);
315 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
316 a->name = a->_name_data.s;
317 archive_clear_error(&a->archive);
320 * Clean up the requested path. This is necessary for correct
321 * dir restores; the dir restore logic otherwise gets messed
322 * up by nonsense like "dir/.".
324 ret = cleanup_pathname(a);
325 if (ret != ARCHIVE_OK)
329 * Set the umask to zero so we get predictable mode settings.
330 * This gets done on every call to _write_header in case the
331 * user edits their umask during the extraction for some
332 * reason. This will be reset before we return. Note that we
333 * don't need to do this in _finish_entry, as the chmod(), etc,
334 * system calls don't obey umask.
336 a->user_umask = umask(0);
337 /* From here on, early exit requires "goto done" to clean up. */
339 /* Figure out what we need to do for this entry. */
340 a->todo = TODO_MODE_BASE;
341 if (a->flags & ARCHIVE_EXTRACT_PERM) {
342 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
344 * SGID requires an extra "check" step because we
345 * cannot easily predict the GID that the system will
346 * assign. (Different systems assign GIDs to files
347 * based on a variety of criteria, including process
348 * credentials and the gid of the enclosing
349 * directory.) We can only restore the SGID bit if
350 * the file has the right GID, and we only know the
351 * GID if we either set it (see set_ownership) or if
352 * we've actually called stat() on the file after it
353 * was restored. Since there are several places at
354 * which we might verify the GID, we need a TODO bit
357 if (a->mode & S_ISGID)
358 a->todo |= TODO_SGID | TODO_SGID_CHECK;
360 * Verifying the SUID is simpler, but can still be
361 * done in multiple ways, hence the separate "check" bit.
363 if (a->mode & S_ISUID)
364 a->todo |= TODO_SUID | TODO_SUID_CHECK;
367 * User didn't request full permissions, so don't
368 * restore SUID, SGID bits and obey umask.
373 a->mode &= ~a->user_umask;
375 if (a->flags & ARCHIVE_EXTRACT_OWNER)
376 a->todo |= TODO_OWNER;
377 if (a->flags & ARCHIVE_EXTRACT_TIME)
378 a->todo |= TODO_TIMES;
379 if (a->flags & ARCHIVE_EXTRACT_ACL)
380 a->todo |= TODO_ACLS;
381 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
382 a->todo |= TODO_FFLAGS;
383 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
384 ret = check_symlinks(a);
385 if (ret != ARCHIVE_OK)
389 /* If path exceeds PATH_MAX, shorten the path. */
390 edit_deep_directories(a);
393 ret = restore_entry(a);
396 /* If we changed directory above, restore it here. */
397 if (a->restore_pwd >= 0) {
398 fchdir(a->restore_pwd);
399 close(a->restore_pwd);
405 * Fixup uses the unedited pathname from archive_entry_pathname(),
406 * because it is relative to the base dir and the edited path
407 * might be relative to some intermediate dir as a result of the
408 * deep restore logic.
410 if (a->deferred & TODO_MODE) {
411 fe = current_fixup(a, archive_entry_pathname(entry));
412 fe->fixup |= TODO_MODE_BASE;
416 if (a->deferred & TODO_TIMES) {
417 fe = current_fixup(a, archive_entry_pathname(entry));
418 fe->fixup |= TODO_TIMES;
419 fe->mtime = archive_entry_mtime(entry);
420 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
421 fe->atime = archive_entry_atime(entry);
422 fe->atime_nanos = archive_entry_atime_nsec(entry);
425 if (a->deferred & TODO_FFLAGS) {
426 fe = current_fixup(a, archive_entry_pathname(entry));
427 fe->fixup |= TODO_FFLAGS;
428 /* TODO: Complete this.. defer fflags from below. */
431 /* We've created the object and are ready to pour data into it. */
432 if (ret == ARCHIVE_OK)
433 a->archive.state = ARCHIVE_STATE_DATA;
435 * If it's not open, tell our client not to try writing.
436 * In particular, dirs, links, etc, don't get written to.
439 archive_entry_set_size(entry, 0);
443 /* Restore the user's umask before returning. */
444 umask(a->user_umask);
450 archive_write_disk_set_skip_file(struct archive *_a, dev_t d, ino_t i)
452 struct archive_write_disk *a = (struct archive_write_disk *)_a;
453 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
454 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
455 a->skip_file_dev = d;
456 a->skip_file_ino = i;
461 _archive_write_data_block(struct archive *_a,
462 const void *buff, size_t size, off_t offset)
464 struct archive_write_disk *a = (struct archive_write_disk *)_a;
465 ssize_t bytes_written = 0;
468 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
469 ARCHIVE_STATE_DATA, "archive_write_disk_block");
471 archive_set_error(&a->archive, 0, "File not open");
472 return (ARCHIVE_WARN);
474 archive_clear_error(&a->archive);
476 /* Seek if necessary to the specified offset. */
477 if (offset != a->offset) {
478 if (lseek(a->fd, offset, SEEK_SET) < 0) {
479 archive_set_error(&a->archive, errno, "Seek failed");
480 return (ARCHIVE_WARN);
485 /* Write the data. */
486 while (size > 0 && a->offset < a->filesize) {
487 if ((off_t)(a->offset + size) > a->filesize) {
488 size = (size_t)(a->filesize - a->offset);
489 archive_set_error(&a->archive, errno,
490 "Write request too large");
493 bytes_written = write(a->fd, buff, size);
494 if (bytes_written < 0) {
495 archive_set_error(&a->archive, errno, "Write failed");
496 return (ARCHIVE_WARN);
498 size -= bytes_written;
499 a->offset += bytes_written;
505 _archive_write_data(struct archive *_a, const void *buff, size_t size)
507 struct archive_write_disk *a = (struct archive_write_disk *)_a;
511 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
512 ARCHIVE_STATE_DATA, "archive_write_data");
517 r = _archive_write_data_block(_a, buff, size, a->offset);
520 return (a->offset - offset);
524 _archive_write_finish_entry(struct archive *_a)
526 struct archive_write_disk *a = (struct archive_write_disk *)_a;
527 int ret = ARCHIVE_OK;
529 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
530 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
531 "archive_write_finish_entry");
532 if (a->archive.state & ARCHIVE_STATE_HEADER)
534 archive_clear_error(&a->archive);
536 /* Restore metadata. */
539 * Look up the "real" UID only if we're going to need it. We
540 * need this for TODO_SGID because chown() requires both.
542 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
543 a->uid = a->lookup_uid(a->lookup_uid_data,
544 archive_entry_uname(a->entry),
545 archive_entry_uid(a->entry));
547 /* Look up the "real" GID only if we're going to need it. */
548 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
549 a->gid = a->lookup_gid(a->lookup_gid_data,
550 archive_entry_gname(a->entry),
551 archive_entry_gid(a->entry));
554 * If restoring ownership, do it before trying to restore suid/sgid
555 * bits. If we set the owner, we know what it is and can skip
556 * a stat() call to examine the ownership of the file on disk.
558 if (a->todo & TODO_OWNER)
559 ret = set_ownership(a);
560 if (a->todo & TODO_MODE) {
561 int r2 = set_mode(a, a->mode);
562 if (r2 < ret) ret = r2;
564 if (a->todo & TODO_TIMES) {
565 int r2 = set_time(a);
566 if (r2 < ret) ret = r2;
568 if (a->todo & TODO_ACLS) {
569 int r2 = set_acls(a);
570 if (r2 < ret) ret = r2;
572 if (a->todo & TODO_XATTR) {
573 int r2 = set_xattrs(a);
574 if (r2 < ret) ret = r2;
576 if (a->todo & TODO_FFLAGS) {
577 int r2 = set_fflags(a);
578 if (r2 < ret) ret = r2;
581 /* If there's an fd, we can close it now. */
586 /* If there's an entry, we can release it now. */
588 archive_entry_free(a->entry);
591 a->archive.state = ARCHIVE_STATE_HEADER;
596 archive_write_disk_set_group_lookup(struct archive *_a,
598 gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid),
599 void (*cleanup_gid)(void *private))
601 struct archive_write_disk *a = (struct archive_write_disk *)_a;
602 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
603 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
605 a->lookup_gid = lookup_gid;
606 a->cleanup_gid = cleanup_gid;
607 a->lookup_gid_data = private_data;
612 archive_write_disk_set_user_lookup(struct archive *_a,
614 uid_t (*lookup_uid)(void *private, const char *uname, uid_t uid),
615 void (*cleanup_uid)(void *private))
617 struct archive_write_disk *a = (struct archive_write_disk *)_a;
618 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
619 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
621 a->lookup_uid = lookup_uid;
622 a->cleanup_uid = cleanup_uid;
623 a->lookup_uid_data = private_data;
629 * Create a new archive_write_disk object and initialize it with global state.
632 archive_write_disk_new(void)
634 struct archive_write_disk *a;
636 a = (struct archive_write_disk *)malloc(sizeof(*a));
639 memset(a, 0, sizeof(*a));
640 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
641 /* We're ready to write a header immediately. */
642 a->archive.state = ARCHIVE_STATE_HEADER;
643 a->archive.vtable = archive_write_disk_vtable();
644 a->lookup_uid = trivial_lookup_uid;
645 a->lookup_gid = trivial_lookup_gid;
647 a->user_uid = geteuid();
648 #endif /* HAVE_GETEUID */
649 if (archive_string_ensure(&a->path_safe, 512) == NULL) {
653 return (&a->archive);
658 * If pathname is longer than PATH_MAX, chdir to a suitable
659 * intermediate dir and edit the path down to a shorter suffix. Note
660 * that this routine never returns an error; if the chdir() attempt
661 * fails for any reason, we just go ahead with the long pathname. The
662 * object creation is likely to fail, but any error will get handled
667 edit_deep_directories(struct archive_write_disk *a)
670 char *tail = a->name;
674 /* If path is short, avoid the open() below. */
675 if (strlen(tail) <= PATH_MAX)
678 /* Try to record our starting dir. */
679 a->restore_pwd = open(".", O_RDONLY | O_BINARY);
680 if (a->restore_pwd < 0)
683 /* As long as the path is too long... */
684 while (strlen(tail) > PATH_MAX) {
685 /* Locate a dir prefix shorter than PATH_MAX. */
686 tail += PATH_MAX - 8;
687 while (tail > a->name && *tail != '/')
689 /* Exit if we find a too-long path component. */
692 /* Create the intermediate dir and chdir to it. */
693 *tail = '\0'; /* Terminate dir portion */
694 ret = create_dir(a, a->name);
695 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
697 *tail = '/'; /* Restore the / we removed. */
698 if (ret != ARCHIVE_OK)
701 /* The chdir() succeeded; we've now shortened the path. */
709 * The main restore function.
712 restore_entry(struct archive_write_disk *a)
714 int ret = ARCHIVE_OK, en;
716 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
718 * TODO: Fix this. Apparently, there are platforms
719 * that still allow root to hose the entire filesystem
720 * by unlinking a dir. The S_ISDIR() test above
721 * prevents us from using unlink() here if the new
722 * object is a dir, but that doesn't mean the old
723 * object isn't a dir.
725 if (unlink(a->name) == 0) {
726 /* We removed it, we're done. */
727 } else if (errno == ENOENT) {
728 /* File didn't exist, that's just as good. */
729 } else if (rmdir(a->name) == 0) {
730 /* It was a dir, but now it's gone. */
732 /* We tried, but couldn't get rid of it. */
733 archive_set_error(&a->archive, errno,
735 return(ARCHIVE_WARN);
739 /* Try creating it first; if this fails, we'll try to recover. */
740 en = create_filesystem_object(a);
742 if ((en == ENOTDIR || en == ENOENT)
743 && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
744 /* If the parent dir doesn't exist, try creating it. */
745 create_parent_dir(a, a->name);
746 /* Now try to create the object again. */
747 en = create_filesystem_object(a);
750 if ((en == EISDIR || en == EEXIST)
751 && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
752 /* If we're not overwriting, we're done. */
753 archive_set_error(&a->archive, en, "Already exists");
754 return (ARCHIVE_WARN);
758 * Some platforms return EISDIR if you call
759 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
760 * return EEXIST. POSIX is ambiguous, requiring EISDIR
761 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
762 * on an existing item.
765 /* A dir is in the way of a non-dir, rmdir it. */
766 if (rmdir(a->name) != 0) {
767 archive_set_error(&a->archive, errno,
768 "Can't remove already-existing dir");
769 return (ARCHIVE_WARN);
772 en = create_filesystem_object(a);
773 } else if (en == EEXIST) {
775 * We know something is in the way, but we don't know what;
776 * we need to find out before we go any further.
778 if (lstat(a->name, &a->st) != 0) {
779 archive_set_error(&a->archive, errno,
780 "Can't stat existing object");
781 return (ARCHIVE_WARN);
784 /* TODO: if it's a symlink... */
786 if (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER) {
787 if (!older(&(a->st), a->entry)) {
788 archive_set_error(&a->archive, 0,
789 "File on disk is not older; skipping.");
790 return (ARCHIVE_FAILED);
794 /* If it's our archive, we're done. */
795 if (a->skip_file_dev > 0 &&
796 a->skip_file_ino > 0 &&
797 a->st.st_dev == a->skip_file_dev &&
798 a->st.st_ino == a->skip_file_ino) {
799 archive_set_error(&a->archive, 0, "Refusing to overwrite archive");
800 return (ARCHIVE_FAILED);
803 if (!S_ISDIR(a->st.st_mode)) {
804 /* A non-dir is in the way, unlink it. */
805 if (unlink(a->name) != 0) {
806 archive_set_error(&a->archive, errno,
807 "Can't unlink already-existing object");
808 return (ARCHIVE_WARN);
811 en = create_filesystem_object(a);
812 } else if (!S_ISDIR(a->mode)) {
813 /* A dir is in the way of a non-dir, rmdir it. */
814 if (rmdir(a->name) != 0) {
815 archive_set_error(&a->archive, errno,
816 "Can't remove already-existing dir");
817 return (ARCHIVE_WARN);
820 en = create_filesystem_object(a);
823 * There's a dir in the way of a dir. Don't
824 * waste time with rmdir()/mkdir(), just fix
825 * up the permissions on the existing dir.
826 * Note that we don't change perms on existing
827 * dirs unless _EXTRACT_PERM is specified.
829 if ((a->mode != a->st.st_mode)
830 && (a->todo & TODO_MODE_FORCE))
831 a->deferred |= (a->todo & TODO_MODE);
832 /* Ownership doesn't need deferred fixup. */
833 en = 0; /* Forget the EEXIST. */
838 /* Everything failed; give up here. */
839 archive_set_error(&a->archive, en, "Can't create '%s'", a->name);
840 return (ARCHIVE_WARN);
843 a->pst = NULL; /* Cached stat data no longer valid. */
848 * Returns 0 if creation succeeds, or else returns errno value from
849 * the failed system call. Note: This function should only ever perform
850 * a single system call.
853 create_filesystem_object(struct archive_write_disk *a)
855 /* Create the entry. */
856 const char *linkname;
857 mode_t final_mode, mode;
860 /* We identify hard/symlinks according to the link names. */
861 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
862 linkname = archive_entry_hardlink(a->entry);
863 if (linkname != NULL) {
864 r = link(linkname, a->name) ? errno : 0;
866 * New cpio and pax formats allow hardlink entries
867 * to carry data, so we may have to open the file
868 * for hardlink entries.
870 if (r == 0 && a->filesize > 0) {
871 a->fd = open(a->name, O_WRONLY | O_TRUNC | O_BINARY);
877 linkname = archive_entry_symlink(a->entry);
878 if (linkname != NULL)
879 return symlink(linkname, a->name) ? errno : 0;
882 * The remaining system calls all set permissions, so let's
883 * try to take advantage of that to avoid an extra chmod()
884 * call. (Recall that umask is set to zero right now!)
887 /* Mode we want for the final restored object (w/o file type bits). */
888 final_mode = a->mode & 07777;
890 * The mode that will actually be restored in this step. Note
891 * that SUID, SGID, etc, require additional work to ensure
892 * security, so we never restore them at this point.
894 mode = final_mode & 0777;
896 switch (a->mode & AE_IFMT) {
898 /* POSIX requires that we fall through here. */
901 a->fd = open(a->name,
902 O_WRONLY | O_CREAT | O_EXCL | O_BINARY, mode);
907 /* Note: we use AE_IFCHR for the case label, and
908 * S_IFCHR for the mknod() call. This is correct. */
909 r = mknod(a->name, mode | S_IFCHR,
910 archive_entry_rdev(a->entry));
912 /* TODO: Find a better way to warn about our inability
913 * to restore a char device node. */
915 #endif /* HAVE_MKNOD */
919 r = mknod(a->name, mode | S_IFBLK,
920 archive_entry_rdev(a->entry));
922 /* TODO: Find a better way to warn about our inability
923 * to restore a block device node. */
925 #endif /* HAVE_MKNOD */
928 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
929 r = mkdir(a->name, mode);
931 /* Defer setting dir times. */
932 a->deferred |= (a->todo & TODO_TIMES);
933 a->todo &= ~TODO_TIMES;
934 /* Never use an immediate chmod(). */
935 if (mode != final_mode)
936 a->deferred |= (a->todo & TODO_MODE);
937 a->todo &= ~TODO_MODE;
942 r = mkfifo(a->name, mode);
944 /* TODO: Find a better way to warn about our inability
945 * to restore a fifo. */
947 #endif /* HAVE_MKFIFO */
951 /* All the system calls above set errno on failure. */
955 /* If we managed to set the final mode, we've avoided a chmod(). */
956 if (mode == final_mode)
957 a->todo &= ~TODO_MODE;
962 * Cleanup function for archive_extract. Mostly, this involves processing
963 * the fixup list, which is used to address a number of problems:
964 * * Dir permissions might prevent us from restoring a file in that
965 * dir, so we restore the dir with minimum 0700 permissions first,
966 * then correct the mode at the end.
967 * * Similarly, the act of restoring a file touches the directory
968 * and changes the timestamp on the dir, so we have to touch-up dir
969 * timestamps at the end as well.
970 * * Some file flags can interfere with the restore by, for example,
971 * preventing the creation of hardlinks to those files.
973 * Note that tar/cpio do not require that archives be in a particular
974 * order; there is no way to know when the last file has been restored
975 * within a directory, so there's no way to optimize the memory usage
976 * here by fixing up the directory any earlier than the
979 * XXX TODO: Directory ACLs should be restored here, for the same
980 * reason we set directory perms here. XXX
983 _archive_write_close(struct archive *_a)
985 struct archive_write_disk *a = (struct archive_write_disk *)_a;
986 struct fixup_entry *next, *p;
989 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
990 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
991 "archive_write_disk_close");
992 ret = _archive_write_finish_entry(&a->archive);
994 /* Sort dir list so directories are fixed up in depth-first order. */
995 p = sort_dir_list(a->fixup_list);
998 a->pst = NULL; /* Mark stat cache as out-of-date. */
999 if (p->fixup & TODO_TIMES) {
1001 /* {f,l,}utimes() are preferred, when available. */
1002 struct timeval times[2];
1003 times[1].tv_sec = p->mtime;
1004 times[1].tv_usec = p->mtime_nanos / 1000;
1005 times[0].tv_sec = p->atime;
1006 times[0].tv_usec = p->atime_nanos / 1000;
1008 lutimes(p->name, times);
1010 utimes(p->name, times);
1013 /* utime() is more portable, but less precise. */
1014 struct utimbuf times;
1015 times.modtime = p->mtime;
1016 times.actime = p->atime;
1018 utime(p->name, ×);
1021 if (p->fixup & TODO_MODE_BASE)
1022 chmod(p->name, p->mode);
1024 if (p->fixup & TODO_FFLAGS)
1025 set_fflags_platform(a, -1, p->name,
1026 p->mode, p->fflags_set, 0);
1033 a->fixup_list = NULL;
1038 _archive_write_finish(struct archive *_a)
1040 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1042 ret = _archive_write_close(&a->archive);
1043 if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1044 (a->cleanup_gid)(a->lookup_gid_data);
1045 if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1046 (a->cleanup_uid)(a->lookup_uid_data);
1047 archive_string_free(&a->_name_data);
1048 archive_string_free(&a->archive.error_string);
1049 archive_string_free(&a->path_safe);
1055 * Simple O(n log n) merge sort to order the fixup list. In
1056 * particular, we want to restore dir timestamps depth-first.
1058 static struct fixup_entry *
1059 sort_dir_list(struct fixup_entry *p)
1061 struct fixup_entry *a, *b, *t;
1065 /* A one-item list is already sorted. */
1066 if (p->next == NULL)
1069 /* Step 1: split the list. */
1073 /* Step a twice, t once. */
1079 /* Now, t is at the mid-point, so break the list here. */
1084 /* Step 2: Recursively sort the two sub-lists. */
1085 a = sort_dir_list(a);
1086 b = sort_dir_list(b);
1088 /* Step 3: Merge the returned lists. */
1089 /* Pick the first element for the merged list. */
1090 if (strcmp(a->name, b->name) > 0) {
1098 /* Always put the later element on the list first. */
1099 while (a != NULL && b != NULL) {
1100 if (strcmp(a->name, b->name) > 0) {
1110 /* Only one list is non-empty, so just splice it on. */
1120 * Returns a new, initialized fixup entry.
1122 * TODO: Reduce the memory requirements for this list by using a tree
1123 * structure rather than a simple list of names.
1125 static struct fixup_entry *
1126 new_fixup(struct archive_write_disk *a, const char *pathname)
1128 struct fixup_entry *fe;
1130 fe = (struct fixup_entry *)malloc(sizeof(struct fixup_entry));
1133 fe->next = a->fixup_list;
1136 fe->name = strdup(pathname);
1141 * Returns a fixup structure for the current entry.
1143 static struct fixup_entry *
1144 current_fixup(struct archive_write_disk *a, const char *pathname)
1146 if (a->current_fixup == NULL)
1147 a->current_fixup = new_fixup(a, pathname);
1148 return (a->current_fixup);
1151 /* TODO: Make this work. */
1153 * TODO: The deep-directory support bypasses this; disable deep directory
1154 * support if we're doing symlink checks.
1157 * TODO: Someday, integrate this with the deep dir support; they both
1158 * scan the path and both can be optimized by comparing against other
1162 check_symlinks(struct archive_write_disk *a)
1170 * Guard against symlink tricks. Reject any archive entry whose
1171 * destination would be altered by a symlink.
1173 /* Whatever we checked last time doesn't need to be re-checked. */
1176 while ((*pn != '\0') && (*p == *pn))
1179 /* Keep going until we've checked the entire name. */
1180 while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
1181 /* Skip the next path element. */
1182 while (*pn != '\0' && *pn != '/')
1186 /* Check that we haven't hit a symlink. */
1187 r = lstat(a->name, &st);
1189 /* We've hit a dir that doesn't exist; stop now. */
1190 if (errno == ENOENT)
1192 } else if (S_ISLNK(st.st_mode)) {
1195 * Last element is symlink; remove it
1196 * so we can overwrite it with the
1197 * item being extracted.
1199 if (unlink(a->name)) {
1200 archive_set_error(&a->archive, errno,
1201 "Could not remove symlink %s",
1204 return (ARCHIVE_WARN);
1207 * Even if we did remove it, a warning
1208 * is in order. The warning is silly,
1209 * though, if we're just replacing one
1210 * symlink with another symlink.
1212 if (!S_ISLNK(a->mode)) {
1213 archive_set_error(&a->archive, 0,
1214 "Removing symlink %s",
1217 /* Symlink gone. No more problem! */
1220 } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
1221 /* User asked us to remove problems. */
1222 if (unlink(a->name) != 0) {
1223 archive_set_error(&a->archive, 0,
1224 "Cannot remove intervening symlink %s",
1227 return (ARCHIVE_WARN);
1230 archive_set_error(&a->archive, 0,
1231 "Cannot extract through symlink %s",
1234 return (ARCHIVE_WARN);
1239 /* We've checked and/or cleaned the whole path, so remember it. */
1240 archive_strcpy(&a->path_safe, a->name);
1241 return (ARCHIVE_OK);
1245 * Canonicalize the pathname. In particular, this strips duplicate
1246 * '/' characters, '.' elements, and trailing '/'. It also raises an
1247 * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
1248 * set) any '..' in the path.
1251 cleanup_pathname(struct archive_write_disk *a)
1254 char separator = '\0';
1255 int lastdotdot = 0; /* True if last elt copied was '..' */
1257 dest = src = a->name;
1259 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1260 "Invalid empty pathname");
1261 return (ARCHIVE_WARN);
1264 /* Skip leading '/'. */
1268 /* Scan the pathname one element at a time. */
1270 /* src points to first char after '/' */
1271 if (src[0] == '\0') {
1273 } else if (src[0] == '/') {
1274 /* Found '//', ignore second one. */
1277 } else if (src[0] == '.') {
1278 if (src[1] == '\0') {
1279 /* Ignore trailing '.' */
1281 } else if (src[1] == '/') {
1285 } else if (src[1] == '.') {
1286 if (src[2] == '/' || src[2] == '\0') {
1287 /* Conditionally warn about '..' */
1288 if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
1289 archive_set_error(&a->archive,
1291 "Path contains '..'");
1292 return (ARCHIVE_WARN);
1298 * Note: Under no circumstances do we
1299 * remove '..' elements. In
1300 * particular, restoring
1301 * '/foo/../bar/' should create the
1302 * 'foo' dir as a side-effect.
1309 /* Copy current element, including leading '/'. */
1312 while (*src != '\0' && *src != '/') {
1319 /* Skip '/' separator. */
1323 * We've just copied zero or more path elements, not including the
1327 /* Trailing '..' is always wrong. */
1328 archive_set_error(&a->archive,
1330 "Path contains trailing '..'");
1331 return (ARCHIVE_WARN);
1333 if (dest == a->name) {
1335 * Nothing got copied. The path must have been something
1336 * like '.' or '/' or './' or '/././././/./'.
1343 /* Terminate the result. */
1345 return (ARCHIVE_OK);
1349 * Create the parent directory of the specified path, assuming path
1350 * is already in mutable storage.
1353 create_parent_dir(struct archive_write_disk *a, char *path)
1358 /* Remove tail element to obtain parent name. */
1359 slash = strrchr(path, '/');
1361 return (ARCHIVE_OK);
1363 r = create_dir(a, path);
1369 * Create the specified dir, recursing to create parents as necessary.
1371 * Returns ARCHIVE_OK if the path exists when we're done here.
1372 * Otherwise, returns ARCHIVE_WARN.
1373 * Assumes path is in mutable storage; path is unchanged on exit.
1376 create_dir(struct archive_write_disk *a, char *path)
1379 struct fixup_entry *le;
1381 mode_t mode_final, mode;
1386 /* Check for special names and just skip them. */
1387 slash = strrchr(path, '/');
1393 if (base[0] == '\0' ||
1394 (base[0] == '.' && base[1] == '\0') ||
1395 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
1396 /* Don't bother trying to create null path, '.', or '..'. */
1397 if (slash != NULL) {
1399 r = create_dir(a, path);
1403 return (ARCHIVE_OK);
1407 * Yes, this should be stat() and not lstat(). Using lstat()
1408 * here loses the ability to extract through symlinks. Also note
1409 * that this should not use the a->st cache.
1411 if (stat(path, &st) == 0) {
1412 if (S_ISDIR(st.st_mode))
1413 return (ARCHIVE_OK);
1414 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1415 archive_set_error(&a->archive, EEXIST,
1416 "Can't create directory '%s'", path);
1417 return (ARCHIVE_WARN);
1419 if (unlink(path) != 0) {
1420 archive_set_error(&a->archive, errno,
1421 "Can't create directory '%s': "
1422 "Conflicting file cannot be removed");
1423 return (ARCHIVE_WARN);
1425 } else if (errno != ENOENT && errno != ENOTDIR) {
1427 archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
1428 return (ARCHIVE_WARN);
1429 } else if (slash != NULL) {
1431 r = create_dir(a, path);
1433 if (r != ARCHIVE_OK)
1438 * Mode we want for the final restored directory. Per POSIX,
1439 * implicitly-created dirs must be created obeying the umask.
1440 * There's no mention whether this is different for privileged
1441 * restores (which the rest of this code handles by pretending
1442 * umask=0). I've chosen here to always obey the user's umask for
1443 * implicit dirs, even if _EXTRACT_PERM was specified.
1445 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
1446 /* Mode we want on disk during the restore process. */
1448 mode |= MINIMUM_DIR_MODE;
1449 mode &= MAXIMUM_DIR_MODE;
1450 if (mkdir(path, mode) == 0) {
1451 if (mode != mode_final) {
1452 le = new_fixup(a, path);
1453 le->fixup |=TODO_MODE_BASE;
1454 le->mode = mode_final;
1456 return (ARCHIVE_OK);
1460 * Without the following check, a/b/../b/c/d fails at the
1461 * second visit to 'b', so 'd' can't be created. Note that we
1462 * don't add it to the fixup list here, as it's already been
1465 if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1466 return (ARCHIVE_OK);
1468 archive_set_error(&a->archive, errno, "Failed to create dir '%s'", path);
1469 return (ARCHIVE_WARN);
1473 * Note: Although we can skip setting the user id if the desired user
1474 * id matches the current user, we cannot skip setting the group, as
1475 * many systems set the gid bit based on the containing directory. So
1476 * we have to perform a chown syscall if we want to restore the SGID
1477 * bit. (The alternative is to stat() and then possibly chown(); it's
1478 * more efficient to skip the stat() and just always chown().) Note
1479 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
1480 * allows set_mode to skip the stat() check for the GID.
1483 set_ownership(struct archive_write_disk *a)
1485 /* If we know we can't change it, don't bother trying. */
1486 if (a->user_uid != 0 && a->user_uid != a->uid) {
1487 archive_set_error(&a->archive, errno,
1488 "Can't set UID=%d", a->uid);
1489 return (ARCHIVE_WARN);
1493 /* If we have an fd, we can avoid a race. */
1494 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
1495 /* We've set owner and know uid/gid are correct. */
1496 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1497 return (ARCHIVE_OK);
1501 /* We prefer lchown() but will use chown() if that's all we have. */
1502 /* Of course, if we have neither, this will always fail. */
1504 if (lchown(a->name, a->uid, a->gid) == 0) {
1505 /* We've set owner and know uid/gid are correct. */
1506 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1507 return (ARCHIVE_OK);
1510 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
1511 /* We've set owner and know uid/gid are correct. */
1512 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1513 return (ARCHIVE_OK);
1517 archive_set_error(&a->archive, errno,
1518 "Can't set user=%d/group=%d for %s", a->uid, a->gid,
1520 return (ARCHIVE_WARN);
1525 * The utimes()-family functions provide high resolution and
1526 * a way to set time on an fd or a symlink. We prefer them
1527 * when they're available.
1530 set_time(struct archive_write_disk *a)
1532 struct timeval times[2];
1534 times[1].tv_sec = archive_entry_mtime(a->entry);
1535 times[1].tv_usec = archive_entry_mtime_nsec(a->entry) / 1000;
1537 times[0].tv_sec = archive_entry_atime(a->entry);
1538 times[0].tv_usec = archive_entry_atime_nsec(a->entry) / 1000;
1541 if (a->fd >= 0 && futimes(a->fd, times) == 0) {
1542 return (ARCHIVE_OK);
1547 if (lutimes(a->name, times) != 0)
1549 if (!S_ISLNK(a->mode) && utimes(a->name, times) != 0)
1552 archive_set_error(&a->archive, errno, "Can't update time for %s",
1554 return (ARCHIVE_WARN);
1558 * Note: POSIX does not provide a portable way to restore ctime.
1559 * (Apart from resetting the system clock, which is distasteful.)
1560 * So, any restoration of ctime will necessarily be OS-specific.
1563 /* XXX TODO: Can FreeBSD restore ctime? XXX */
1564 return (ARCHIVE_OK);
1566 #elif defined(HAVE_UTIME)
1568 * utime() is an older, more standard interface that we'll use
1569 * if utimes() isn't available.
1572 set_time(struct archive_write_disk *a)
1574 struct utimbuf times;
1576 times.modtime = archive_entry_mtime(a->entry);
1577 times.actime = archive_entry_atime(a->entry);
1578 if (!S_ISLNK(a->mode) && utime(a->name, ×) != 0) {
1579 archive_set_error(&a->archive, errno,
1580 "Can't update time for %s", a->name);
1581 return (ARCHIVE_WARN);
1583 return (ARCHIVE_OK);
1586 /* This platform doesn't give us a way to restore the time. */
1588 set_time(struct archive_write_disk *a)
1590 (void)a; /* UNUSED */
1591 archive_set_error(&a->archive, errno,
1592 "Can't update time for %s", a->name);
1593 return (ARCHIVE_WARN);
1599 set_mode(struct archive_write_disk *a, int mode)
1602 mode &= 07777; /* Strip off file type bits. */
1604 if (a->todo & TODO_SGID_CHECK) {
1606 * If we don't know the GID is right, we must stat()
1607 * to verify it. We can't just check the GID of this
1608 * process, since systems sometimes set GID from
1609 * the enclosing dir or based on ACLs.
1611 if (a->pst != NULL) {
1612 /* Already have stat() data available. */
1614 } else if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
1617 } else if (stat(a->name, &a->st) == 0) {
1620 archive_set_error(&a->archive, errno,
1621 "Couldn't stat file");
1622 return (ARCHIVE_WARN);
1624 if (a->pst->st_gid != a->gid) {
1626 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1628 * This is only an error if you
1629 * requested owner restore. If you
1630 * didn't, we'll try to restore
1631 * sgid/suid, but won't consider it a
1632 * problem if we can't.
1634 archive_set_error(&a->archive, -1,
1635 "Can't restore SGID bit");
1639 /* While we're here, double-check the UID. */
1640 if (a->pst->st_uid != a->uid
1641 && (a->todo & TODO_SUID)) {
1643 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1644 archive_set_error(&a->archive, -1,
1645 "Can't restore SUID bit");
1649 a->todo &= ~TODO_SGID_CHECK;
1650 a->todo &= ~TODO_SUID_CHECK;
1651 } else if (a->todo & TODO_SUID_CHECK) {
1653 * If we don't know the UID is right, we can just check
1654 * the user, since all systems set the file UID from
1657 if (a->user_uid != a->uid) {
1659 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1660 archive_set_error(&a->archive, -1,
1661 "Can't make file SUID");
1665 a->todo &= ~TODO_SUID_CHECK;
1668 if (S_ISLNK(a->mode)) {
1671 * If this is a symlink, use lchmod(). If the
1672 * platform doesn't support lchmod(), just skip it. A
1673 * platform that doesn't provide a way to set
1674 * permissions on symlinks probably ignores
1675 * permissions on symlinks, so a failure here has no
1678 if (lchmod(a->name, mode) != 0) {
1679 archive_set_error(&a->archive, errno,
1680 "Can't set permissions to 0%o", (int)mode);
1684 } else if (!S_ISDIR(a->mode)) {
1686 * If it's not a symlink and not a dir, then use
1687 * fchmod() or chmod(), depending on whether we have
1688 * an fd. Dirs get their perms set during the
1689 * post-extract fixup, which is handled elsewhere.
1693 if (fchmod(a->fd, mode) != 0) {
1694 archive_set_error(&a->archive, errno,
1695 "Can't set permissions to 0%o", (int)mode);
1700 /* If this platform lacks fchmod(), then
1701 * we'll just use chmod(). */
1702 if (chmod(a->name, mode) != 0) {
1703 archive_set_error(&a->archive, errno,
1704 "Can't set permissions to 0%o", (int)mode);
1712 set_fflags(struct archive_write_disk *a)
1714 struct fixup_entry *le;
1715 unsigned long set, clear;
1718 mode_t mode = archive_entry_mode(a->entry);
1721 * Make 'critical_flags' hold all file flags that can't be
1722 * immediately restored. For example, on BSD systems,
1723 * SF_IMMUTABLE prevents hardlinks from being created, so
1724 * should not be set until after any hardlinks are created. To
1725 * preserve some semblance of portability, this uses #ifdef
1726 * extensively. Ugly, but it works.
1728 * Yes, Virginia, this does create a security race. It's mitigated
1729 * somewhat by the practice of creating dirs 0700 until the extract
1730 * is done, but it would be nice if we could do more than that.
1731 * People restoring critical file systems should be wary of
1732 * other programs that might try to muck with files as they're
1735 /* Hopefully, the compiler will optimize this mess into a constant. */
1738 critical_flags |= SF_IMMUTABLE;
1741 critical_flags |= UF_IMMUTABLE;
1744 critical_flags |= SF_APPEND;
1747 critical_flags |= UF_APPEND;
1749 #ifdef EXT2_APPEND_FL
1750 critical_flags |= EXT2_APPEND_FL;
1752 #ifdef EXT2_IMMUTABLE_FL
1753 critical_flags |= EXT2_IMMUTABLE_FL;
1756 if (a->todo & TODO_FFLAGS) {
1757 archive_entry_fflags(a->entry, &set, &clear);
1760 * The first test encourages the compiler to eliminate
1761 * all of this if it's not necessary.
1763 if ((critical_flags != 0) && (set & critical_flags)) {
1764 le = current_fixup(a, a->name);
1765 le->fixup |= TODO_FFLAGS;
1766 le->fflags_set = set;
1767 /* Store the mode if it's not already there. */
1768 if ((le->fixup & TODO_MODE) == 0)
1771 r = set_fflags_platform(a, a->fd,
1772 a->name, mode, set, clear);
1773 if (r != ARCHIVE_OK)
1777 return (ARCHIVE_OK);
1781 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && !defined(__linux)
1783 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1784 mode_t mode, unsigned long set, unsigned long clear)
1786 (void)mode; /* UNUSED */
1787 if (set == 0 && clear == 0)
1788 return (ARCHIVE_OK);
1791 * XXX Is the stat here really necessary? Or can I just use
1792 * the 'set' flags directly? In particular, I'm not sure
1793 * about the correct approach if we're overwriting an existing
1794 * file that already has flags on it. XXX
1796 if (fd >= 0 && fstat(fd, &a->st) == 0)
1798 else if (lstat(name, &a->st) == 0)
1801 archive_set_error(&a->archive, errno,
1802 "Couldn't stat file");
1803 return (ARCHIVE_WARN);
1806 a->st.st_flags &= ~clear;
1807 a->st.st_flags |= set;
1808 #ifdef HAVE_FCHFLAGS
1809 /* If platform has fchflags() and we were given an fd, use it. */
1810 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
1811 return (ARCHIVE_OK);
1814 * If we can't use the fd to set the flags, we'll use the
1815 * pathname to set flags. We prefer lchflags() but will use
1816 * chflags() if we must.
1818 #ifdef HAVE_LCHFLAGS
1819 if (lchflags(name, a->st.st_flags) == 0)
1820 return (ARCHIVE_OK);
1821 #elif defined(HAVE_CHFLAGS)
1822 if (S_ISLNK(a->st.st_mode)) {
1823 archive_set_error(&a->archive, errno,
1824 "Can't set file flags on symlink.");
1825 return (ARCHIVE_WARN);
1827 if (chflags(name, a->st.st_flags) == 0)
1828 return (ARCHIVE_OK);
1830 archive_set_error(&a->archive, errno,
1831 "Failed to set file flags");
1832 return (ARCHIVE_WARN);
1835 #elif defined(__linux) && defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS)
1838 * Linux has flags too, but uses ioctl() to access them instead of
1839 * having a separate chflags() system call.
1842 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1843 mode_t mode, unsigned long set, unsigned long clear)
1847 unsigned long newflags, oldflags;
1848 unsigned long sf_mask = 0;
1850 if (set == 0 && clear == 0)
1851 return (ARCHIVE_OK);
1852 /* Only regular files and dirs can have flags. */
1853 if (!S_ISREG(mode) && !S_ISDIR(mode))
1854 return (ARCHIVE_OK);
1856 /* If we weren't given an fd, open it ourselves. */
1858 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY);
1860 return (ARCHIVE_OK);
1863 * Linux has no define for the flags that are only settable by
1864 * the root user. This code may seem a little complex, but
1865 * there seem to be some Linux systems that lack these
1866 * defines. (?) The code below degrades reasonably gracefully
1867 * if sf_mask is incomplete.
1869 #ifdef EXT2_IMMUTABLE_FL
1870 sf_mask |= EXT2_IMMUTABLE_FL;
1872 #ifdef EXT2_APPEND_FL
1873 sf_mask |= EXT2_APPEND_FL;
1876 * XXX As above, this would be way simpler if we didn't have
1877 * to read the current flags from disk. XXX
1880 /* Try setting the flags as given. */
1881 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1882 newflags = (oldflags & ~clear) | set;
1883 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1888 /* If we couldn't set all the flags, try again with a subset. */
1889 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1890 newflags &= ~sf_mask;
1891 oldflags &= sf_mask;
1892 newflags |= oldflags;
1893 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1896 /* We couldn't set the flags, so report the failure. */
1898 archive_set_error(&a->archive, errno,
1899 "Failed to set file flags");
1907 #else /* Not HAVE_CHFLAGS && Not __linux */
1910 * Of course, some systems have neither BSD chflags() nor Linux' flags
1911 * support through ioctl().
1914 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1915 mode_t mode, unsigned long set, unsigned long clear)
1917 (void)a; /* UNUSED */
1918 (void)fd; /* UNUSED */
1919 (void)name; /* UNUSED */
1920 (void)mode; /* UNUSED */
1921 (void)set; /* UNUSED */
1922 (void)clear; /* UNUSED */
1923 return (ARCHIVE_OK);
1926 #endif /* __linux */
1928 #ifndef HAVE_POSIX_ACL
1929 /* Default empty function body to satisfy mainline code. */
1931 set_acls(struct archive_write_disk *a)
1933 (void)a; /* UNUSED */
1934 return (ARCHIVE_OK);
1940 * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
1943 set_acls(struct archive_write_disk *a)
1947 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_ACCESS,
1948 ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
1949 if (ret != ARCHIVE_OK)
1951 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_DEFAULT,
1952 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
1958 set_acl(struct archive_write_disk *a, int fd, struct archive_entry *entry,
1959 acl_type_t acl_type, int ae_requested_type, const char *tname)
1962 acl_entry_t acl_entry;
1963 acl_permset_t acl_permset;
1965 int ae_type, ae_permset, ae_tag, ae_id;
1968 const char *ae_name;
1973 entries = archive_entry_acl_reset(entry, ae_requested_type);
1975 return (ARCHIVE_OK);
1976 acl = acl_init(entries);
1977 while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
1978 &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
1979 acl_create_entry(&acl, &acl_entry);
1982 case ARCHIVE_ENTRY_ACL_USER:
1983 acl_set_tag_type(acl_entry, ACL_USER);
1984 ae_uid = a->lookup_uid(a->lookup_uid_data,
1986 acl_set_qualifier(acl_entry, &ae_uid);
1988 case ARCHIVE_ENTRY_ACL_GROUP:
1989 acl_set_tag_type(acl_entry, ACL_GROUP);
1990 ae_gid = a->lookup_gid(a->lookup_gid_data,
1992 acl_set_qualifier(acl_entry, &ae_gid);
1994 case ARCHIVE_ENTRY_ACL_USER_OBJ:
1995 acl_set_tag_type(acl_entry, ACL_USER_OBJ);
1997 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
1998 acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
2000 case ARCHIVE_ENTRY_ACL_MASK:
2001 acl_set_tag_type(acl_entry, ACL_MASK);
2003 case ARCHIVE_ENTRY_ACL_OTHER:
2004 acl_set_tag_type(acl_entry, ACL_OTHER);
2011 acl_get_permset(acl_entry, &acl_permset);
2012 acl_clear_perms(acl_permset);
2013 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
2014 acl_add_perm(acl_permset, ACL_EXECUTE);
2015 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
2016 acl_add_perm(acl_permset, ACL_WRITE);
2017 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
2018 acl_add_perm(acl_permset, ACL_READ);
2021 name = archive_entry_pathname(entry);
2023 /* Try restoring the ACL through 'fd' if we can. */
2025 if (fd >= 0 && acl_type == ACL_TYPE_ACCESS && acl_set_fd(fd, acl) == 0)
2029 #if HAVE_ACL_SET_FD_NP
2030 if (fd >= 0 && acl_set_fd_np(fd, acl, acl_type) == 0)
2035 if (acl_set_file(name, acl_type, acl) != 0) {
2036 archive_set_error(&a->archive, errno, "Failed to set %s acl", tname);
2046 * Restore extended attributes - Linux implementation
2049 set_xattrs(struct archive_write_disk *a)
2051 struct archive_entry *entry = a->entry;
2052 static int warning_done = 0;
2053 int ret = ARCHIVE_OK;
2054 int i = archive_entry_xattr_reset(entry);
2060 archive_entry_xattr_next(entry, &name, &value, &size);
2062 strncmp(name, "xfsroot.", 8) != 0 &&
2063 strncmp(name, "system.", 7) != 0) {
2067 e = fsetxattr(a->fd, name, value, size, 0);
2071 e = lsetxattr(archive_entry_pathname(entry),
2072 name, value, size, 0);
2075 if (errno == ENOTSUP) {
2076 if (!warning_done) {
2078 archive_set_error(&a->archive, errno,
2079 "Cannot restore extended "
2080 "attributes on this file "
2084 archive_set_error(&a->archive, errno,
2085 "Failed to set extended attribute");
2089 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2090 "Invalid extended attribute encountered");
2098 * Restore extended attributes - stub implementation for unsupported systems
2101 set_xattrs(struct archive_write_disk *a)
2103 static int warning_done = 0;
2105 /* If there aren't any extended attributes, then it's okay not
2106 * to extract them, otherwise, issue a single warning. */
2107 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
2109 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2110 "Cannot restore extended attributes on this system");
2111 return (ARCHIVE_WARN);
2113 /* Warning was already emitted; suppress further warnings. */
2114 return (ARCHIVE_OK);
2120 * Trivial implementations of gid/uid lookup functions.
2121 * These are normally overridden by the client, but these stub
2122 * versions ensure that we always have something that works.
2125 trivial_lookup_gid(void *private_data, const char *gname, gid_t gid)
2127 (void)private_data; /* UNUSED */
2128 (void)gname; /* UNUSED */
2133 trivial_lookup_uid(void *private_data, const char *uname, uid_t uid)
2135 (void)private_data; /* UNUSED */
2136 (void)uname; /* UNUSED */
2141 * Test if file on disk is older than entry.
2144 older(struct stat *st, struct archive_entry *entry)
2146 /* First, test the seconds and return if we have a definite answer. */
2147 /* Definitely older. */
2148 if (st->st_mtime < archive_entry_mtime(entry))
2150 /* Definitely younger. */
2151 if (st->st_mtime > archive_entry_mtime(entry))
2153 /* If this platform supports fractional seconds, try those. */
2154 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
2155 /* Definitely older. */
2156 if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
2158 /* Definitely younger. */
2159 if (st->st_mtimespec.tv_nsec > archive_entry_mtime_nsec(entry))
2161 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
2162 /* Definitely older. */
2163 if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
2165 /* Definitely older. */
2166 if (st->st_mtim.tv_nsec > archive_entry_mtime_nsec(entry))
2169 /* This system doesn't have high-res timestamps. */
2171 /* Same age, so not older. */