Add our READMEs.
[dragonfly/vkernel-mp.git] / contrib / libarchive-2.1 / libarchive / archive_write_disk.c
blob052cd25e6b54d0e86153201273fc1cf9664dbdbe
1 /*-
2 * Copyright (c) 2003-2007 Tim Kientzle
3 * All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
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: src/lib/libarchive/archive_write_disk.c,v 1.10 2007/04/15 04:43:12 kientzle Exp $");
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33 #ifdef HAVE_SYS_ACL_H
34 #include <sys/acl.h>
35 #endif
36 #ifdef HAVE_ATTR_XATTR_H
37 #include <attr/xattr.h>
38 #endif
39 #ifdef HAVE_SYS_IOCTL_H
40 #include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_SYS_STAT_H
43 #include <sys/stat.h>
44 #endif
45 #ifdef HAVE_SYS_TIME_H
46 #include <sys/time.h>
47 #endif
49 #ifdef HAVE_EXT2FS_EXT2_FS_H
50 #include <ext2fs/ext2_fs.h> /* for Linux file flags */
51 #endif
52 #ifdef HAVE_ERRNO_H
53 #include <errno.h>
54 #endif
55 #ifdef HAVE_FCNTL_H
56 #include <fcntl.h>
57 #endif
58 #ifdef HAVE_GRP_H
59 #include <grp.h>
60 #endif
61 #ifdef HAVE_LINUX_FS_H
62 #include <linux/fs.h> /* for Linux file flags */
63 #endif
64 #ifdef HAVE_LINUX_EXT2_FS_H
65 #include <linux/ext2_fs.h> /* for Linux file flags */
66 #endif
67 #ifdef HAVE_LIMITS_H
68 #include <limits.h>
69 #endif
70 #ifdef HAVE_PWD_H
71 #include <pwd.h>
72 #endif
73 #include <stdio.h>
74 #ifdef HAVE_STDLIB_H
75 #include <stdlib.h>
76 #endif
77 #ifdef HAVE_STRING_H
78 #include <string.h>
79 #endif
80 #ifdef HAVE_UNISTD_H
81 #include <unistd.h>
82 #endif
83 #ifdef HAVE_UTIME_H
84 #include <utime.h>
85 #endif
87 #include "archive.h"
88 #include "archive_string.h"
89 #include "archive_entry.h"
90 #include "archive_private.h"
92 struct fixup_entry {
93 struct fixup_entry *next;
94 mode_t mode;
95 int64_t mtime;
96 int64_t atime;
97 unsigned long mtime_nanos;
98 unsigned long atime_nanos;
99 unsigned long fflags_set;
100 int fixup; /* bitmask of what needs fixing */
101 char *name;
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;
133 mode_t user_umask;
134 struct fixup_entry *fixup_list;
135 struct fixup_entry *current_fixup;
136 uid_t user_uid;
137 dev_t skip_file_dev;
138 ino_t skip_file_ino;
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,
155 * pst is null.
157 struct stat st;
158 struct stat *pst;
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. */
165 int todo;
166 /* Tasks deferred until end-of-archive. */
167 int deferred;
168 /* Options requested by the client. */
169 int flags;
170 /* Handle for the file we're restoring. */
171 int fd;
172 /* Current offset for writing data to the file. */
173 off_t offset;
174 /* Dir we were in before this restore; only for deep paths. */
175 int restore_pwd;
176 /* Mode we should use for this entry; affected by _PERM and umask. */
177 mode_t mode;
178 /* UID/GID to use in restoring this entry. */
179 uid_t uid;
180 gid_t gid;
184 * Default mode for dirs created automatically (will be modified by umask).
185 * Note that POSIX specifies 0777 for implicity-created dirs, "modified
186 * by the process' file creation mask."
188 #define DEFAULT_DIR_MODE 0777
190 * Dir modes are restored in two steps: During the extraction, the permissions
191 * in the archive are modified to match the following limits. During
192 * the post-extract fixup pass, the permissions from the archive are
193 * applied.
195 #define MINIMUM_DIR_MODE 0700
196 #define MAXIMUM_DIR_MODE 0775
198 static int check_symlinks(struct archive_write_disk *);
199 static int create_filesystem_object(struct archive_write_disk *);
200 static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname);
201 #ifdef HAVE_FCHDIR
202 static void edit_deep_directories(struct archive_write_disk *ad);
203 #endif
204 static int cleanup_pathname(struct archive_write_disk *);
205 static int create_dir(struct archive_write_disk *, char *);
206 static int create_parent_dir(struct archive_write_disk *, char *);
207 static int restore_entry(struct archive_write_disk *);
208 #ifdef HAVE_POSIX_ACL
209 static int set_acl(struct archive_write_disk *, int fd, struct archive_entry *,
210 acl_type_t, int archive_entry_acl_type, const char *tn);
211 #endif
212 static int set_acls(struct archive_write_disk *);
213 static int set_xattrs(struct archive_write_disk *);
214 static int set_fflags(struct archive_write_disk *);
215 static int set_fflags_platform(struct archive_write_disk *, int fd,
216 const char *name, mode_t mode,
217 unsigned long fflags_set, unsigned long fflags_clear);
218 static int set_ownership(struct archive_write_disk *);
219 static int set_mode(struct archive_write_disk *, int mode);
220 static int set_time(struct archive_write_disk *);
221 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
222 static gid_t trivial_lookup_gid(void *, const char *, gid_t);
223 static uid_t trivial_lookup_uid(void *, const char *, uid_t);
226 static struct archive_vtable *archive_write_disk_vtable(void);
228 static int _archive_write_close(struct archive *);
229 static int _archive_write_finish(struct archive *);
230 static int _archive_write_header(struct archive *, struct archive_entry *);
231 static int _archive_write_finish_entry(struct archive *);
232 static ssize_t _archive_write_data(struct archive *, const void *, size_t);
233 static ssize_t _archive_write_data_block(struct archive *, const void *, size_t, off_t);
235 static struct archive_vtable *
236 archive_write_disk_vtable(void)
238 static struct archive_vtable av;
239 static int inited = 0;
241 if (!inited) {
242 av.archive_write_close = _archive_write_close;
243 av.archive_write_finish = _archive_write_finish;
244 av.archive_write_header = _archive_write_header;
245 av.archive_write_finish_entry = _archive_write_finish_entry;
246 av.archive_write_data = _archive_write_data;
247 av.archive_write_data_block = _archive_write_data_block;
249 return (&av);
254 archive_write_disk_set_options(struct archive *_a, int flags)
256 struct archive_write_disk *a = (struct archive_write_disk *)_a;
258 a->flags = flags;
259 return (ARCHIVE_OK);
264 * Extract this entry to disk.
266 * TODO: Validate hardlinks. According to the standards, we're
267 * supposed to check each extracted hardlink and squawk if it refers
268 * to a file that we didn't restore. I'm not entirely convinced this
269 * is a good idea, but more importantly: Is there any way to validate
270 * hardlinks without keeping a complete list of filenames from the
271 * entire archive?? Ugh.
274 static int
275 _archive_write_header(struct archive *_a, struct archive_entry *entry)
277 struct archive_write_disk *a = (struct archive_write_disk *)_a;
278 struct fixup_entry *fe;
279 int ret, r;
281 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
282 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
283 "archive_write_disk_header");
284 archive_clear_error(&a->archive);
285 if (a->archive.state & ARCHIVE_STATE_DATA) {
286 r = _archive_write_finish_entry(&a->archive);
287 if (r != ARCHIVE_OK)
288 return (r);
291 /* Set up for this particular entry. */
292 a->pst = NULL;
293 a->current_fixup = NULL;
294 a->deferred = 0;
295 a->entry = entry;
296 a->fd = -1;
297 a->offset = 0;
298 a->uid = a->user_uid;
299 a->mode = archive_entry_mode(a->entry);
300 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
301 a->name = a->_name_data.s;
302 archive_clear_error(&a->archive);
305 * Clean up the requested path. This is necessary for correct
306 * dir restores; the dir restore logic otherwise gets messed
307 * up by nonsense like "dir/.".
309 ret = cleanup_pathname(a);
310 if (ret != ARCHIVE_OK)
311 return (ret);
314 * Set the umask to zero so we get predictable mode settings.
315 * This gets done on every call to _write_header in case the
316 * user edits their umask during the extraction for some
317 * reason. This will be reset before we return. Note that we
318 * don't need to do this in _finish_entry, as the chmod(), etc,
319 * system calls don't obey umask.
321 a->user_umask = umask(0);
322 /* From here on, early exit requires "goto done" to clean up. */
324 /* Figure out what we need to do for this entry. */
325 a->todo = TODO_MODE_BASE;
326 if (a->flags & ARCHIVE_EXTRACT_PERM) {
327 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
329 * SGID requires an extra "check" step because we
330 * cannot easily predict the GID that the system will
331 * assign. (Different systems assign GIDs to files
332 * based on a variety of criteria, including process
333 * credentials and the gid of the enclosing
334 * directory.) We can only restore the SGID bit if
335 * the file has the right GID, and we only know the
336 * GID if we either set it (see set_ownership) or if
337 * we've actually called stat() on the file after it
338 * was restored. Since there are several places at
339 * which we might verify the GID, we need a TODO bit
340 * to keep track.
342 if (a->mode & S_ISGID)
343 a->todo |= TODO_SGID | TODO_SGID_CHECK;
345 * Verifying the SUID is simpler, but can still be
346 * done in multiple ways, hence the separate "check" bit.
348 if (a->mode & S_ISUID)
349 a->todo |= TODO_SUID | TODO_SUID_CHECK;
350 } else {
352 * User didn't request full permissions, so don't
353 * restore SUID, SGID bits and obey umask.
355 a->mode &= ~S_ISUID;
356 a->mode &= ~S_ISGID;
357 a->mode &= ~S_ISVTX;
358 a->mode &= ~a->user_umask;
360 if (a->flags & ARCHIVE_EXTRACT_OWNER)
361 a->todo |= TODO_OWNER;
362 if (a->flags & ARCHIVE_EXTRACT_TIME)
363 a->todo |= TODO_TIMES;
364 if (a->flags & ARCHIVE_EXTRACT_ACL)
365 a->todo |= TODO_ACLS;
366 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
367 a->todo |= TODO_FFLAGS;
368 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
369 ret = check_symlinks(a);
370 if (ret != ARCHIVE_OK)
371 goto done;
373 #ifdef HAVE_FCHDIR
374 /* If path exceeds PATH_MAX, shorten the path. */
375 edit_deep_directories(a);
376 #endif
378 ret = restore_entry(a);
380 #ifdef HAVE_FCHDIR
381 /* If we changed directory above, restore it here. */
382 if (a->restore_pwd >= 0) {
383 fchdir(a->restore_pwd);
384 close(a->restore_pwd);
385 a->restore_pwd = -1;
387 #endif
390 * Fixup uses the unedited pathname from archive_entry_pathname(),
391 * because it is relative to the base dir and the edited path
392 * might be relative to some intermediate dir as a result of the
393 * deep restore logic.
395 if (a->deferred & TODO_MODE) {
396 fe = current_fixup(a, archive_entry_pathname(entry));
397 fe->fixup |= TODO_MODE_BASE;
398 fe->mode = a->mode;
401 if (a->deferred & TODO_TIMES) {
402 fe = current_fixup(a, archive_entry_pathname(entry));
403 fe->fixup |= TODO_TIMES;
404 fe->mtime = archive_entry_mtime(entry);
405 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
406 fe->atime = archive_entry_atime(entry);
407 fe->atime_nanos = archive_entry_atime_nsec(entry);
410 if (a->deferred & TODO_FFLAGS) {
411 fe = current_fixup(a, archive_entry_pathname(entry));
412 fe->fixup |= TODO_FFLAGS;
413 /* TODO: Complete this.. defer fflags from below. */
416 /* We've created the object and are ready to pour data into it. */
417 if (ret == ARCHIVE_OK)
418 a->archive.state = ARCHIVE_STATE_DATA;
419 done:
420 /* Restore the user's umask before returning. */
421 umask(a->user_umask);
423 return (ret);
427 archive_write_disk_set_skip_file(struct archive *_a, dev_t d, ino_t i)
429 struct archive_write_disk *a = (struct archive_write_disk *)_a;
430 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
431 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
432 a->skip_file_dev = d;
433 a->skip_file_ino = i;
434 return (ARCHIVE_OK);
437 static ssize_t
438 _archive_write_data_block(struct archive *_a,
439 const void *buff, size_t size, off_t offset)
441 struct archive_write_disk *a = (struct archive_write_disk *)_a;
442 ssize_t bytes_written = 0;
444 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
445 ARCHIVE_STATE_DATA, "archive_write_disk_block");
446 if (a->fd < 0)
447 return (ARCHIVE_OK);
448 archive_clear_error(&a->archive);
450 /* Seek if necessary to the specified offset. */
451 if (offset != a->offset) {
452 if (lseek(a->fd, offset, SEEK_SET) < 0) {
453 archive_set_error(&a->archive, errno, "Seek failed");
454 return (ARCHIVE_WARN);
456 a->offset = offset;
459 /* Write the data. */
460 while (size > 0) {
461 bytes_written = write(a->fd, buff, size);
462 if (bytes_written < 0) {
463 archive_set_error(&a->archive, errno, "Write failed");
464 return (ARCHIVE_WARN);
466 size -= bytes_written;
467 a->offset += bytes_written;
469 return (ARCHIVE_OK);
472 static ssize_t
473 _archive_write_data(struct archive *_a, const void *buff, size_t size)
475 struct archive_write_disk *a = (struct archive_write_disk *)_a;
476 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
477 ARCHIVE_STATE_DATA, "archive_write_data");
478 if (a->fd < 0)
479 return (ARCHIVE_OK);
481 return (_archive_write_data_block(_a, buff, size, a->offset));
484 static int
485 _archive_write_finish_entry(struct archive *_a)
487 struct archive_write_disk *a = (struct archive_write_disk *)_a;
488 int ret = ARCHIVE_OK;
490 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
491 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
492 "archive_write_finish_entry");
493 if (a->archive.state & ARCHIVE_STATE_HEADER)
494 return (ARCHIVE_OK);
495 archive_clear_error(&a->archive);
497 /* Restore metadata. */
500 * Look up the "real" UID only if we're going to need it. We
501 * need this for TODO_SGID because chown() requires both.
503 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
504 a->uid = a->lookup_uid(a->lookup_uid_data,
505 archive_entry_uname(a->entry),
506 archive_entry_uid(a->entry));
508 /* Look up the "real" GID only if we're going to need it. */
509 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
510 a->gid = a->lookup_gid(a->lookup_gid_data,
511 archive_entry_gname(a->entry),
512 archive_entry_gid(a->entry));
515 * If restoring ownership, do it before trying to restore suid/sgid
516 * bits. If we set the owner, we know what it is and can skip
517 * a stat() call to examine the ownership of the file on disk.
519 if (a->todo & TODO_OWNER)
520 ret = set_ownership(a);
521 if (a->todo & TODO_MODE) {
522 int r2 = set_mode(a, a->mode);
523 if (r2 < ret) ret = r2;
525 if (a->todo & TODO_TIMES) {
526 int r2 = set_time(a);
527 if (r2 < ret) ret = r2;
529 if (a->todo & TODO_ACLS) {
530 int r2 = set_acls(a);
531 if (r2 < ret) ret = r2;
533 if (a->todo & TODO_XATTR) {
534 int r2 = set_xattrs(a);
535 if (r2 < ret) ret = r2;
537 if (a->todo & TODO_FFLAGS) {
538 int r2 = set_fflags(a);
539 if (r2 < ret) ret = r2;
542 /* If there's an fd, we can close it now. */
543 if (a->fd >= 0) {
544 close(a->fd);
545 a->fd = -1;
547 a->archive.state = ARCHIVE_STATE_HEADER;
548 return (ret);
552 archive_write_disk_set_group_lookup(struct archive *_a,
553 void *private_data,
554 gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid),
555 void (*cleanup_gid)(void *private))
557 struct archive_write_disk *a = (struct archive_write_disk *)_a;
558 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
559 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
561 a->lookup_gid = lookup_gid;
562 a->cleanup_gid = cleanup_gid;
563 a->lookup_gid_data = private_data;
564 return (ARCHIVE_OK);
568 archive_write_disk_set_user_lookup(struct archive *_a,
569 void *private_data,
570 uid_t (*lookup_uid)(void *private, const char *uname, uid_t uid),
571 void (*cleanup_uid)(void *private))
573 struct archive_write_disk *a = (struct archive_write_disk *)_a;
574 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
575 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
577 a->lookup_uid = lookup_uid;
578 a->cleanup_uid = cleanup_uid;
579 a->lookup_uid_data = private_data;
580 return (ARCHIVE_OK);
585 * Create a new archive_write_disk object and initialize it with global state.
587 struct archive *
588 archive_write_disk_new(void)
590 struct archive_write_disk *a;
592 a = (struct archive_write_disk *)malloc(sizeof(*a));
593 if (a == NULL)
594 return (NULL);
595 memset(a, 0, sizeof(*a));
596 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
597 /* We're ready to write a header immediately. */
598 a->archive.state = ARCHIVE_STATE_HEADER;
599 a->archive.vtable = archive_write_disk_vtable();
600 a->lookup_uid = trivial_lookup_uid;
601 a->lookup_gid = trivial_lookup_gid;
602 a->user_uid = geteuid();
603 archive_string_ensure(&a->path_safe, 64);
604 return (&a->archive);
609 * If pathname is longer than PATH_MAX, chdir to a suitable
610 * intermediate dir and edit the path down to a shorter suffix. Note
611 * that this routine never returns an error; if the chdir() attempt
612 * fails for any reason, we just go ahead with the long pathname. The
613 * object creation is likely to fail, but any error will get handled
614 * at that time.
616 #ifdef HAVE_FCHDIR
617 static void
618 edit_deep_directories(struct archive_write_disk *a)
620 int ret;
621 char *tail = a->name;
623 a->restore_pwd = -1;
625 /* If path is short, avoid the open() below. */
626 if (strlen(tail) <= PATH_MAX)
627 return;
629 /* Try to record our starting dir. */
630 a->restore_pwd = open(".", O_RDONLY);
631 if (a->restore_pwd < 0)
632 return;
634 /* As long as the path is too long... */
635 while (strlen(tail) > PATH_MAX) {
636 /* Locate a dir prefix shorter than PATH_MAX. */
637 tail += PATH_MAX - 8;
638 while (tail > a->name && *tail != '/')
639 tail--;
640 /* Exit if we find a too-long path component. */
641 if (tail <= a->name)
642 return;
643 /* Create the intermediate dir and chdir to it. */
644 *tail = '\0'; /* Terminate dir portion */
645 ret = create_dir(a, a->name);
646 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
647 ret = ARCHIVE_WARN;
648 *tail = '/'; /* Restore the / we removed. */
649 if (ret != ARCHIVE_OK)
650 return;
651 tail++;
652 /* The chdir() succeeded; we've now shortened the path. */
653 a->name = tail;
655 return;
657 #endif
660 * The main restore function.
662 static int
663 restore_entry(struct archive_write_disk *a)
665 int ret = ARCHIVE_OK, en;
667 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
668 if (unlink(a->name) == 0) {
669 /* We removed it, we're done. */
670 } else if (errno == ENOENT) {
671 /* File didn't exist, that's just as good. */
672 } else if (rmdir(a->name) == 0) {
673 /* It was a dir, but now it's gone. */
674 } else {
675 /* We tried, but couldn't get rid of it. */
676 archive_set_error(&a->archive, errno,
677 "Could not unlink");
678 return(ARCHIVE_WARN);
682 /* Try creating it first; if this fails, we'll try to recover. */
683 en = create_filesystem_object(a);
685 if (en == ENOTDIR || en == ENOENT) {
686 /* If the parent dir doesn't exist, try creating it. */
687 create_parent_dir(a, a->name);
688 /* Now try to create the object again. */
689 en = create_filesystem_object(a);
692 if ((en == EISDIR || en == EEXIST)
693 && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
694 /* If we're not overwriting, we're done. */
695 archive_set_error(&a->archive, en, "Already exists");
696 return (ARCHIVE_WARN);
700 * Some platforms return EISDIR if you call
701 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
702 * return EEXIST. POSIX is ambiguous, requiring EISDIR
703 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
704 * on an existing item.
706 if (en == EISDIR) {
707 /* A dir is in the way of a non-dir, rmdir it. */
708 if (rmdir(a->name) != 0) {
709 archive_set_error(&a->archive, errno,
710 "Can't remove already-existing dir");
711 return (ARCHIVE_WARN);
713 /* Try again. */
714 en = create_filesystem_object(a);
715 } else if (en == EEXIST) {
717 * We know something is in the way, but we don't know what;
718 * we need to find out before we go any further.
720 if (lstat(a->name, &a->st) != 0) {
721 archive_set_error(&a->archive, errno,
722 "Can't stat existing object");
723 return (ARCHIVE_WARN);
726 /* TODO: if it's a symlink... */
728 /* If it's our archive, we're done. */
729 if (a->skip_file_dev > 0 &&
730 a->skip_file_ino > 0 &&
731 a->st.st_dev == a->skip_file_dev &&
732 a->st.st_ino == a->skip_file_ino) {
733 archive_set_error(&a->archive, 0, "Refusing to overwrite archive");
734 return (ARCHIVE_FAILED);
737 if (!S_ISDIR(a->st.st_mode)) {
738 /* A non-dir is in the way, unlink it. */
739 if (unlink(a->name) != 0) {
740 archive_set_error(&a->archive, errno,
741 "Can't unlink already-existing object");
742 return (ARCHIVE_WARN);
744 /* Try again. */
745 en = create_filesystem_object(a);
746 } else if (!S_ISDIR(a->mode)) {
747 /* A dir is in the way of a non-dir, rmdir it. */
748 if (rmdir(a->name) != 0) {
749 archive_set_error(&a->archive, errno,
750 "Can't remove already-existing dir");
751 return (ARCHIVE_WARN);
753 /* Try again. */
754 en = create_filesystem_object(a);
755 } else {
757 * There's a dir in the way of a dir. Don't
758 * waste time with rmdir()/mkdir(), just fix
759 * up the permissions on the existing dir.
760 * Note that we don't change perms on existing
761 * dirs unless _EXTRACT_PERM is specified.
763 if ((a->mode != a->st.st_mode)
764 && (a->todo & TODO_MODE_FORCE))
765 a->deferred |= (a->todo & TODO_MODE);
766 /* Ownership doesn't need deferred fixup. */
767 en = 0; /* Forget the EEXIST. */
771 if (en) {
772 /* Everything failed; give up here. */
773 archive_set_error(&a->archive, en, "Can't create '%s'", a->name);
774 return (ARCHIVE_WARN);
777 a->pst = NULL; /* Cached stat data no longer valid. */
778 return (ret);
782 * Returns 0 if creation succeeds, or else returns errno value from
783 * the failed system call. Note: This function should only ever perform
784 * a single system call.
787 create_filesystem_object(struct archive_write_disk *a)
789 /* Create the entry. */
790 const char *linkname;
791 mode_t final_mode, mode;
792 int r;
794 /* We identify hard/symlinks according to the link names. */
795 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
796 linkname = archive_entry_hardlink(a->entry);
797 if (linkname != NULL)
798 return link(linkname, a->name) ? errno : 0;
799 linkname = archive_entry_symlink(a->entry);
800 if (linkname != NULL)
801 return symlink(linkname, a->name) ? errno : 0;
804 * The remaining system calls all set permissions, so let's
805 * try to take advantage of that to avoid an extra chmod()
806 * call. (Recall that umask is set to zero right now!)
809 /* Mode we want for the final restored object (w/o file type bits). */
810 final_mode = a->mode & 07777;
812 * The mode that will actually be restored in this step. Note
813 * that SUID, SGID, etc, require additional work to ensure
814 * security, so we never restore them at this point.
816 mode = final_mode & 0777;
818 switch (a->mode & S_IFMT) {
819 default:
820 /* POSIX requires that we fall through here. */
821 /* FALLTHROUGH */
822 case S_IFREG:
823 a->fd = open(a->name,
824 O_WRONLY | O_CREAT | O_EXCL, mode);
825 r = (a->fd < 0);
826 break;
827 case S_IFCHR:
828 r = mknod(a->name, mode | S_IFCHR,
829 archive_entry_rdev(a->entry));
830 break;
831 case S_IFBLK:
832 r = mknod(a->name, mode | S_IFBLK,
833 archive_entry_rdev(a->entry));
834 break;
835 case S_IFDIR:
836 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
837 r = mkdir(a->name, mode);
838 if (r == 0) {
839 /* Defer setting dir times. */
840 a->deferred |= (a->todo & TODO_TIMES);
841 a->todo &= ~TODO_TIMES;
842 /* Never use an immediate chmod(). */
843 if (mode != final_mode)
844 a->deferred |= (a->todo & TODO_MODE);
845 a->todo &= ~TODO_MODE;
847 break;
848 case S_IFIFO:
849 r = mkfifo(a->name, mode);
850 break;
853 /* All the system calls above set errno on failure. */
854 if (r)
855 return (errno);
857 /* If we managed to set the final mode, we've avoided a chmod(). */
858 if (mode == final_mode)
859 a->todo &= ~TODO_MODE;
860 return (0);
864 * Cleanup function for archive_extract. Mostly, this involves processing
865 * the fixup list, which is used to address a number of problems:
866 * * Dir permissions might prevent us from restoring a file in that
867 * dir, so we restore the dir with minimum 0700 permissions first,
868 * then correct the mode at the end.
869 * * Similarly, the act of restoring a file touches the directory
870 * and changes the timestamp on the dir, so we have to touch-up dir
871 * timestamps at the end as well.
872 * * Some file flags can interfere with the restore by, for example,
873 * preventing the creation of hardlinks to those files.
875 * Note that tar/cpio do not require that archives be in a particular
876 * order; there is no way to know when the last file has been restored
877 * within a directory, so there's no way to optimize the memory usage
878 * here by fixing up the directory any earlier than the
879 * end-of-archive.
881 * XXX TODO: Directory ACLs should be restored here, for the same
882 * reason we set directory perms here. XXX
884 static int
885 _archive_write_close(struct archive *_a)
887 struct archive_write_disk *a = (struct archive_write_disk *)_a;
888 struct fixup_entry *next, *p;
889 int ret;
891 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
892 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
893 "archive_write_disk_close");
894 ret = _archive_write_finish_entry(&a->archive);
896 /* Sort dir list so directories are fixed up in depth-first order. */
897 p = sort_dir_list(a->fixup_list);
899 while (p != NULL) {
900 a->pst = NULL; /* Mark stat cache as out-of-date. */
901 if (p->fixup & TODO_TIMES) {
902 #ifdef HAVE_UTIMES
903 /* {f,l,}utimes() are preferred, when available. */
904 struct timeval times[2];
905 times[1].tv_sec = p->mtime;
906 times[1].tv_usec = p->mtime_nanos / 1000;
907 times[0].tv_sec = p->atime;
908 times[0].tv_usec = p->atime_nanos / 1000;
909 #ifdef HAVE_LUTIMES
910 lutimes(p->name, times);
911 #else
912 utimes(p->name, times);
913 #endif
914 #else
915 /* utime() is more portable, but less precise. */
916 struct utimbuf times;
917 times.modtime = p->mtime;
918 times.actime = p->atime;
920 utime(p->name, &times);
921 #endif
923 if (p->fixup & TODO_MODE_BASE)
924 chmod(p->name, p->mode);
926 if (p->fixup & TODO_FFLAGS)
927 set_fflags_platform(a, -1, p->name,
928 p->mode, p->fflags_set, 0);
930 next = p->next;
931 free(p->name);
932 free(p);
933 p = next;
935 a->fixup_list = NULL;
936 return (ret);
939 static int
940 _archive_write_finish(struct archive *_a)
942 struct archive_write_disk *a = (struct archive_write_disk *)_a;
943 int ret;
944 ret = _archive_write_close(&a->archive);
945 if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
946 (a->cleanup_gid)(a->lookup_gid_data);
947 if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
948 (a->cleanup_uid)(a->lookup_uid_data);
949 archive_string_free(&a->_name_data);
950 archive_string_free(&a->archive.error_string);
951 archive_string_free(&a->path_safe);
952 free(a);
953 return (ret);
957 * Simple O(n log n) merge sort to order the fixup list. In
958 * particular, we want to restore dir timestamps depth-first.
960 static struct fixup_entry *
961 sort_dir_list(struct fixup_entry *p)
963 struct fixup_entry *a, *b, *t;
965 if (p == NULL)
966 return (NULL);
967 /* A one-item list is already sorted. */
968 if (p->next == NULL)
969 return (p);
971 /* Step 1: split the list. */
972 t = p;
973 a = p->next->next;
974 while (a != NULL) {
975 /* Step a twice, t once. */
976 a = a->next;
977 if (a != NULL)
978 a = a->next;
979 t = t->next;
981 /* Now, t is at the mid-point, so break the list here. */
982 b = t->next;
983 t->next = NULL;
984 a = p;
986 /* Step 2: Recursively sort the two sub-lists. */
987 a = sort_dir_list(a);
988 b = sort_dir_list(b);
990 /* Step 3: Merge the returned lists. */
991 /* Pick the first element for the merged list. */
992 if (strcmp(a->name, b->name) > 0) {
993 t = p = a;
994 a = a->next;
995 } else {
996 t = p = b;
997 b = b->next;
1000 /* Always put the later element on the list first. */
1001 while (a != NULL && b != NULL) {
1002 if (strcmp(a->name, b->name) > 0) {
1003 t->next = a;
1004 a = a->next;
1005 } else {
1006 t->next = b;
1007 b = b->next;
1009 t = t->next;
1012 /* Only one list is non-empty, so just splice it on. */
1013 if (a != NULL)
1014 t->next = a;
1015 if (b != NULL)
1016 t->next = b;
1018 return (p);
1022 * Returns a new, initialized fixup entry.
1024 * TODO: Reduce the memory requirements for this list by using a tree
1025 * structure rather than a simple list of names.
1027 static struct fixup_entry *
1028 new_fixup(struct archive_write_disk *a, const char *pathname)
1030 struct fixup_entry *fe;
1032 fe = (struct fixup_entry *)malloc(sizeof(struct fixup_entry));
1033 if (fe == NULL)
1034 return (NULL);
1035 fe->next = a->fixup_list;
1036 a->fixup_list = fe;
1037 fe->fixup = 0;
1038 fe->name = strdup(pathname);
1039 return (fe);
1043 * Returns a fixup structure for the current entry.
1045 static struct fixup_entry *
1046 current_fixup(struct archive_write_disk *a, const char *pathname)
1048 if (a->current_fixup == NULL)
1049 a->current_fixup = new_fixup(a, pathname);
1050 return (a->current_fixup);
1053 /* TODO: Make this work. */
1055 * TODO: The deep-directory support bypasses this; disable deep directory
1056 * support if we're doing symlink checks.
1059 * TODO: Someday, integrate this with the deep dir support; they both
1060 * scan the path and both can be optimized by comparing against other
1061 * recent paths.
1063 static int
1064 check_symlinks(struct archive_write_disk *a)
1066 char *pn, *p;
1067 char c;
1068 int r;
1069 struct stat st;
1072 * Gaurd against symlink tricks. Reject any archive entry whose
1073 * destination would be altered by a symlink.
1075 /* Whatever we checked last time doesn't need to be re-checked. */
1076 pn = a->name;
1077 p = a->path_safe.s;
1078 while ((*pn != '\0') && (*p == *pn))
1079 ++p, ++pn;
1080 c = pn[0];
1081 /* Keep going until we've checked the entire name. */
1082 while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
1083 /* Skip the next path element. */
1084 while (*pn != '\0' && *pn != '/')
1085 ++pn;
1086 c = pn[0];
1087 pn[0] = '\0';
1088 /* Check that we haven't hit a symlink. */
1089 r = lstat(a->name, &st);
1090 if (r != 0) {
1091 /* We've hit a dir that doesn't exist; stop now. */
1092 if (errno == ENOENT)
1093 break;
1094 } else if (S_ISLNK(st.st_mode)) {
1095 if (c == '\0') {
1097 * Last element is symlink; remove it
1098 * so we can overwrite it with the
1099 * item being extracted.
1101 if (unlink(a->name)) {
1102 archive_set_error(&a->archive, errno,
1103 "Could not remove symlink %s",
1104 a->name);
1105 pn[0] = c;
1106 return (ARCHIVE_WARN);
1109 * Even if we did remove it, a warning
1110 * is in order. The warning is silly,
1111 * though, if we're just replacing one
1112 * symlink with another symlink.
1114 if (!S_ISLNK(a->mode)) {
1115 archive_set_error(&a->archive, 0,
1116 "Removing symlink %s",
1117 a->name);
1119 /* Symlink gone. No more problem! */
1120 pn[0] = c;
1121 return (0);
1122 } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
1123 /* User asked us to remove problems. */
1124 if (unlink(a->name) != 0) {
1125 archive_set_error(&a->archive, 0,
1126 "Cannot remove intervening symlink %s",
1127 a->name);
1128 pn[0] = c;
1129 return (ARCHIVE_WARN);
1131 } else {
1132 archive_set_error(&a->archive, 0,
1133 "Cannot extract through symlink %s",
1134 a->name);
1135 pn[0] = c;
1136 return (ARCHIVE_WARN);
1140 pn[0] = c;
1141 /* We've checked and/or cleaned the whole path, so remember it. */
1142 archive_strcpy(&a->path_safe, a->name);
1143 return (ARCHIVE_OK);
1147 * Canonicalize the pathname. In particular, this strips duplicate
1148 * '/' characters, '.' elements, and trailing '/'. It also raises an
1149 * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
1150 * set) any '..' in the path.
1152 static int
1153 cleanup_pathname(struct archive_write_disk *a)
1155 char *dest, *src;
1156 char separator = '\0';
1157 int lastdotdot = 0; /* True if last elt copied was '..' */
1159 dest = src = a->name;
1160 if (*src == '\0') {
1161 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1162 "Invalid empty pathname");
1163 return (ARCHIVE_WARN);
1166 /* Skip leading '/'. */
1167 if (*src == '/')
1168 separator = *src++;
1170 /* Scan the pathname one element at a time. */
1171 for (;;) {
1172 /* src points to first char after '/' */
1173 if (src[0] == '\0') {
1174 break;
1175 } else if (src[0] == '/') {
1176 /* Found '//', ignore second one. */
1177 src++;
1178 continue;
1179 } else if (src[0] == '.') {
1180 if (src[1] == '\0') {
1181 /* Ignore trailing '.' */
1182 break;
1183 } else if (src[1] == '/') {
1184 /* Skip './'. */
1185 src += 2;
1186 continue;
1187 } else if (src[1] == '.') {
1188 if (src[2] == '/' || src[2] == '\0') {
1189 /* Conditionally warn about '..' */
1190 if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
1191 archive_set_error(&a->archive,
1192 ARCHIVE_ERRNO_MISC,
1193 "Path contains '..'");
1194 return (ARCHIVE_WARN);
1196 lastdotdot = 1;
1197 } else
1198 lastdotdot = 0;
1200 * Note: Under no circumstances do we
1201 * remove '..' elements. In
1202 * particular, restoring
1203 * '/foo/../bar/' should create the
1204 * 'foo' dir as a side-effect.
1206 } else
1207 lastdotdot = 0;
1208 } else
1209 lastdotdot = 0;
1211 /* Copy current element, including leading '/'. */
1212 if (separator)
1213 *dest++ = '/';
1214 while (*src != '\0' && *src != '/') {
1215 *dest++ = *src++;
1218 if (*src == '\0')
1219 break;
1221 /* Skip '/' separator. */
1222 separator = *src++;
1225 * We've just copied zero or more path elements, not including the
1226 * final '/'.
1228 if (lastdotdot) {
1229 /* Trailing '..' is always wrong. */
1230 archive_set_error(&a->archive,
1231 ARCHIVE_ERRNO_MISC,
1232 "Path contains trailing '..'");
1233 return (ARCHIVE_WARN);
1235 if (dest == a->name) {
1237 * Nothing got copied. The path must have been something
1238 * like '.' or '/' or './' or '/././././/./'.
1240 if (separator)
1241 *dest++ = '/';
1242 else
1243 *dest++ = '.';
1245 /* Terminate the result. */
1246 *dest = '\0';
1247 return (ARCHIVE_OK);
1251 * Create the parent directory of the specified path, assuming path
1252 * is already in mutable storage.
1254 static int
1255 create_parent_dir(struct archive_write_disk *a, char *path)
1257 char *slash;
1258 int r;
1260 /* Remove tail element to obtain parent name. */
1261 slash = strrchr(path, '/');
1262 if (slash == NULL)
1263 return (ARCHIVE_OK);
1264 *slash = '\0';
1265 r = create_dir(a, path);
1266 *slash = '/';
1267 return (r);
1271 * Create the specified dir, recursing to create parents as necessary.
1273 * Returns ARCHIVE_OK if the path exists when we're done here.
1274 * Otherwise, returns ARCHIVE_WARN.
1275 * Assumes path is in mutable storage; path is unchanged on exit.
1277 static int
1278 create_dir(struct archive_write_disk *a, char *path)
1280 struct stat st;
1281 struct fixup_entry *le;
1282 char *slash, *base;
1283 mode_t mode_final, mode;
1284 int r;
1286 r = ARCHIVE_OK;
1288 /* Check for special names and just skip them. */
1289 slash = strrchr(path, '/');
1290 base = strrchr(path, '/');
1291 if (slash == NULL)
1292 base = path;
1293 else
1294 base = slash + 1;
1296 if (base[0] == '\0' ||
1297 (base[0] == '.' && base[1] == '\0') ||
1298 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
1299 /* Don't bother trying to create null path, '.', or '..'. */
1300 if (slash != NULL) {
1301 *slash = '\0';
1302 r = create_dir(a, path);
1303 *slash = '/';
1304 return (r);
1306 return (ARCHIVE_OK);
1310 * Yes, this should be stat() and not lstat(). Using lstat()
1311 * here loses the ability to extract through symlinks. Also note
1312 * that this should not use the a->st cache.
1314 if (stat(path, &st) == 0) {
1315 if (S_ISDIR(st.st_mode))
1316 return (ARCHIVE_OK);
1317 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1318 archive_set_error(&a->archive, EEXIST,
1319 "Can't create directory '%s'", path);
1320 return (ARCHIVE_WARN);
1322 if (unlink(path) != 0) {
1323 archive_set_error(&a->archive, errno,
1324 "Can't create directory '%s': "
1325 "Conflicting file cannot be removed");
1326 return (ARCHIVE_WARN);
1328 } else if (errno != ENOENT && errno != ENOTDIR) {
1329 /* Stat failed? */
1330 archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
1331 return (ARCHIVE_WARN);
1332 } else if (slash != NULL) {
1333 *slash = '\0';
1334 r = create_dir(a, path);
1335 *slash = '/';
1336 if (r != ARCHIVE_OK)
1337 return (r);
1341 * Mode we want for the final restored directory. Per POSIX,
1342 * implicitly-created dirs must be created obeying the umask.
1343 * There's no mention whether this is different for privileged
1344 * restores (which the rest of this code handles by pretending
1345 * umask=0). I've chosen here to always obey the user's umask for
1346 * implicit dirs, even if _EXTRACT_PERM was specified.
1348 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
1349 /* Mode we want on disk during the restore process. */
1350 mode = mode_final;
1351 mode |= MINIMUM_DIR_MODE;
1352 mode &= MAXIMUM_DIR_MODE;
1353 if (mkdir(path, mode) == 0) {
1354 if (mode != mode_final) {
1355 le = new_fixup(a, path);
1356 le->fixup |=TODO_MODE_BASE;
1357 le->mode = mode_final;
1359 return (ARCHIVE_OK);
1363 * Without the following check, a/b/../b/c/d fails at the
1364 * second visit to 'b', so 'd' can't be created. Note that we
1365 * don't add it to the fixup list here, as it's already been
1366 * added.
1368 if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1369 return (ARCHIVE_OK);
1371 archive_set_error(&a->archive, errno, "Failed to create dir '%s'", path);
1372 return (ARCHIVE_WARN);
1376 * Note: Although we can skip setting the user id if the desired user
1377 * id matches the current user, we cannot skip setting the group, as
1378 * many systems set the gid bit based on the containing directory. So
1379 * we have to perform a chown syscall if we want to restore the SGID
1380 * bit. (The alternative is to stat() and then possibly chown(); it's
1381 * more efficient to skip the stat() and just always chown().) Note
1382 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
1383 * allows set_mode to skip the stat() check for the GID.
1385 static int
1386 set_ownership(struct archive_write_disk *a)
1388 /* If we know we can't change it, don't bother trying. */
1389 if (a->user_uid != 0 && a->user_uid != a->uid) {
1390 archive_set_error(&a->archive, errno,
1391 "Can't set UID=%d", a->uid);
1392 return (ARCHIVE_WARN);
1395 #ifdef HAVE_FCHOWN
1396 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0)
1397 goto success;
1398 #endif
1400 #ifdef HAVE_LCHOWN
1401 if (lchown(a->name, a->uid, a->gid) == 0)
1402 goto success;
1403 #else
1404 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0)
1405 goto success;
1406 #endif
1408 archive_set_error(&a->archive, errno,
1409 "Can't set user=%d/group=%d for %s", a->uid, a->gid,
1410 a->name);
1411 return (ARCHIVE_WARN);
1412 success:
1413 a->todo &= ~TODO_OWNER;
1414 /* We know the user/group are correct now. */
1415 a->todo &= ~TODO_SGID_CHECK;
1416 a->todo &= ~TODO_SUID_CHECK;
1417 return (ARCHIVE_OK);
1420 #ifdef HAVE_UTIMES
1422 * The utimes()-family functions provide high resolution and
1423 * a way to set time on an fd or a symlink. We prefer them
1424 * when they're available.
1426 static int
1427 set_time(struct archive_write_disk *a)
1429 struct timeval times[2];
1431 times[1].tv_sec = archive_entry_mtime(a->entry);
1432 times[1].tv_usec = archive_entry_mtime_nsec(a->entry) / 1000;
1434 times[0].tv_sec = archive_entry_atime(a->entry);
1435 times[0].tv_usec = archive_entry_atime_nsec(a->entry) / 1000;
1437 #ifdef HAVE_FUTIMES
1438 if (a->fd >= 0 && futimes(a->fd, times) == 0) {
1439 return (ARCHIVE_OK);
1441 #endif
1443 #ifdef HAVE_LUTIMES
1444 if (lutimes(a->name, times) != 0)
1445 #else
1446 if (!S_ISLNK(a->mode) && utimes(a->name, times) != 0)
1447 #endif
1449 archive_set_error(&a->archive, errno, "Can't update time for %s",
1450 a->name);
1451 return (ARCHIVE_WARN);
1455 * Note: POSIX does not provide a portable way to restore ctime.
1456 * (Apart from resetting the system clock, which is distasteful.)
1457 * So, any restoration of ctime will necessarily be OS-specific.
1460 /* XXX TODO: Can FreeBSD restore ctime? XXX */
1461 return (ARCHIVE_OK);
1463 #elif defined(HAVE_UTIME)
1465 * utime() is an older, more standard interface that we'll use
1466 * if utimes() isn't available.
1468 static int
1469 set_time(struct archive_write_disk *a)
1471 struct utimbuf times;
1473 times.modtime = archive_entry_mtime(a->entry);
1474 times.actime = archive_entry_atime(a->entry);
1475 if (!S_ISLNK(a->mode) && utime(a->name, &times) != 0) {
1476 archive_set_error(&a->archive, errno,
1477 "Can't update time for %s", a->name);
1478 return (ARCHIVE_WARN);
1480 return (ARCHIVE_OK);
1482 #else
1483 /* This platform doesn't give us a way to restore the time. */
1484 static int
1485 set_time(struct archive_write_disk *a)
1487 (void)a; /* UNUSED */
1488 archive_set_error(&a->archive, errno,
1489 "Can't update time for %s", a->name);
1490 return (ARCHIVE_WARN);
1492 #endif
1495 static int
1496 set_mode(struct archive_write_disk *a, int mode)
1498 int r = ARCHIVE_OK;
1499 mode &= 07777; /* Strip off file type bits. */
1501 if (a->todo & TODO_SGID_CHECK) {
1503 * If we don't know the GID is right, we must stat()
1504 * to verify it. We can't just check the GID of this
1505 * process, since systems sometimes set GID from
1506 * the enclosing dir or based on ACLs.
1508 if (a->pst != NULL) {
1509 /* Already have stat() data available. */
1510 #ifdef HAVE_FSTAT
1511 } else if (fd >= 0 && fstat(fd, &a->st) == 0) {
1512 a->pst = &a->st;
1513 #endif
1514 } else if (stat(a->name, &a->st) == 0) {
1515 a->pst = &a->st;
1516 } else {
1517 archive_set_error(&a->archive, errno,
1518 "Couldn't stat file");
1519 return (ARCHIVE_WARN);
1521 if (a->pst->st_gid != a->gid) {
1522 mode &= ~ S_ISGID;
1523 archive_set_error(&a->archive, -1, "Can't restore SGID bit");
1524 r = ARCHIVE_WARN;
1526 /* While we're here, double-check the UID. */
1527 if (a->pst->st_uid != a->uid
1528 && (a->todo & TODO_SUID)) {
1529 mode &= ~ S_ISUID;
1530 archive_set_error(&a->archive, -1, "Can't restore SUID bit");
1531 r = ARCHIVE_WARN;
1533 a->todo &= ~TODO_SGID_CHECK;
1534 a->todo &= ~TODO_SUID_CHECK;
1535 } else if (a->todo & TODO_SUID_CHECK) {
1537 * If we don't know the UID is right, we can just check
1538 * the user, since all systems set the file UID from
1539 * the process UID.
1541 if (a->user_uid != a->uid) {
1542 mode &= ~ S_ISUID;
1543 archive_set_error(&a->archive, -1, "Can't make file SUID");
1544 r = ARCHIVE_WARN;
1546 a->todo &= ~TODO_SUID_CHECK;
1549 if (S_ISLNK(a->mode)) {
1550 #ifdef HAVE_LCHMOD
1552 * If this is a symlink, use lchmod(). If the
1553 * platform doesn't support lchmod(), just skip it. A
1554 * platform that doesn't provide a way to set
1555 * permissions on symlinks probably ignores
1556 * permissions on symlinks, so a failure here has no
1557 * impact.
1559 if (lchmod(a->name, mode) != 0) {
1560 archive_set_error(&a->archive, errno,
1561 "Can't set permissions to 0%o", (int)mode);
1562 r = ARCHIVE_WARN;
1564 #endif
1565 } else if (!S_ISDIR(a->mode)) {
1567 * If it's not a symlink and not a dir, then use
1568 * fchmod() or chmod(), depending on whether we have
1569 * an fd. Dirs get their perms set during the
1570 * post-extract fixup, which is handled elsewhere.
1572 #ifdef HAVE_FCHMOD
1573 if (a->fd >= 0) {
1574 if (fchmod(a->fd, mode) != 0) {
1575 archive_set_error(&a->archive, errno,
1576 "Can't set permissions to 0%o", (int)mode);
1577 r = ARCHIVE_WARN;
1579 } else
1580 #endif
1581 /* If this platform lacks fchmod(), then
1582 * we'll just use chmod(). */
1583 if (chmod(a->name, mode) != 0) {
1584 archive_set_error(&a->archive, errno,
1585 "Can't set permissions to 0%o", (int)mode);
1586 r = ARCHIVE_WARN;
1589 return (r);
1592 static int
1593 set_fflags(struct archive_write_disk *a)
1595 struct fixup_entry *le;
1596 unsigned long set, clear;
1597 int r;
1598 int critical_flags;
1599 mode_t mode = archive_entry_mode(a->entry);
1602 * Make 'critical_flags' hold all file flags that can't be
1603 * immediately restored. For example, on BSD systems,
1604 * SF_IMMUTABLE prevents hardlinks from being created, so
1605 * should not be set until after any hardlinks are created. To
1606 * preserve some semblance of portability, this uses #ifdef
1607 * extensively. Ugly, but it works.
1609 * Yes, Virginia, this does create a security race. It's mitigated
1610 * somewhat by the practice of creating dirs 0700 until the extract
1611 * is done, but it would be nice if we could do more than that.
1612 * People restoring critical file systems should be wary of
1613 * other programs that might try to muck with files as they're
1614 * being restored.
1616 /* Hopefully, the compiler will optimize this mess into a constant. */
1617 critical_flags = 0;
1618 #ifdef SF_IMMUTABLE
1619 critical_flags |= SF_IMMUTABLE;
1620 #endif
1621 #ifdef UF_IMMUTABLE
1622 critical_flags |= UF_IMMUTABLE;
1623 #endif
1624 #ifdef SF_APPEND
1625 critical_flags |= SF_APPEND;
1626 #endif
1627 #ifdef UF_APPEND
1628 critical_flags |= UF_APPEND;
1629 #endif
1630 #ifdef EXT2_APPEND_FL
1631 critical_flags |= EXT2_APPEND_FL;
1632 #endif
1633 #ifdef EXT2_IMMUTABLE_FL
1634 critical_flags |= EXT2_IMMUTABLE_FL;
1635 #endif
1637 if (a->todo & TODO_FFLAGS) {
1638 archive_entry_fflags(a->entry, &set, &clear);
1641 * The first test encourages the compiler to eliminate
1642 * all of this if it's not necessary.
1644 if ((critical_flags != 0) && (set & critical_flags)) {
1645 le = current_fixup(a, a->name);
1646 le->fixup |= TODO_FFLAGS;
1647 le->fflags_set = set;
1648 /* Store the mode if it's not already there. */
1649 if ((le->fixup & TODO_MODE) == 0)
1650 le->mode = mode;
1651 } else {
1652 r = set_fflags_platform(a, a->fd,
1653 a->name, mode, set, clear);
1654 if (r != ARCHIVE_OK)
1655 return (r);
1658 return (ARCHIVE_OK);
1662 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && !defined(__linux)
1663 static int
1664 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1665 mode_t mode, unsigned long set, unsigned long clear)
1667 (void)mode; /* UNUSED */
1668 if (set == 0 && clear == 0)
1669 return (ARCHIVE_OK);
1672 * XXX Is the stat here really necessary? Or can I just use
1673 * the 'set' flags directly? In particular, I'm not sure
1674 * about the correct approach if we're overwriting an existing
1675 * file that already has flags on it. XXX
1677 if (fd >= 0 && fstat(fd, &a->st) == 0)
1678 a->pst = &a->st;
1679 else if (lstat(name, &a->st) == 0)
1680 a->pst = &a->st;
1681 else {
1682 archive_set_error(&a->archive, errno,
1683 "Couldn't stat file");
1684 return (ARCHIVE_WARN);
1687 a->st.st_flags &= ~clear;
1688 a->st.st_flags |= set;
1689 #ifdef HAVE_FCHFLAGS
1690 /* If platform has fchflags() and we were given an fd, use it. */
1691 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
1692 return (ARCHIVE_OK);
1693 #endif
1695 * If we can't use the fd to set the flags, we'll use the
1696 * pathname to set flags. We prefer lchflags() but will use
1697 * chflags() if we must.
1699 #ifdef HAVE_LCHFLAGS
1700 if (lchflags(name, a->st.st_flags) == 0)
1701 return (ARCHIVE_OK);
1702 #elif defined(HAVE_CHFLAGS)
1703 if (S_ISLNK(a->st.st_mode)) {
1704 archive_set_error(&a->archive, errno,
1705 "Can't set file flags on symlink.");
1706 return (ARCHIVE_WARN);
1708 if (chflags(name, a->st.st_flags) == 0)
1709 return (ARCHIVE_OK);
1710 #endif
1711 archive_set_error(&a->archive, errno,
1712 "Failed to set file flags");
1713 return (ARCHIVE_WARN);
1716 #elif defined(__linux) && defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS)
1719 * Linux has flags too, but uses ioctl() to access them instead of
1720 * having a separate chflags() system call.
1722 static int
1723 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1724 mode_t mode, unsigned long set, unsigned long clear)
1726 int ret;
1727 int myfd = fd;
1728 unsigned long newflags, oldflags;
1729 unsigned long sf_mask = 0;
1731 if (set == 0 && clear == 0)
1732 return (ARCHIVE_OK);
1733 /* Only regular files and dirs can have flags. */
1734 if (!S_ISREG(mode) && !S_ISDIR(mode))
1735 return (ARCHIVE_OK);
1737 /* If we weren't given an fd, open it ourselves. */
1738 if (myfd < 0)
1739 myfd = open(name, O_RDONLY|O_NONBLOCK);
1740 if (myfd < 0)
1741 return (ARCHIVE_OK);
1744 * Linux has no define for the flags that are only settable by
1745 * the root user. This code may seem a little complex, but
1746 * there seem to be some Linux systems that lack these
1747 * defines. (?) The code below degrades reasonably gracefully
1748 * if sf_mask is incomplete.
1750 #ifdef EXT2_IMMUTABLE_FL
1751 sf_mask |= EXT2_IMMUTABLE_FL;
1752 #endif
1753 #ifdef EXT2_APPEND_FL
1754 sf_mask |= EXT2_APPEND_FL;
1755 #endif
1757 * XXX As above, this would be way simpler if we didn't have
1758 * to read the current flags from disk. XXX
1760 ret = ARCHIVE_OK;
1761 /* Try setting the flags as given. */
1762 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1763 newflags = (oldflags & ~clear) | set;
1764 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1765 goto cleanup;
1766 if (errno != EPERM)
1767 goto fail;
1769 /* If we couldn't set all the flags, try again with a subset. */
1770 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1771 newflags &= ~sf_mask;
1772 oldflags &= sf_mask;
1773 newflags |= oldflags;
1774 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1775 goto cleanup;
1777 /* We couldn't set the flags, so report the failure. */
1778 fail:
1779 archive_set_error(&a->archive, errno,
1780 "Failed to set file flags");
1781 ret = ARCHIVE_WARN;
1782 cleanup:
1783 if (fd < 0)
1784 close(myfd);
1785 return (ret);
1788 #else /* Not HAVE_CHFLAGS && Not __linux */
1791 * Of course, some systems have neither BSD chflags() nor Linux' flags
1792 * support through ioctl().
1794 static int
1795 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1796 mode_t mode, unsigned long set, unsigned long clear)
1798 (void)a; /* UNUSED */
1799 (void)fd; /* UNUSED */
1800 (void)name; /* UNUSED */
1801 (void)mode; /* UNUSED */
1802 (void)set; /* UNUSED */
1803 (void)clear; /* UNUSED */
1804 return (ARCHIVE_OK);
1807 #endif /* __linux */
1809 #ifndef HAVE_POSIX_ACL
1810 /* Default empty function body to satisfy mainline code. */
1811 static int
1812 set_acls(struct archive_write_disk *a)
1814 (void)a; /* UNUSED */
1815 return (ARCHIVE_OK);
1818 #else
1821 * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
1823 static int
1824 set_acls(struct archive_write_disk *a)
1826 int ret;
1828 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_ACCESS,
1829 ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
1830 if (ret != ARCHIVE_OK)
1831 return (ret);
1832 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_DEFAULT,
1833 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
1834 return (ret);
1838 static int
1839 set_acl(struct archive_write_disk *a, int fd, struct archive_entry *entry,
1840 acl_type_t acl_type, int ae_requested_type, const char *tname)
1842 acl_t acl;
1843 acl_entry_t acl_entry;
1844 acl_permset_t acl_permset;
1845 int ret;
1846 int ae_type, ae_permset, ae_tag, ae_id;
1847 uid_t ae_uid;
1848 gid_t ae_gid;
1849 const char *ae_name;
1850 int entries;
1851 const char *name;
1853 ret = ARCHIVE_OK;
1854 entries = archive_entry_acl_reset(entry, ae_requested_type);
1855 if (entries == 0)
1856 return (ARCHIVE_OK);
1857 acl = acl_init(entries);
1858 while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
1859 &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
1860 acl_create_entry(&acl, &acl_entry);
1862 switch (ae_tag) {
1863 case ARCHIVE_ENTRY_ACL_USER:
1864 acl_set_tag_type(acl_entry, ACL_USER);
1865 ae_uid = a->lookup_uid(a->lookup_uid_data,
1866 ae_name, ae_id);
1867 acl_set_qualifier(acl_entry, &ae_uid);
1868 break;
1869 case ARCHIVE_ENTRY_ACL_GROUP:
1870 acl_set_tag_type(acl_entry, ACL_GROUP);
1871 ae_gid = a->lookup_gid(a->lookup_gid_data,
1872 ae_name, ae_id);
1873 acl_set_qualifier(acl_entry, &ae_gid);
1874 break;
1875 case ARCHIVE_ENTRY_ACL_USER_OBJ:
1876 acl_set_tag_type(acl_entry, ACL_USER_OBJ);
1877 break;
1878 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
1879 acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
1880 break;
1881 case ARCHIVE_ENTRY_ACL_MASK:
1882 acl_set_tag_type(acl_entry, ACL_MASK);
1883 break;
1884 case ARCHIVE_ENTRY_ACL_OTHER:
1885 acl_set_tag_type(acl_entry, ACL_OTHER);
1886 break;
1887 default:
1888 /* XXX */
1889 break;
1892 acl_get_permset(acl_entry, &acl_permset);
1893 acl_clear_perms(acl_permset);
1894 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
1895 acl_add_perm(acl_permset, ACL_EXECUTE);
1896 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
1897 acl_add_perm(acl_permset, ACL_WRITE);
1898 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
1899 acl_add_perm(acl_permset, ACL_READ);
1902 name = archive_entry_pathname(entry);
1904 /* Try restoring the ACL through 'fd' if we can. */
1905 #if HAVE_ACL_SET_FD
1906 if (fd >= 0 && acl_type == ACL_TYPE_ACCESS && acl_set_fd(fd, acl) == 0)
1907 ret = ARCHIVE_OK;
1908 else
1909 #else
1910 #if HAVE_ACL_SET_FD_NP
1911 if (fd >= 0 && acl_set_fd_np(fd, acl, acl_type) == 0)
1912 ret = ARCHIVE_OK;
1913 else
1914 #endif
1915 #endif
1916 if (acl_set_file(name, acl_type, acl) != 0) {
1917 archive_set_error(&a->archive, errno, "Failed to set %s acl", tname);
1918 ret = ARCHIVE_WARN;
1920 acl_free(acl);
1921 return (ret);
1923 #endif
1925 #if HAVE_LSETXATTR
1927 * Restore extended attributes - Linux implementation
1929 static int
1930 set_xattrs(struct archive_write_disk *a)
1932 struct archive_entry *entry = a->entry;
1933 static int warning_done = 0;
1934 int ret = ARCHIVE_OK;
1935 int i = archive_entry_xattr_reset(entry);
1937 while (i--) {
1938 const char *name;
1939 const void *value;
1940 size_t size;
1941 archive_entry_xattr_next(entry, &name, &value, &size);
1942 if (name != NULL &&
1943 strncmp(name, "xfsroot.", 8) != 0 &&
1944 strncmp(name, "system.", 7) != 0) {
1945 int e;
1946 #if HAVE_FSETXATTR
1947 if (a->fd >= 0)
1948 e = fsetxattr(a->fd, name, value, size, 0);
1949 else
1950 #endif
1952 e = lsetxattr(archive_entry_pathname(entry),
1953 name, value, size, 0);
1955 if (e == -1) {
1956 if (errno == ENOTSUP) {
1957 if (!warning_done) {
1958 warning_done = 1;
1959 archive_set_error(&a->archive, errno,
1960 "Cannot restore extended "
1961 "attributes on this file "
1962 "system");
1964 } else
1965 archive_set_error(&a->archive, errno,
1966 "Failed to set extended attribute");
1967 ret = ARCHIVE_WARN;
1969 } else {
1970 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1971 "Invalid extended attribute encountered");
1972 ret = ARCHIVE_WARN;
1975 return (ret);
1977 #else
1979 * Restore extended attributes - stub implementation for unsupported systems
1981 static int
1982 set_xattrs(struct archive_write_disk *a)
1984 static int warning_done = 0;
1986 /* If there aren't any extended attributes, then it's okay not
1987 * to extract them, otherwise, issue a single warning. */
1988 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
1989 warning_done = 1;
1990 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1991 "Cannot restore extended attributes on this system");
1992 return (ARCHIVE_WARN);
1994 /* Warning was already emitted; suppress further warnings. */
1995 return (ARCHIVE_OK);
1997 #endif
2001 * Trivial implementations of gid/uid lookup functions.
2002 * These are normally overridden by the client, but these stub
2003 * versions ensure that we always have something that works.
2005 static gid_t
2006 trivial_lookup_gid(void *private_data, const char *gname, gid_t gid)
2008 (void)private_data; /* UNUSED */
2009 (void)gname; /* UNUSED */
2010 return (gid);
2013 static uid_t
2014 trivial_lookup_uid(void *private_data, const char *uname, uid_t uid)
2016 (void)private_data; /* UNUSED */
2017 (void)uname; /* UNUSED */
2018 return (uid);