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
49 #ifdef HAVE_EXT2FS_EXT2_FS_H
50 #include <ext2fs/ext2_fs.h> /* for Linux file flags */
61 #ifdef HAVE_LINUX_FS_H
62 #include <linux/fs.h> /* for Linux file flags */
64 #ifdef HAVE_LINUX_EXT2_FS_H
65 #include <linux/ext2_fs.h> /* for Linux file flags */
88 #include "archive_string.h"
89 #include "archive_entry.h"
90 #include "archive_private.h"
93 struct fixup_entry *next;
97 unsigned long mtime_nanos;
98 unsigned long atime_nanos;
99 unsigned long fflags_set;
100 int fixup; /* bitmask of what needs fixing */
105 * We use a bitmask to track which operations remain to be done for
106 * this file. In particular, this helps us avoid unnecessary
107 * operations when it's possible to take care of one step as a
108 * side-effect of another. For example, mkdir() can specify the mode
109 * for the newly-created object but symlink() cannot. This means we
110 * can skip chmod() if mkdir() succeeded, but we must explicitly
111 * chmod() if we're trying to create a directory that already exists
112 * (mkdir() failed) or if we're restoring a symlink. Similarly, we
113 * need to verify UID/GID before trying to restore SUID/SGID bits;
114 * that verification can occur explicitly through a stat() call or
115 * implicitly because of a successful chown() call.
117 #define TODO_MODE_FORCE 0x40000000
118 #define TODO_MODE_BASE 0x20000000
119 #define TODO_SUID 0x10000000
120 #define TODO_SUID_CHECK 0x08000000
121 #define TODO_SGID 0x04000000
122 #define TODO_SGID_CHECK 0x02000000
123 #define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
124 #define TODO_TIMES ARCHIVE_EXTRACT_TIME
125 #define TODO_OWNER ARCHIVE_EXTRACT_OWNER
126 #define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS
127 #define TODO_ACLS ARCHIVE_EXTRACT_ACL
128 #define TODO_XATTR ARCHIVE_EXTRACT_XATTR
130 struct archive_write_disk {
131 struct archive archive;
134 struct fixup_entry *fixup_list;
135 struct fixup_entry *current_fixup;
140 gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid);
141 void (*cleanup_gid)(void *private);
142 void *lookup_gid_data;
143 uid_t (*lookup_uid)(void *private, const char *gname, gid_t gid);
144 void (*cleanup_uid)(void *private);
145 void *lookup_uid_data;
148 * Full path of last file to satisfy symlink checks.
150 struct archive_string path_safe;
153 * Cached stat data from disk for the current entry.
154 * If this is valid, pst points to st. Otherwise,
160 /* Information about the object being restored right now. */
161 struct archive_entry *entry; /* Entry being extracted. */
162 char *name; /* Name of entry, possibly edited. */
163 struct archive_string _name_data; /* backing store for 'name' */
164 /* Tasks remaining for this object. */
166 /* Tasks deferred until end-of-archive. */
168 /* Options requested by the client. */
170 /* Handle for the file we're restoring. */
172 /* Current offset for writing data to the file. */
174 /* Maximum size of file. */
176 /* Dir we were in before this restore; only for deep paths. */
178 /* Mode we should use for this entry; affected by _PERM and umask. */
180 /* UID/GID to use in restoring this entry. */
186 * Default mode for dirs created automatically (will be modified by umask).
187 * Note that POSIX specifies 0777 for implicity-created dirs, "modified
188 * by the process' file creation mask."
190 #define DEFAULT_DIR_MODE 0777
192 * Dir modes are restored in two steps: During the extraction, the permissions
193 * in the archive are modified to match the following limits. During
194 * the post-extract fixup pass, the permissions from the archive are
197 #define MINIMUM_DIR_MODE 0700
198 #define MAXIMUM_DIR_MODE 0775
200 static int check_symlinks(struct archive_write_disk *);
201 static int create_filesystem_object(struct archive_write_disk *);
202 static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname);
204 static void edit_deep_directories(struct archive_write_disk *ad);
206 static int cleanup_pathname(struct archive_write_disk *);
207 static int create_dir(struct archive_write_disk *, char *);
208 static int create_parent_dir(struct archive_write_disk *, char *);
209 static int older(struct stat *, struct archive_entry *);
210 static int restore_entry(struct archive_write_disk *);
211 #ifdef HAVE_POSIX_ACL
212 static int set_acl(struct archive_write_disk *, int fd, struct archive_entry *,
213 acl_type_t, int archive_entry_acl_type, const char *tn);
215 static int set_acls(struct archive_write_disk *);
216 static int set_xattrs(struct archive_write_disk *);
217 static int set_fflags(struct archive_write_disk *);
218 static int set_fflags_platform(struct archive_write_disk *, int fd,
219 const char *name, mode_t mode,
220 unsigned long fflags_set, unsigned long fflags_clear);
221 static int set_ownership(struct archive_write_disk *);
222 static int set_mode(struct archive_write_disk *, int mode);
223 static int set_time(struct archive_write_disk *);
224 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
225 static gid_t trivial_lookup_gid(void *, const char *, gid_t);
226 static uid_t trivial_lookup_uid(void *, const char *, uid_t);
229 static struct archive_vtable *archive_write_disk_vtable(void);
231 static int _archive_write_close(struct archive *);
232 static int _archive_write_finish(struct archive *);
233 static int _archive_write_header(struct archive *, struct archive_entry *);
234 static int _archive_write_finish_entry(struct archive *);
235 static ssize_t _archive_write_data(struct archive *, const void *, size_t);
236 static ssize_t _archive_write_data_block(struct archive *, const void *, size_t, off_t);
238 static struct archive_vtable *
239 archive_write_disk_vtable(void)
241 static struct archive_vtable av;
242 static int inited = 0;
245 av.archive_write_close = _archive_write_close;
246 av.archive_write_finish = _archive_write_finish;
247 av.archive_write_header = _archive_write_header;
248 av.archive_write_finish_entry = _archive_write_finish_entry;
249 av.archive_write_data = _archive_write_data;
250 av.archive_write_data_block = _archive_write_data_block;
257 archive_write_disk_set_options(struct archive *_a, int flags)
259 struct archive_write_disk *a = (struct archive_write_disk *)_a;
267 * Extract this entry to disk.
269 * TODO: Validate hardlinks. According to the standards, we're
270 * supposed to check each extracted hardlink and squawk if it refers
271 * to a file that we didn't restore. I'm not entirely convinced this
272 * is a good idea, but more importantly: Is there any way to validate
273 * hardlinks without keeping a complete list of filenames from the
274 * entire archive?? Ugh.
278 _archive_write_header(struct archive *_a, struct archive_entry *entry)
280 struct archive_write_disk *a = (struct archive_write_disk *)_a;
281 struct fixup_entry *fe;
284 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
285 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
286 "archive_write_disk_header");
287 archive_clear_error(&a->archive);
288 if (a->archive.state & ARCHIVE_STATE_DATA) {
289 r = _archive_write_finish_entry(&a->archive);
294 /* Set up for this particular entry. */
296 a->current_fixup = NULL;
299 archive_entry_free(a->entry);
302 a->entry = archive_entry_clone(entry);
305 a->uid = a->user_uid;
306 a->mode = archive_entry_mode(a->entry);
307 a->filesize = archive_entry_size(a->entry);
308 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
309 a->name = a->_name_data.s;
310 archive_clear_error(&a->archive);
313 * Clean up the requested path. This is necessary for correct
314 * dir restores; the dir restore logic otherwise gets messed
315 * up by nonsense like "dir/.".
317 ret = cleanup_pathname(a);
318 if (ret != ARCHIVE_OK)
322 * Set the umask to zero so we get predictable mode settings.
323 * This gets done on every call to _write_header in case the
324 * user edits their umask during the extraction for some
325 * reason. This will be reset before we return. Note that we
326 * don't need to do this in _finish_entry, as the chmod(), etc,
327 * system calls don't obey umask.
329 a->user_umask = umask(0);
330 /* From here on, early exit requires "goto done" to clean up. */
332 /* Figure out what we need to do for this entry. */
333 a->todo = TODO_MODE_BASE;
334 if (a->flags & ARCHIVE_EXTRACT_PERM) {
335 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
337 * SGID requires an extra "check" step because we
338 * cannot easily predict the GID that the system will
339 * assign. (Different systems assign GIDs to files
340 * based on a variety of criteria, including process
341 * credentials and the gid of the enclosing
342 * directory.) We can only restore the SGID bit if
343 * the file has the right GID, and we only know the
344 * GID if we either set it (see set_ownership) or if
345 * we've actually called stat() on the file after it
346 * was restored. Since there are several places at
347 * which we might verify the GID, we need a TODO bit
350 if (a->mode & S_ISGID)
351 a->todo |= TODO_SGID | TODO_SGID_CHECK;
353 * Verifying the SUID is simpler, but can still be
354 * done in multiple ways, hence the separate "check" bit.
356 if (a->mode & S_ISUID)
357 a->todo |= TODO_SUID | TODO_SUID_CHECK;
360 * User didn't request full permissions, so don't
361 * restore SUID, SGID bits and obey umask.
366 a->mode &= ~a->user_umask;
368 if (a->flags & ARCHIVE_EXTRACT_OWNER)
369 a->todo |= TODO_OWNER;
370 if (a->flags & ARCHIVE_EXTRACT_TIME)
371 a->todo |= TODO_TIMES;
372 if (a->flags & ARCHIVE_EXTRACT_ACL)
373 a->todo |= TODO_ACLS;
374 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
375 a->todo |= TODO_FFLAGS;
376 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
377 ret = check_symlinks(a);
378 if (ret != ARCHIVE_OK)
382 /* If path exceeds PATH_MAX, shorten the path. */
383 edit_deep_directories(a);
386 ret = restore_entry(a);
389 /* If we changed directory above, restore it here. */
390 if (a->restore_pwd >= 0) {
391 fchdir(a->restore_pwd);
392 close(a->restore_pwd);
398 * Fixup uses the unedited pathname from archive_entry_pathname(),
399 * because it is relative to the base dir and the edited path
400 * might be relative to some intermediate dir as a result of the
401 * deep restore logic.
403 if (a->deferred & TODO_MODE) {
404 fe = current_fixup(a, archive_entry_pathname(entry));
405 fe->fixup |= TODO_MODE_BASE;
409 if (a->deferred & TODO_TIMES) {
410 fe = current_fixup(a, archive_entry_pathname(entry));
411 fe->fixup |= TODO_TIMES;
412 fe->mtime = archive_entry_mtime(entry);
413 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
414 fe->atime = archive_entry_atime(entry);
415 fe->atime_nanos = archive_entry_atime_nsec(entry);
418 if (a->deferred & TODO_FFLAGS) {
419 fe = current_fixup(a, archive_entry_pathname(entry));
420 fe->fixup |= TODO_FFLAGS;
421 /* TODO: Complete this.. defer fflags from below. */
424 /* We've created the object and are ready to pour data into it. */
425 if (ret == ARCHIVE_OK)
426 a->archive.state = ARCHIVE_STATE_DATA;
428 * If it's not open, tell our client not to try writing.
429 * In particular, dirs, links, etc, don't get written to.
432 archive_entry_set_size(entry, 0);
436 /* Restore the user's umask before returning. */
437 umask(a->user_umask);
443 archive_write_disk_set_skip_file(struct archive *_a, dev_t d, ino_t i)
445 struct archive_write_disk *a = (struct archive_write_disk *)_a;
446 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
447 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
448 a->skip_file_dev = d;
449 a->skip_file_ino = i;
454 _archive_write_data_block(struct archive *_a,
455 const void *buff, size_t size, off_t offset)
457 struct archive_write_disk *a = (struct archive_write_disk *)_a;
458 ssize_t bytes_written = 0;
461 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
462 ARCHIVE_STATE_DATA, "archive_write_disk_block");
464 archive_set_error(&a->archive, 0, "File not open");
465 return (ARCHIVE_WARN);
467 archive_clear_error(&a->archive);
469 /* Seek if necessary to the specified offset. */
470 if (offset != a->offset) {
471 if (lseek(a->fd, offset, SEEK_SET) < 0) {
472 archive_set_error(&a->archive, errno, "Seek failed");
473 return (ARCHIVE_WARN);
478 /* Write the data. */
479 while (size > 0 && a->offset < a->filesize) {
480 if (a->offset + size > a->filesize) {
481 size = (size_t)(a->filesize - a->offset);
482 archive_set_error(&a->archive, errno,
483 "Write request too large");
486 bytes_written = write(a->fd, buff, size);
487 if (bytes_written < 0) {
488 archive_set_error(&a->archive, errno, "Write failed");
489 return (ARCHIVE_WARN);
491 size -= bytes_written;
492 a->offset += bytes_written;
498 _archive_write_data(struct archive *_a, const void *buff, size_t size)
500 struct archive_write_disk *a = (struct archive_write_disk *)_a;
504 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
505 ARCHIVE_STATE_DATA, "archive_write_data");
510 r = _archive_write_data_block(_a, buff, size, a->offset);
513 return (a->offset - offset);
517 _archive_write_finish_entry(struct archive *_a)
519 struct archive_write_disk *a = (struct archive_write_disk *)_a;
520 int ret = ARCHIVE_OK;
522 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
523 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
524 "archive_write_finish_entry");
525 if (a->archive.state & ARCHIVE_STATE_HEADER)
527 archive_clear_error(&a->archive);
529 /* Restore metadata. */
532 * Look up the "real" UID only if we're going to need it. We
533 * need this for TODO_SGID because chown() requires both.
535 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
536 a->uid = a->lookup_uid(a->lookup_uid_data,
537 archive_entry_uname(a->entry),
538 archive_entry_uid(a->entry));
540 /* Look up the "real" GID only if we're going to need it. */
541 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
542 a->gid = a->lookup_gid(a->lookup_gid_data,
543 archive_entry_gname(a->entry),
544 archive_entry_gid(a->entry));
547 * If restoring ownership, do it before trying to restore suid/sgid
548 * bits. If we set the owner, we know what it is and can skip
549 * a stat() call to examine the ownership of the file on disk.
551 if (a->todo & TODO_OWNER)
552 ret = set_ownership(a);
553 if (a->todo & TODO_MODE) {
554 int r2 = set_mode(a, a->mode);
555 if (r2 < ret) ret = r2;
557 if (a->todo & TODO_TIMES) {
558 int r2 = set_time(a);
559 if (r2 < ret) ret = r2;
561 if (a->todo & TODO_ACLS) {
562 int r2 = set_acls(a);
563 if (r2 < ret) ret = r2;
565 if (a->todo & TODO_XATTR) {
566 int r2 = set_xattrs(a);
567 if (r2 < ret) ret = r2;
569 if (a->todo & TODO_FFLAGS) {
570 int r2 = set_fflags(a);
571 if (r2 < ret) ret = r2;
574 /* If there's an fd, we can close it now. */
579 /* If there's an entry, we can release it now. */
581 archive_entry_free(a->entry);
584 a->archive.state = ARCHIVE_STATE_HEADER;
589 archive_write_disk_set_group_lookup(struct archive *_a,
591 gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid),
592 void (*cleanup_gid)(void *private))
594 struct archive_write_disk *a = (struct archive_write_disk *)_a;
595 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
596 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
598 a->lookup_gid = lookup_gid;
599 a->cleanup_gid = cleanup_gid;
600 a->lookup_gid_data = private_data;
605 archive_write_disk_set_user_lookup(struct archive *_a,
607 uid_t (*lookup_uid)(void *private, const char *uname, uid_t uid),
608 void (*cleanup_uid)(void *private))
610 struct archive_write_disk *a = (struct archive_write_disk *)_a;
611 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
612 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
614 a->lookup_uid = lookup_uid;
615 a->cleanup_uid = cleanup_uid;
616 a->lookup_uid_data = private_data;
622 * Create a new archive_write_disk object and initialize it with global state.
625 archive_write_disk_new(void)
627 struct archive_write_disk *a;
629 a = (struct archive_write_disk *)malloc(sizeof(*a));
632 memset(a, 0, sizeof(*a));
633 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
634 /* We're ready to write a header immediately. */
635 a->archive.state = ARCHIVE_STATE_HEADER;
636 a->archive.vtable = archive_write_disk_vtable();
637 a->lookup_uid = trivial_lookup_uid;
638 a->lookup_gid = trivial_lookup_gid;
639 a->user_uid = geteuid();
640 if (archive_string_ensure(&a->path_safe, 512) == NULL) {
644 return (&a->archive);
649 * If pathname is longer than PATH_MAX, chdir to a suitable
650 * intermediate dir and edit the path down to a shorter suffix. Note
651 * that this routine never returns an error; if the chdir() attempt
652 * fails for any reason, we just go ahead with the long pathname. The
653 * object creation is likely to fail, but any error will get handled
658 edit_deep_directories(struct archive_write_disk *a)
661 char *tail = a->name;
665 /* If path is short, avoid the open() below. */
666 if (strlen(tail) <= PATH_MAX)
669 /* Try to record our starting dir. */
670 a->restore_pwd = open(".", O_RDONLY);
671 if (a->restore_pwd < 0)
674 /* As long as the path is too long... */
675 while (strlen(tail) > PATH_MAX) {
676 /* Locate a dir prefix shorter than PATH_MAX. */
677 tail += PATH_MAX - 8;
678 while (tail > a->name && *tail != '/')
680 /* Exit if we find a too-long path component. */
683 /* Create the intermediate dir and chdir to it. */
684 *tail = '\0'; /* Terminate dir portion */
685 ret = create_dir(a, a->name);
686 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
688 *tail = '/'; /* Restore the / we removed. */
689 if (ret != ARCHIVE_OK)
692 /* The chdir() succeeded; we've now shortened the path. */
700 * The main restore function.
703 restore_entry(struct archive_write_disk *a)
705 int ret = ARCHIVE_OK, en;
707 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
708 if (unlink(a->name) == 0) {
709 /* We removed it, we're done. */
710 } else if (errno == ENOENT) {
711 /* File didn't exist, that's just as good. */
712 } else if (rmdir(a->name) == 0) {
713 /* It was a dir, but now it's gone. */
715 /* We tried, but couldn't get rid of it. */
716 archive_set_error(&a->archive, errno,
718 return(ARCHIVE_WARN);
722 /* Try creating it first; if this fails, we'll try to recover. */
723 en = create_filesystem_object(a);
725 if ((en == ENOTDIR || en == ENOENT)
726 && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
727 /* If the parent dir doesn't exist, try creating it. */
728 create_parent_dir(a, a->name);
729 /* Now try to create the object again. */
730 en = create_filesystem_object(a);
733 if ((en == EISDIR || en == EEXIST)
734 && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
735 /* If we're not overwriting, we're done. */
736 archive_set_error(&a->archive, en, "Already exists");
737 return (ARCHIVE_WARN);
741 * Some platforms return EISDIR if you call
742 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
743 * return EEXIST. POSIX is ambiguous, requiring EISDIR
744 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
745 * on an existing item.
748 /* A dir is in the way of a non-dir, rmdir it. */
749 if (rmdir(a->name) != 0) {
750 archive_set_error(&a->archive, errno,
751 "Can't remove already-existing dir");
752 return (ARCHIVE_WARN);
755 en = create_filesystem_object(a);
756 } else if (en == EEXIST) {
758 * We know something is in the way, but we don't know what;
759 * we need to find out before we go any further.
761 if (lstat(a->name, &a->st) != 0) {
762 archive_set_error(&a->archive, errno,
763 "Can't stat existing object");
764 return (ARCHIVE_WARN);
767 /* TODO: if it's a symlink... */
769 if (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER) {
770 if (!older(&(a->st), a->entry)) {
771 archive_set_error(&a->archive, 0,
772 "File on disk is not older; skipping.");
773 return (ARCHIVE_FAILED);
777 /* If it's our archive, we're done. */
778 if (a->skip_file_dev > 0 &&
779 a->skip_file_ino > 0 &&
780 a->st.st_dev == a->skip_file_dev &&
781 a->st.st_ino == a->skip_file_ino) {
782 archive_set_error(&a->archive, 0, "Refusing to overwrite archive");
783 return (ARCHIVE_FAILED);
786 if (!S_ISDIR(a->st.st_mode)) {
787 /* A non-dir is in the way, unlink it. */
788 if (unlink(a->name) != 0) {
789 archive_set_error(&a->archive, errno,
790 "Can't unlink already-existing object");
791 return (ARCHIVE_WARN);
794 en = create_filesystem_object(a);
795 } else if (!S_ISDIR(a->mode)) {
796 /* A dir is in the way of a non-dir, rmdir it. */
797 if (rmdir(a->name) != 0) {
798 archive_set_error(&a->archive, errno,
799 "Can't remove already-existing dir");
800 return (ARCHIVE_WARN);
803 en = create_filesystem_object(a);
806 * There's a dir in the way of a dir. Don't
807 * waste time with rmdir()/mkdir(), just fix
808 * up the permissions on the existing dir.
809 * Note that we don't change perms on existing
810 * dirs unless _EXTRACT_PERM is specified.
812 if ((a->mode != a->st.st_mode)
813 && (a->todo & TODO_MODE_FORCE))
814 a->deferred |= (a->todo & TODO_MODE);
815 /* Ownership doesn't need deferred fixup. */
816 en = 0; /* Forget the EEXIST. */
821 /* Everything failed; give up here. */
822 archive_set_error(&a->archive, en, "Can't create '%s'", a->name);
823 return (ARCHIVE_WARN);
826 a->pst = NULL; /* Cached stat data no longer valid. */
831 * Returns 0 if creation succeeds, or else returns errno value from
832 * the failed system call. Note: This function should only ever perform
833 * a single system call.
836 create_filesystem_object(struct archive_write_disk *a)
838 /* Create the entry. */
839 const char *linkname;
840 mode_t final_mode, mode;
843 /* We identify hard/symlinks according to the link names. */
844 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
845 linkname = archive_entry_hardlink(a->entry);
846 if (linkname != NULL) {
847 r = link(linkname, a->name) ? errno : 0;
849 * New cpio and pax formats allow hardlink entries
850 * to carry data, so we may have to open the file
851 * for hardlink entries.
853 if (r == 0 && a->filesize > 0) {
854 a->fd = open(a->name, O_WRONLY | O_TRUNC);
860 linkname = archive_entry_symlink(a->entry);
861 if (linkname != NULL)
862 return symlink(linkname, a->name) ? errno : 0;
865 * The remaining system calls all set permissions, so let's
866 * try to take advantage of that to avoid an extra chmod()
867 * call. (Recall that umask is set to zero right now!)
870 /* Mode we want for the final restored object (w/o file type bits). */
871 final_mode = a->mode & 07777;
873 * The mode that will actually be restored in this step. Note
874 * that SUID, SGID, etc, require additional work to ensure
875 * security, so we never restore them at this point.
877 mode = final_mode & 0777;
879 switch (a->mode & S_IFMT) {
881 /* POSIX requires that we fall through here. */
884 a->fd = open(a->name,
885 O_WRONLY | O_CREAT | O_EXCL, mode);
889 r = mknod(a->name, mode | S_IFCHR,
890 archive_entry_rdev(a->entry));
893 r = mknod(a->name, mode | S_IFBLK,
894 archive_entry_rdev(a->entry));
897 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
898 r = mkdir(a->name, mode);
900 /* Defer setting dir times. */
901 a->deferred |= (a->todo & TODO_TIMES);
902 a->todo &= ~TODO_TIMES;
903 /* Never use an immediate chmod(). */
904 if (mode != final_mode)
905 a->deferred |= (a->todo & TODO_MODE);
906 a->todo &= ~TODO_MODE;
910 r = mkfifo(a->name, mode);
914 /* All the system calls above set errno on failure. */
918 /* If we managed to set the final mode, we've avoided a chmod(). */
919 if (mode == final_mode)
920 a->todo &= ~TODO_MODE;
925 * Cleanup function for archive_extract. Mostly, this involves processing
926 * the fixup list, which is used to address a number of problems:
927 * * Dir permissions might prevent us from restoring a file in that
928 * dir, so we restore the dir with minimum 0700 permissions first,
929 * then correct the mode at the end.
930 * * Similarly, the act of restoring a file touches the directory
931 * and changes the timestamp on the dir, so we have to touch-up dir
932 * timestamps at the end as well.
933 * * Some file flags can interfere with the restore by, for example,
934 * preventing the creation of hardlinks to those files.
936 * Note that tar/cpio do not require that archives be in a particular
937 * order; there is no way to know when the last file has been restored
938 * within a directory, so there's no way to optimize the memory usage
939 * here by fixing up the directory any earlier than the
942 * XXX TODO: Directory ACLs should be restored here, for the same
943 * reason we set directory perms here. XXX
946 _archive_write_close(struct archive *_a)
948 struct archive_write_disk *a = (struct archive_write_disk *)_a;
949 struct fixup_entry *next, *p;
952 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
953 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
954 "archive_write_disk_close");
955 ret = _archive_write_finish_entry(&a->archive);
957 /* Sort dir list so directories are fixed up in depth-first order. */
958 p = sort_dir_list(a->fixup_list);
961 a->pst = NULL; /* Mark stat cache as out-of-date. */
962 if (p->fixup & TODO_TIMES) {
964 /* {f,l,}utimes() are preferred, when available. */
965 struct timeval times[2];
966 times[1].tv_sec = p->mtime;
967 times[1].tv_usec = p->mtime_nanos / 1000;
968 times[0].tv_sec = p->atime;
969 times[0].tv_usec = p->atime_nanos / 1000;
971 lutimes(p->name, times);
973 utimes(p->name, times);
976 /* utime() is more portable, but less precise. */
977 struct utimbuf times;
978 times.modtime = p->mtime;
979 times.actime = p->atime;
981 utime(p->name, ×);
984 if (p->fixup & TODO_MODE_BASE)
985 chmod(p->name, p->mode);
987 if (p->fixup & TODO_FFLAGS)
988 set_fflags_platform(a, -1, p->name,
989 p->mode, p->fflags_set, 0);
996 a->fixup_list = NULL;
1001 _archive_write_finish(struct archive *_a)
1003 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1005 ret = _archive_write_close(&a->archive);
1006 if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1007 (a->cleanup_gid)(a->lookup_gid_data);
1008 if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1009 (a->cleanup_uid)(a->lookup_uid_data);
1010 archive_string_free(&a->_name_data);
1011 archive_string_free(&a->archive.error_string);
1012 archive_string_free(&a->path_safe);
1018 * Simple O(n log n) merge sort to order the fixup list. In
1019 * particular, we want to restore dir timestamps depth-first.
1021 static struct fixup_entry *
1022 sort_dir_list(struct fixup_entry *p)
1024 struct fixup_entry *a, *b, *t;
1028 /* A one-item list is already sorted. */
1029 if (p->next == NULL)
1032 /* Step 1: split the list. */
1036 /* Step a twice, t once. */
1042 /* Now, t is at the mid-point, so break the list here. */
1047 /* Step 2: Recursively sort the two sub-lists. */
1048 a = sort_dir_list(a);
1049 b = sort_dir_list(b);
1051 /* Step 3: Merge the returned lists. */
1052 /* Pick the first element for the merged list. */
1053 if (strcmp(a->name, b->name) > 0) {
1061 /* Always put the later element on the list first. */
1062 while (a != NULL && b != NULL) {
1063 if (strcmp(a->name, b->name) > 0) {
1073 /* Only one list is non-empty, so just splice it on. */
1083 * Returns a new, initialized fixup entry.
1085 * TODO: Reduce the memory requirements for this list by using a tree
1086 * structure rather than a simple list of names.
1088 static struct fixup_entry *
1089 new_fixup(struct archive_write_disk *a, const char *pathname)
1091 struct fixup_entry *fe;
1093 fe = (struct fixup_entry *)malloc(sizeof(struct fixup_entry));
1096 fe->next = a->fixup_list;
1099 fe->name = strdup(pathname);
1104 * Returns a fixup structure for the current entry.
1106 static struct fixup_entry *
1107 current_fixup(struct archive_write_disk *a, const char *pathname)
1109 if (a->current_fixup == NULL)
1110 a->current_fixup = new_fixup(a, pathname);
1111 return (a->current_fixup);
1114 /* TODO: Make this work. */
1116 * TODO: The deep-directory support bypasses this; disable deep directory
1117 * support if we're doing symlink checks.
1120 * TODO: Someday, integrate this with the deep dir support; they both
1121 * scan the path and both can be optimized by comparing against other
1125 check_symlinks(struct archive_write_disk *a)
1133 * Gaurd against symlink tricks. Reject any archive entry whose
1134 * destination would be altered by a symlink.
1136 /* Whatever we checked last time doesn't need to be re-checked. */
1139 while ((*pn != '\0') && (*p == *pn))
1142 /* Keep going until we've checked the entire name. */
1143 while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
1144 /* Skip the next path element. */
1145 while (*pn != '\0' && *pn != '/')
1149 /* Check that we haven't hit a symlink. */
1150 r = lstat(a->name, &st);
1152 /* We've hit a dir that doesn't exist; stop now. */
1153 if (errno == ENOENT)
1155 } else if (S_ISLNK(st.st_mode)) {
1158 * Last element is symlink; remove it
1159 * so we can overwrite it with the
1160 * item being extracted.
1162 if (unlink(a->name)) {
1163 archive_set_error(&a->archive, errno,
1164 "Could not remove symlink %s",
1167 return (ARCHIVE_WARN);
1170 * Even if we did remove it, a warning
1171 * is in order. The warning is silly,
1172 * though, if we're just replacing one
1173 * symlink with another symlink.
1175 if (!S_ISLNK(a->mode)) {
1176 archive_set_error(&a->archive, 0,
1177 "Removing symlink %s",
1180 /* Symlink gone. No more problem! */
1183 } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
1184 /* User asked us to remove problems. */
1185 if (unlink(a->name) != 0) {
1186 archive_set_error(&a->archive, 0,
1187 "Cannot remove intervening symlink %s",
1190 return (ARCHIVE_WARN);
1193 archive_set_error(&a->archive, 0,
1194 "Cannot extract through symlink %s",
1197 return (ARCHIVE_WARN);
1202 /* We've checked and/or cleaned the whole path, so remember it. */
1203 archive_strcpy(&a->path_safe, a->name);
1204 return (ARCHIVE_OK);
1208 * Canonicalize the pathname. In particular, this strips duplicate
1209 * '/' characters, '.' elements, and trailing '/'. It also raises an
1210 * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
1211 * set) any '..' in the path.
1214 cleanup_pathname(struct archive_write_disk *a)
1217 char separator = '\0';
1218 int lastdotdot = 0; /* True if last elt copied was '..' */
1220 dest = src = a->name;
1222 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1223 "Invalid empty pathname");
1224 return (ARCHIVE_WARN);
1227 /* Skip leading '/'. */
1231 /* Scan the pathname one element at a time. */
1233 /* src points to first char after '/' */
1234 if (src[0] == '\0') {
1236 } else if (src[0] == '/') {
1237 /* Found '//', ignore second one. */
1240 } else if (src[0] == '.') {
1241 if (src[1] == '\0') {
1242 /* Ignore trailing '.' */
1244 } else if (src[1] == '/') {
1248 } else if (src[1] == '.') {
1249 if (src[2] == '/' || src[2] == '\0') {
1250 /* Conditionally warn about '..' */
1251 if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
1252 archive_set_error(&a->archive,
1254 "Path contains '..'");
1255 return (ARCHIVE_WARN);
1261 * Note: Under no circumstances do we
1262 * remove '..' elements. In
1263 * particular, restoring
1264 * '/foo/../bar/' should create the
1265 * 'foo' dir as a side-effect.
1272 /* Copy current element, including leading '/'. */
1275 while (*src != '\0' && *src != '/') {
1282 /* Skip '/' separator. */
1286 * We've just copied zero or more path elements, not including the
1290 /* Trailing '..' is always wrong. */
1291 archive_set_error(&a->archive,
1293 "Path contains trailing '..'");
1294 return (ARCHIVE_WARN);
1296 if (dest == a->name) {
1298 * Nothing got copied. The path must have been something
1299 * like '.' or '/' or './' or '/././././/./'.
1306 /* Terminate the result. */
1308 return (ARCHIVE_OK);
1312 * Create the parent directory of the specified path, assuming path
1313 * is already in mutable storage.
1316 create_parent_dir(struct archive_write_disk *a, char *path)
1321 /* Remove tail element to obtain parent name. */
1322 slash = strrchr(path, '/');
1324 return (ARCHIVE_OK);
1326 r = create_dir(a, path);
1332 * Create the specified dir, recursing to create parents as necessary.
1334 * Returns ARCHIVE_OK if the path exists when we're done here.
1335 * Otherwise, returns ARCHIVE_WARN.
1336 * Assumes path is in mutable storage; path is unchanged on exit.
1339 create_dir(struct archive_write_disk *a, char *path)
1342 struct fixup_entry *le;
1344 mode_t mode_final, mode;
1349 /* Check for special names and just skip them. */
1350 slash = strrchr(path, '/');
1356 if (base[0] == '\0' ||
1357 (base[0] == '.' && base[1] == '\0') ||
1358 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
1359 /* Don't bother trying to create null path, '.', or '..'. */
1360 if (slash != NULL) {
1362 r = create_dir(a, path);
1366 return (ARCHIVE_OK);
1370 * Yes, this should be stat() and not lstat(). Using lstat()
1371 * here loses the ability to extract through symlinks. Also note
1372 * that this should not use the a->st cache.
1374 if (stat(path, &st) == 0) {
1375 if (S_ISDIR(st.st_mode))
1376 return (ARCHIVE_OK);
1377 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1378 archive_set_error(&a->archive, EEXIST,
1379 "Can't create directory '%s'", path);
1380 return (ARCHIVE_WARN);
1382 if (unlink(path) != 0) {
1383 archive_set_error(&a->archive, errno,
1384 "Can't create directory '%s': "
1385 "Conflicting file cannot be removed");
1386 return (ARCHIVE_WARN);
1388 } else if (errno != ENOENT && errno != ENOTDIR) {
1390 archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
1391 return (ARCHIVE_WARN);
1392 } else if (slash != NULL) {
1394 r = create_dir(a, path);
1396 if (r != ARCHIVE_OK)
1401 * Mode we want for the final restored directory. Per POSIX,
1402 * implicitly-created dirs must be created obeying the umask.
1403 * There's no mention whether this is different for privileged
1404 * restores (which the rest of this code handles by pretending
1405 * umask=0). I've chosen here to always obey the user's umask for
1406 * implicit dirs, even if _EXTRACT_PERM was specified.
1408 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
1409 /* Mode we want on disk during the restore process. */
1411 mode |= MINIMUM_DIR_MODE;
1412 mode &= MAXIMUM_DIR_MODE;
1413 if (mkdir(path, mode) == 0) {
1414 if (mode != mode_final) {
1415 le = new_fixup(a, path);
1416 le->fixup |=TODO_MODE_BASE;
1417 le->mode = mode_final;
1419 return (ARCHIVE_OK);
1423 * Without the following check, a/b/../b/c/d fails at the
1424 * second visit to 'b', so 'd' can't be created. Note that we
1425 * don't add it to the fixup list here, as it's already been
1428 if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1429 return (ARCHIVE_OK);
1431 archive_set_error(&a->archive, errno, "Failed to create dir '%s'", path);
1432 return (ARCHIVE_WARN);
1436 * Note: Although we can skip setting the user id if the desired user
1437 * id matches the current user, we cannot skip setting the group, as
1438 * many systems set the gid bit based on the containing directory. So
1439 * we have to perform a chown syscall if we want to restore the SGID
1440 * bit. (The alternative is to stat() and then possibly chown(); it's
1441 * more efficient to skip the stat() and just always chown().) Note
1442 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
1443 * allows set_mode to skip the stat() check for the GID.
1446 set_ownership(struct archive_write_disk *a)
1448 /* If we know we can't change it, don't bother trying. */
1449 if (a->user_uid != 0 && a->user_uid != a->uid) {
1450 archive_set_error(&a->archive, errno,
1451 "Can't set UID=%d", a->uid);
1452 return (ARCHIVE_WARN);
1456 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0)
1461 if (lchown(a->name, a->uid, a->gid) == 0)
1464 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0)
1468 archive_set_error(&a->archive, errno,
1469 "Can't set user=%d/group=%d for %s", a->uid, a->gid,
1471 return (ARCHIVE_WARN);
1473 a->todo &= ~TODO_OWNER;
1474 /* We know the user/group are correct now. */
1475 a->todo &= ~TODO_SGID_CHECK;
1476 a->todo &= ~TODO_SUID_CHECK;
1477 return (ARCHIVE_OK);
1482 * The utimes()-family functions provide high resolution and
1483 * a way to set time on an fd or a symlink. We prefer them
1484 * when they're available.
1487 set_time(struct archive_write_disk *a)
1489 struct timeval times[2];
1491 times[1].tv_sec = archive_entry_mtime(a->entry);
1492 times[1].tv_usec = archive_entry_mtime_nsec(a->entry) / 1000;
1494 times[0].tv_sec = archive_entry_atime(a->entry);
1495 times[0].tv_usec = archive_entry_atime_nsec(a->entry) / 1000;
1498 if (a->fd >= 0 && futimes(a->fd, times) == 0) {
1499 return (ARCHIVE_OK);
1504 if (lutimes(a->name, times) != 0)
1506 if (!S_ISLNK(a->mode) && utimes(a->name, times) != 0)
1509 archive_set_error(&a->archive, errno, "Can't update time for %s",
1511 return (ARCHIVE_WARN);
1515 * Note: POSIX does not provide a portable way to restore ctime.
1516 * (Apart from resetting the system clock, which is distasteful.)
1517 * So, any restoration of ctime will necessarily be OS-specific.
1520 /* XXX TODO: Can FreeBSD restore ctime? XXX */
1521 return (ARCHIVE_OK);
1523 #elif defined(HAVE_UTIME)
1525 * utime() is an older, more standard interface that we'll use
1526 * if utimes() isn't available.
1529 set_time(struct archive_write_disk *a)
1531 struct utimbuf times;
1533 times.modtime = archive_entry_mtime(a->entry);
1534 times.actime = archive_entry_atime(a->entry);
1535 if (!S_ISLNK(a->mode) && utime(a->name, ×) != 0) {
1536 archive_set_error(&a->archive, errno,
1537 "Can't update time for %s", a->name);
1538 return (ARCHIVE_WARN);
1540 return (ARCHIVE_OK);
1543 /* This platform doesn't give us a way to restore the time. */
1545 set_time(struct archive_write_disk *a)
1547 (void)a; /* UNUSED */
1548 archive_set_error(&a->archive, errno,
1549 "Can't update time for %s", a->name);
1550 return (ARCHIVE_WARN);
1556 set_mode(struct archive_write_disk *a, int mode)
1559 mode &= 07777; /* Strip off file type bits. */
1561 if (a->todo & TODO_SGID_CHECK) {
1563 * If we don't know the GID is right, we must stat()
1564 * to verify it. We can't just check the GID of this
1565 * process, since systems sometimes set GID from
1566 * the enclosing dir or based on ACLs.
1568 if (a->pst != NULL) {
1569 /* Already have stat() data available. */
1571 } else if (fd >= 0 && fstat(fd, &a->st) == 0) {
1574 } else if (stat(a->name, &a->st) == 0) {
1577 archive_set_error(&a->archive, errno,
1578 "Couldn't stat file");
1579 return (ARCHIVE_WARN);
1581 if (a->pst->st_gid != a->gid) {
1583 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1585 * This is only an error if you
1586 * requested owner restore. If you
1587 * didn't, we'll try to restore
1588 * sgid/suid, but won't consider it a
1589 * problem if we can't.
1591 archive_set_error(&a->archive, -1,
1592 "Can't restore SGID bit");
1596 /* While we're here, double-check the UID. */
1597 if (a->pst->st_uid != a->uid
1598 && (a->todo & TODO_SUID)) {
1600 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1601 archive_set_error(&a->archive, -1,
1602 "Can't restore SUID bit");
1606 a->todo &= ~TODO_SGID_CHECK;
1607 a->todo &= ~TODO_SUID_CHECK;
1608 } else if (a->todo & TODO_SUID_CHECK) {
1610 * If we don't know the UID is right, we can just check
1611 * the user, since all systems set the file UID from
1614 if (a->user_uid != a->uid) {
1616 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1617 archive_set_error(&a->archive, -1,
1618 "Can't make file SUID");
1622 a->todo &= ~TODO_SUID_CHECK;
1625 if (S_ISLNK(a->mode)) {
1628 * If this is a symlink, use lchmod(). If the
1629 * platform doesn't support lchmod(), just skip it. A
1630 * platform that doesn't provide a way to set
1631 * permissions on symlinks probably ignores
1632 * permissions on symlinks, so a failure here has no
1635 if (lchmod(a->name, mode) != 0) {
1636 archive_set_error(&a->archive, errno,
1637 "Can't set permissions to 0%o", (int)mode);
1641 } else if (!S_ISDIR(a->mode)) {
1643 * If it's not a symlink and not a dir, then use
1644 * fchmod() or chmod(), depending on whether we have
1645 * an fd. Dirs get their perms set during the
1646 * post-extract fixup, which is handled elsewhere.
1650 if (fchmod(a->fd, mode) != 0) {
1651 archive_set_error(&a->archive, errno,
1652 "Can't set permissions to 0%o", (int)mode);
1657 /* If this platform lacks fchmod(), then
1658 * we'll just use chmod(). */
1659 if (chmod(a->name, mode) != 0) {
1660 archive_set_error(&a->archive, errno,
1661 "Can't set permissions to 0%o", (int)mode);
1669 set_fflags(struct archive_write_disk *a)
1671 struct fixup_entry *le;
1672 unsigned long set, clear;
1675 mode_t mode = archive_entry_mode(a->entry);
1678 * Make 'critical_flags' hold all file flags that can't be
1679 * immediately restored. For example, on BSD systems,
1680 * SF_IMMUTABLE prevents hardlinks from being created, so
1681 * should not be set until after any hardlinks are created. To
1682 * preserve some semblance of portability, this uses #ifdef
1683 * extensively. Ugly, but it works.
1685 * Yes, Virginia, this does create a security race. It's mitigated
1686 * somewhat by the practice of creating dirs 0700 until the extract
1687 * is done, but it would be nice if we could do more than that.
1688 * People restoring critical file systems should be wary of
1689 * other programs that might try to muck with files as they're
1692 /* Hopefully, the compiler will optimize this mess into a constant. */
1695 critical_flags |= SF_IMMUTABLE;
1698 critical_flags |= UF_IMMUTABLE;
1701 critical_flags |= SF_APPEND;
1704 critical_flags |= UF_APPEND;
1706 #ifdef EXT2_APPEND_FL
1707 critical_flags |= EXT2_APPEND_FL;
1709 #ifdef EXT2_IMMUTABLE_FL
1710 critical_flags |= EXT2_IMMUTABLE_FL;
1713 if (a->todo & TODO_FFLAGS) {
1714 archive_entry_fflags(a->entry, &set, &clear);
1717 * The first test encourages the compiler to eliminate
1718 * all of this if it's not necessary.
1720 if ((critical_flags != 0) && (set & critical_flags)) {
1721 le = current_fixup(a, a->name);
1722 le->fixup |= TODO_FFLAGS;
1723 le->fflags_set = set;
1724 /* Store the mode if it's not already there. */
1725 if ((le->fixup & TODO_MODE) == 0)
1728 r = set_fflags_platform(a, a->fd,
1729 a->name, mode, set, clear);
1730 if (r != ARCHIVE_OK)
1734 return (ARCHIVE_OK);
1738 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && !defined(__linux)
1740 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1741 mode_t mode, unsigned long set, unsigned long clear)
1743 (void)mode; /* UNUSED */
1744 if (set == 0 && clear == 0)
1745 return (ARCHIVE_OK);
1748 * XXX Is the stat here really necessary? Or can I just use
1749 * the 'set' flags directly? In particular, I'm not sure
1750 * about the correct approach if we're overwriting an existing
1751 * file that already has flags on it. XXX
1753 if (fd >= 0 && fstat(fd, &a->st) == 0)
1755 else if (lstat(name, &a->st) == 0)
1758 archive_set_error(&a->archive, errno,
1759 "Couldn't stat file");
1760 return (ARCHIVE_WARN);
1763 a->st.st_flags &= ~clear;
1764 a->st.st_flags |= set;
1765 #ifdef HAVE_FCHFLAGS
1766 /* If platform has fchflags() and we were given an fd, use it. */
1767 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
1768 return (ARCHIVE_OK);
1771 * If we can't use the fd to set the flags, we'll use the
1772 * pathname to set flags. We prefer lchflags() but will use
1773 * chflags() if we must.
1775 #ifdef HAVE_LCHFLAGS
1776 if (lchflags(name, a->st.st_flags) == 0)
1777 return (ARCHIVE_OK);
1778 #elif defined(HAVE_CHFLAGS)
1779 if (S_ISLNK(a->st.st_mode)) {
1780 archive_set_error(&a->archive, errno,
1781 "Can't set file flags on symlink.");
1782 return (ARCHIVE_WARN);
1784 if (chflags(name, a->st.st_flags) == 0)
1785 return (ARCHIVE_OK);
1787 archive_set_error(&a->archive, errno,
1788 "Failed to set file flags");
1789 return (ARCHIVE_WARN);
1792 #elif defined(__linux) && defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS)
1795 * Linux has flags too, but uses ioctl() to access them instead of
1796 * having a separate chflags() system call.
1799 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1800 mode_t mode, unsigned long set, unsigned long clear)
1804 unsigned long newflags, oldflags;
1805 unsigned long sf_mask = 0;
1807 if (set == 0 && clear == 0)
1808 return (ARCHIVE_OK);
1809 /* Only regular files and dirs can have flags. */
1810 if (!S_ISREG(mode) && !S_ISDIR(mode))
1811 return (ARCHIVE_OK);
1813 /* If we weren't given an fd, open it ourselves. */
1815 myfd = open(name, O_RDONLY|O_NONBLOCK);
1817 return (ARCHIVE_OK);
1820 * Linux has no define for the flags that are only settable by
1821 * the root user. This code may seem a little complex, but
1822 * there seem to be some Linux systems that lack these
1823 * defines. (?) The code below degrades reasonably gracefully
1824 * if sf_mask is incomplete.
1826 #ifdef EXT2_IMMUTABLE_FL
1827 sf_mask |= EXT2_IMMUTABLE_FL;
1829 #ifdef EXT2_APPEND_FL
1830 sf_mask |= EXT2_APPEND_FL;
1833 * XXX As above, this would be way simpler if we didn't have
1834 * to read the current flags from disk. XXX
1837 /* Try setting the flags as given. */
1838 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1839 newflags = (oldflags & ~clear) | set;
1840 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1845 /* If we couldn't set all the flags, try again with a subset. */
1846 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1847 newflags &= ~sf_mask;
1848 oldflags &= sf_mask;
1849 newflags |= oldflags;
1850 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1853 /* We couldn't set the flags, so report the failure. */
1855 archive_set_error(&a->archive, errno,
1856 "Failed to set file flags");
1864 #else /* Not HAVE_CHFLAGS && Not __linux */
1867 * Of course, some systems have neither BSD chflags() nor Linux' flags
1868 * support through ioctl().
1871 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1872 mode_t mode, unsigned long set, unsigned long clear)
1874 (void)a; /* UNUSED */
1875 (void)fd; /* UNUSED */
1876 (void)name; /* UNUSED */
1877 (void)mode; /* UNUSED */
1878 (void)set; /* UNUSED */
1879 (void)clear; /* UNUSED */
1880 return (ARCHIVE_OK);
1883 #endif /* __linux */
1885 #ifndef HAVE_POSIX_ACL
1886 /* Default empty function body to satisfy mainline code. */
1888 set_acls(struct archive_write_disk *a)
1890 (void)a; /* UNUSED */
1891 return (ARCHIVE_OK);
1897 * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
1900 set_acls(struct archive_write_disk *a)
1904 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_ACCESS,
1905 ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
1906 if (ret != ARCHIVE_OK)
1908 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_DEFAULT,
1909 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
1915 set_acl(struct archive_write_disk *a, int fd, struct archive_entry *entry,
1916 acl_type_t acl_type, int ae_requested_type, const char *tname)
1919 acl_entry_t acl_entry;
1920 acl_permset_t acl_permset;
1922 int ae_type, ae_permset, ae_tag, ae_id;
1925 const char *ae_name;
1930 entries = archive_entry_acl_reset(entry, ae_requested_type);
1932 return (ARCHIVE_OK);
1933 acl = acl_init(entries);
1934 while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
1935 &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
1936 acl_create_entry(&acl, &acl_entry);
1939 case ARCHIVE_ENTRY_ACL_USER:
1940 acl_set_tag_type(acl_entry, ACL_USER);
1941 ae_uid = a->lookup_uid(a->lookup_uid_data,
1943 acl_set_qualifier(acl_entry, &ae_uid);
1945 case ARCHIVE_ENTRY_ACL_GROUP:
1946 acl_set_tag_type(acl_entry, ACL_GROUP);
1947 ae_gid = a->lookup_gid(a->lookup_gid_data,
1949 acl_set_qualifier(acl_entry, &ae_gid);
1951 case ARCHIVE_ENTRY_ACL_USER_OBJ:
1952 acl_set_tag_type(acl_entry, ACL_USER_OBJ);
1954 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
1955 acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
1957 case ARCHIVE_ENTRY_ACL_MASK:
1958 acl_set_tag_type(acl_entry, ACL_MASK);
1960 case ARCHIVE_ENTRY_ACL_OTHER:
1961 acl_set_tag_type(acl_entry, ACL_OTHER);
1968 acl_get_permset(acl_entry, &acl_permset);
1969 acl_clear_perms(acl_permset);
1970 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
1971 acl_add_perm(acl_permset, ACL_EXECUTE);
1972 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
1973 acl_add_perm(acl_permset, ACL_WRITE);
1974 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
1975 acl_add_perm(acl_permset, ACL_READ);
1978 name = archive_entry_pathname(entry);
1980 /* Try restoring the ACL through 'fd' if we can. */
1982 if (fd >= 0 && acl_type == ACL_TYPE_ACCESS && acl_set_fd(fd, acl) == 0)
1986 #if HAVE_ACL_SET_FD_NP
1987 if (fd >= 0 && acl_set_fd_np(fd, acl, acl_type) == 0)
1992 if (acl_set_file(name, acl_type, acl) != 0) {
1993 archive_set_error(&a->archive, errno, "Failed to set %s acl", tname);
2003 * Restore extended attributes - Linux implementation
2006 set_xattrs(struct archive_write_disk *a)
2008 struct archive_entry *entry = a->entry;
2009 static int warning_done = 0;
2010 int ret = ARCHIVE_OK;
2011 int i = archive_entry_xattr_reset(entry);
2017 archive_entry_xattr_next(entry, &name, &value, &size);
2019 strncmp(name, "xfsroot.", 8) != 0 &&
2020 strncmp(name, "system.", 7) != 0) {
2024 e = fsetxattr(a->fd, name, value, size, 0);
2028 e = lsetxattr(archive_entry_pathname(entry),
2029 name, value, size, 0);
2032 if (errno == ENOTSUP) {
2033 if (!warning_done) {
2035 archive_set_error(&a->archive, errno,
2036 "Cannot restore extended "
2037 "attributes on this file "
2041 archive_set_error(&a->archive, errno,
2042 "Failed to set extended attribute");
2046 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2047 "Invalid extended attribute encountered");
2055 * Restore extended attributes - stub implementation for unsupported systems
2058 set_xattrs(struct archive_write_disk *a)
2060 static int warning_done = 0;
2062 /* If there aren't any extended attributes, then it's okay not
2063 * to extract them, otherwise, issue a single warning. */
2064 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
2066 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2067 "Cannot restore extended attributes on this system");
2068 return (ARCHIVE_WARN);
2070 /* Warning was already emitted; suppress further warnings. */
2071 return (ARCHIVE_OK);
2077 * Trivial implementations of gid/uid lookup functions.
2078 * These are normally overridden by the client, but these stub
2079 * versions ensure that we always have something that works.
2082 trivial_lookup_gid(void *private_data, const char *gname, gid_t gid)
2084 (void)private_data; /* UNUSED */
2085 (void)gname; /* UNUSED */
2090 trivial_lookup_uid(void *private_data, const char *uname, uid_t uid)
2092 (void)private_data; /* UNUSED */
2093 (void)uname; /* UNUSED */
2098 * Test if file on disk is older than entry.
2101 older(struct stat *st, struct archive_entry *entry)
2103 /* First, test the seconds and return if we have a definite answer. */
2104 /* Definitely older. */
2105 if (st->st_mtime < archive_entry_mtime(entry))
2107 /* Definitely younger. */
2108 if (st->st_mtime > archive_entry_mtime(entry))
2110 /* If this platform supports fractional seconds, try those. */
2111 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
2112 /* Definitely older. */
2113 if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
2115 /* Definitely younger. */
2116 if (st->st_mtimespec.tv_nsec > archive_entry_mtime_nsec(entry))
2118 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
2119 /* Definitely older. */
2120 if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
2122 /* Definitely older. */
2123 if (st->st_mtim.tv_nsec > archive_entry_mtime_nsec(entry))
2126 /* This system doesn't have high-res timestamps. */
2128 /* Same age, so not older. */