Import libarchive and bsdtar version 2.0.25
[dragonfly/port-amd64.git] / contrib / libarchive-2.0 / libarchive / archive_write_disk.c
blob72534f0140062111c99833449a40e76aa9db1e41
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.3 2007/03/13 06:04:24 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
84 #include "archive.h"
85 #include "archive_string.h"
86 #include "archive_entry.h"
87 #include "archive_private.h"
89 struct fixup_entry {
90 struct fixup_entry *next;
91 mode_t mode;
92 int64_t mtime;
93 int64_t atime;
94 unsigned long mtime_nanos;
95 unsigned long atime_nanos;
96 unsigned long fflags_set;
97 int fixup; /* bitmask of what needs fixing */
98 char *name;
102 * We use a bitmask to track which operations remain to be done for
103 * this file. In particular, this helps us avoid unnecessary
104 * operations when it's possible to take care of one step as a
105 * side-effect of another. For example, mkdir() can specify the mode
106 * for the newly-created object but symlink() cannot. This means we
107 * can skip chmod() if mkdir() succeeded, but we must explicitly
108 * chmod() if we're trying to create a directory that already exists
109 * (mkdir() failed) or if we're restoring a symlink. Similarly, we
110 * need to verify UID/GID before trying to restore SUID/SGID bits;
111 * that verification can occur explicitly through a stat() call or
112 * implicitly because of a successful chown() call.
114 #define TODO_MODE_BASE 0x20000000
115 #define TODO_SUID 0x10000000
116 #define TODO_SUID_CHECK 0x08000000
117 #define TODO_SGID 0x04000000
118 #define TODO_SGID_CHECK 0x02000000
119 #define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
120 #define TODO_TIMES ARCHIVE_EXTRACT_TIME
121 #define TODO_OWNER ARCHIVE_EXTRACT_OWNER
122 #define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS
123 #define TODO_ACLS ARCHIVE_EXTRACT_ACL
124 #define TODO_XATTR ARCHIVE_EXTRACT_XATTR
126 struct archive_write_disk {
127 struct archive archive;
129 mode_t user_umask;
130 struct fixup_entry *fixup_list;
131 struct fixup_entry *current_fixup;
132 uid_t user_uid;
133 dev_t skip_file_dev;
134 ino_t skip_file_ino;
136 gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid);
137 void (*cleanup_gid)(void *private);
138 void *lookup_gid_data;
139 uid_t (*lookup_uid)(void *private, const char *gname, gid_t gid);
140 void (*cleanup_uid)(void *private);
141 void *lookup_uid_data;
144 * Full path of last file to satisfy symlink checks.
146 struct archive_string path_safe;
149 * Cached stat data from disk for the current entry.
150 * If this is valid, pst points to st. Otherwise,
151 * pst is null.
153 struct stat st;
154 struct stat *pst;
156 /* Information about the object being restored right now. */
157 struct archive_entry *entry; /* Entry being extracted. */
158 char *name; /* Name of entry, possibly edited. */
159 struct archive_string _name_data; /* backing store for 'name' */
160 /* Tasks remaining for this object. */
161 int todo;
162 /* Tasks deferred until end-of-archive. */
163 int deferred;
164 /* Options requested by the client. */
165 int flags;
166 /* Handle for the file we're restoring. */
167 int fd;
168 /* Current offset for writing data to the file. */
169 off_t offset;
170 /* Dir we were in before this restore; only for deep paths. */
171 int restore_pwd;
172 /* Mode we should use for this entry; affected by _PERM and umask. */
173 mode_t mode;
174 /* UID/GID to use in restoring this entry. */
175 uid_t uid;
176 gid_t gid;
180 * Default mode for dirs created automatically (will be modified by umask).
181 * Note that POSIX specifies 0777 for implicity-created dirs, "modified
182 * by the process' file creation mask."
184 #define DEFAULT_DIR_MODE 0777
186 * Dir modes are restored in two steps: During the extraction, the permissions
187 * in the archive are modified to match the following limits. During
188 * the post-extract fixup pass, the permissions from the archive are
189 * applied.
191 #define MINIMUM_DIR_MODE 0700
192 #define MAXIMUM_DIR_MODE 0775
194 static int check_symlinks(struct archive_write_disk *);
195 static int create_filesystem_object(struct archive_write_disk *);
196 static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname);
197 #ifdef HAVE_FCHDIR
198 static void edit_deep_directories(struct archive_write_disk *ad);
199 #endif
200 static int cleanup_pathname(struct archive_write_disk *);
201 static int create_dir(struct archive_write_disk *, char *);
202 static int create_parent_dir(struct archive_write_disk *, char *);
203 static int restore_entry(struct archive_write_disk *);
204 #ifdef HAVE_POSIX_ACL
205 static int set_acl(struct archive_write_disk *, int fd, struct archive_entry *,
206 acl_type_t, int archive_entry_acl_type, const char *tn);
207 #endif
208 static int set_acls(struct archive_write_disk *);
209 static int set_xattrs(struct archive_write_disk *);
210 static int set_fflags(struct archive_write_disk *);
211 static int set_fflags_platform(struct archive_write_disk *, int fd,
212 const char *name, mode_t mode,
213 unsigned long fflags_set, unsigned long fflags_clear);
214 static int set_ownership(struct archive_write_disk *);
215 static int set_mode(struct archive_write_disk *, int mode);
216 static int set_time(struct archive_write_disk *);
217 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
218 static gid_t trivial_lookup_gid(void *, const char *, gid_t);
219 static uid_t trivial_lookup_uid(void *, const char *, uid_t);
222 static struct archive_vtable *archive_write_disk_vtable(void);
224 static int _archive_write_close(struct archive *);
225 static int _archive_write_finish(struct archive *);
226 static int _archive_write_header(struct archive *, struct archive_entry *);
227 static int _archive_write_finish_entry(struct archive *);
228 static ssize_t _archive_write_data(struct archive *, const void *, size_t);
229 static ssize_t _archive_write_data_block(struct archive *, const void *, size_t, off_t);
231 static struct archive_vtable *
232 archive_write_disk_vtable(void)
234 static struct archive_vtable av;
235 static int inited = 0;
237 if (!inited) {
238 av.archive_write_close = _archive_write_close;
239 av.archive_write_finish = _archive_write_finish;
240 av.archive_write_header = _archive_write_header;
241 av.archive_write_finish_entry = _archive_write_finish_entry;
242 av.archive_write_data = _archive_write_data;
243 av.archive_write_data_block = _archive_write_data_block;
245 return (&av);
250 archive_write_disk_set_options(struct archive *_a, int flags)
252 struct archive_write_disk *a = (struct archive_write_disk *)_a;
254 a->flags = flags;
255 return (ARCHIVE_OK);
260 * Extract this entry to disk.
262 * TODO: Validate hardlinks. According to the standards, we're
263 * supposed to check each extracted hardlink and squawk if it refers
264 * to a file that we didn't restore. I'm not entirely convinced this
265 * is a good idea, but more importantly: Is there any way to validate
266 * hardlinks without keeping a complete list of filenames from the
267 * entire archive?? Ugh.
270 static int
271 _archive_write_header(struct archive *_a, struct archive_entry *entry)
273 struct archive_write_disk *a = (struct archive_write_disk *)_a;
274 struct fixup_entry *fe;
275 int ret, r;
277 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
278 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
279 "archive_write_disk_header");
280 archive_clear_error(&a->archive);
281 if (a->archive.state & ARCHIVE_STATE_DATA) {
282 r = _archive_write_finish_entry(&a->archive);
283 if (r != ARCHIVE_OK)
284 return (r);
287 /* Set up for this particular entry. */
288 a->pst = NULL;
289 a->current_fixup = NULL;
290 a->deferred = 0;
291 a->entry = entry;
292 a->fd = -1;
293 a->offset = 0;
294 a->uid = a->user_uid;
295 a->mode = archive_entry_mode(a->entry);
296 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
297 a->name = a->_name_data.s;
298 archive_clear_error(&a->archive);
301 * Clean up the requested path. This is necessary for correct
302 * dir restores; the dir restore logic otherwise gets messed
303 * up by nonsense like "dir/.".
305 ret = cleanup_pathname(a);
306 if (ret != ARCHIVE_OK)
307 return (ret);
310 * Set the umask to zero so we get predictable mode settings.
311 * This gets done on every call to _write_header in case the
312 * user edits their umask during the extraction for some
313 * reason. This will be reset before we return. Note that we
314 * don't need to do this in _finish_entry, as the chmod(), etc,
315 * system calls don't obey umask.
317 a->user_umask = umask(0);
318 /* From here on, early exit requires "goto done" to clean up. */
320 /* Figure out what we need to do for this entry. */
321 a->todo = TODO_MODE_BASE;
322 if (a->flags & ARCHIVE_EXTRACT_PERM) {
324 * SGID requires an extra "check" step because we
325 * cannot easily predict the GID that the system will
326 * assign. (Different systems assign GIDs to files
327 * based on a variety of criteria, including process
328 * credentials and the gid of the enclosing
329 * directory.) We can only restore the SGID bit if
330 * the file has the right GID, and we only know the
331 * GID if we either set it (see set_ownership) or if
332 * we've actually called stat() on the file after it
333 * was restored. Since there are several places at
334 * which we might verify the GID, we need a TODO bit
335 * to keep track.
337 if (a->mode & S_ISGID)
338 a->todo |= TODO_SGID | TODO_SGID_CHECK;
340 * Verifying the SUID is simpler, but can still be
341 * done in multiple ways, hence the separate "check" bit.
343 if (a->mode & S_ISUID)
344 a->todo |= TODO_SUID | TODO_SUID_CHECK;
345 } else {
347 * User didn't request full permissions, so don't
348 * restore SUID, SGID bits and obey umask.
350 a->mode &= ~S_ISUID;
351 a->mode &= ~S_ISGID;
352 a->mode &= ~S_ISVTX;
353 a->mode &= ~a->user_umask;
355 if (a->flags & ARCHIVE_EXTRACT_OWNER)
356 a->todo |= TODO_OWNER;
357 if (a->flags & ARCHIVE_EXTRACT_TIME)
358 a->todo |= TODO_TIMES;
359 if (a->flags & ARCHIVE_EXTRACT_ACL)
360 a->todo |= TODO_ACLS;
361 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
362 a->todo |= TODO_FFLAGS;
363 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
364 ret = check_symlinks(a);
365 if (ret != ARCHIVE_OK)
366 goto done;
368 #ifdef HAVE_FCHDIR
369 /* If path exceeds PATH_MAX, shorten the path. */
370 edit_deep_directories(a);
371 #endif
373 ret = restore_entry(a);
375 #ifdef HAVE_FCHDIR
376 /* If we changed directory above, restore it here. */
377 if (a->restore_pwd >= 0) {
378 fchdir(a->restore_pwd);
379 close(a->restore_pwd);
380 a->restore_pwd = -1;
382 #endif
385 * Fixup uses the unedited pathname from archive_entry_pathname(),
386 * because it is relative to the base dir and the edited path
387 * might be relative to some intermediate dir as a result of the
388 * deep restore logic.
390 if (a->deferred & TODO_MODE) {
391 fe = current_fixup(a, archive_entry_pathname(entry));
392 fe->fixup |= TODO_MODE_BASE;
393 fe->mode = a->mode;
396 if (a->deferred & TODO_TIMES) {
397 fe = current_fixup(a, archive_entry_pathname(entry));
398 fe->fixup |= TODO_TIMES;
399 fe->mtime = archive_entry_mtime(entry);
400 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
401 fe->atime = archive_entry_atime(entry);
402 fe->atime_nanos = archive_entry_atime_nsec(entry);
405 if (a->deferred & TODO_FFLAGS) {
406 fe = current_fixup(a, archive_entry_pathname(entry));
407 fe->fixup |= TODO_FFLAGS;
408 /* TODO: Complete this.. defer fflags from below. */
411 /* We've created the object and are ready to pour data into it. */
412 if (ret == ARCHIVE_OK)
413 a->archive.state = ARCHIVE_STATE_DATA;
414 done:
415 /* Restore the user's umask before returning. */
416 umask(a->user_umask);
418 return (ret);
422 archive_write_disk_set_skip_file(struct archive *_a, dev_t d, ino_t i)
424 struct archive_write_disk *a = (struct archive_write_disk *)_a;
425 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
426 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
427 a->skip_file_dev = d;
428 a->skip_file_ino = i;
429 return (ARCHIVE_OK);
432 static ssize_t
433 _archive_write_data_block(struct archive *_a,
434 const void *buff, size_t size, off_t offset)
436 struct archive_write_disk *a = (struct archive_write_disk *)_a;
437 ssize_t bytes_written = 0;
439 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
440 ARCHIVE_STATE_DATA, "archive_write_disk_block");
441 if (a->fd < 0)
442 return (ARCHIVE_OK);
443 archive_clear_error(&a->archive);
445 /* Seek if necessary to the specified offset. */
446 if (offset != a->offset) {
447 if (lseek(a->fd, offset, SEEK_SET) < 0) {
448 archive_set_error(&a->archive, errno, "Seek failed");
449 return (ARCHIVE_WARN);
451 a->offset = offset;
454 /* Write the data. */
455 while (size > 0) {
456 bytes_written = write(a->fd, buff, size);
457 if (bytes_written < 0) {
458 archive_set_error(&a->archive, errno, "Write failed");
459 return (ARCHIVE_WARN);
461 size -= bytes_written;
462 a->offset += bytes_written;
464 return (ARCHIVE_OK);
467 static ssize_t
468 _archive_write_data(struct archive *_a, const void *buff, size_t size)
470 struct archive_write_disk *a = (struct archive_write_disk *)_a;
471 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
472 ARCHIVE_STATE_DATA, "archive_write_data");
473 if (a->fd < 0)
474 return (ARCHIVE_OK);
476 return (_archive_write_data_block(_a, buff, size, a->offset));
479 static int
480 _archive_write_finish_entry(struct archive *_a)
482 struct archive_write_disk *a = (struct archive_write_disk *)_a;
483 int ret = ARCHIVE_OK;
485 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
486 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
487 "archive_write_finish_entry");
488 if (a->archive.state & ARCHIVE_STATE_HEADER)
489 return (ARCHIVE_OK);
490 archive_clear_error(&a->archive);
492 /* Restore metadata. */
495 * Look up the "real" UID only if we're going to need it. We
496 * need this for TODO_SGID because chown() requires both.
498 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
499 a->uid = a->lookup_uid(a->lookup_uid_data,
500 archive_entry_uname(a->entry),
501 archive_entry_uid(a->entry));
503 /* Look up the "real" GID only if we're going to need it. */
504 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
505 a->gid = a->lookup_gid(a->lookup_gid_data,
506 archive_entry_gname(a->entry),
507 archive_entry_gid(a->entry));
510 * If restoring ownership, do it before trying to restore suid/sgid
511 * bits. If we set the owner, we know what it is and can skip
512 * a stat() call to examine the ownership of the file on disk.
514 if (a->todo & TODO_OWNER)
515 ret = set_ownership(a);
516 if (a->todo & TODO_MODE) {
517 int r2 = set_mode(a, a->mode);
518 if (r2 < ret) ret = r2;
520 if (a->todo & TODO_TIMES) {
521 int r2 = set_time(a);
522 if (r2 < ret) ret = r2;
524 if (a->todo & TODO_ACLS) {
525 int r2 = set_acls(a);
526 if (r2 < ret) ret = r2;
528 if (a->todo & TODO_XATTR) {
529 int r2 = set_xattrs(a);
530 if (r2 < ret) ret = r2;
532 if (a->todo & TODO_FFLAGS) {
533 int r2 = set_fflags(a);
534 if (r2 < ret) ret = r2;
537 /* If there's an fd, we can close it now. */
538 if (a->fd >= 0) {
539 close(a->fd);
540 a->fd = -1;
542 a->archive.state = ARCHIVE_STATE_HEADER;
543 return (ret);
547 archive_write_disk_set_group_lookup(struct archive *_a,
548 void *private_data,
549 gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid),
550 void (*cleanup_gid)(void *private))
552 struct archive_write_disk *a = (struct archive_write_disk *)_a;
553 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
554 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
556 a->lookup_gid = lookup_gid;
557 a->cleanup_gid = cleanup_gid;
558 a->lookup_gid_data = private_data;
559 return (ARCHIVE_OK);
563 archive_write_disk_set_user_lookup(struct archive *_a,
564 void *private_data,
565 uid_t (*lookup_uid)(void *private, const char *uname, uid_t uid),
566 void (*cleanup_uid)(void *private))
568 struct archive_write_disk *a = (struct archive_write_disk *)_a;
569 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
570 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
572 a->lookup_uid = lookup_uid;
573 a->cleanup_uid = cleanup_uid;
574 a->lookup_uid_data = private_data;
575 return (ARCHIVE_OK);
580 * Create a new archive_write_disk object and initialize it with global state.
582 struct archive *
583 archive_write_disk_new(void)
585 struct archive_write_disk *a;
587 a = (struct archive_write_disk *)malloc(sizeof(*a));
588 if (a == NULL)
589 return (NULL);
590 memset(a, 0, sizeof(*a));
591 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
592 /* We're ready to write a header immediately. */
593 a->archive.state = ARCHIVE_STATE_HEADER;
594 a->archive.vtable = archive_write_disk_vtable();
595 a->lookup_uid = trivial_lookup_uid;
596 a->lookup_gid = trivial_lookup_gid;
597 a->user_uid = geteuid();
598 archive_string_ensure(&a->path_safe, 64);
599 return (&a->archive);
604 * If pathname is longer than PATH_MAX, chdir to a suitable
605 * intermediate dir and edit the path down to a shorter suffix. Note
606 * that this routine never returns an error; if the chdir() attempt
607 * fails for any reason, we just go ahead with the long pathname. The
608 * object creation is likely to fail, but any error will get handled
609 * at that time.
611 #ifdef HAVE_FCHDIR
612 static void
613 edit_deep_directories(struct archive_write_disk *a)
615 int ret;
616 char *tail = a->name;
618 a->restore_pwd = -1;
620 /* If path is short, avoid the open() below. */
621 if (strlen(tail) <= PATH_MAX)
622 return;
624 /* Try to record our starting dir. */
625 a->restore_pwd = open(".", O_RDONLY);
626 if (a->restore_pwd < 0)
627 return;
629 /* As long as the path is too long... */
630 while (strlen(tail) > PATH_MAX) {
631 /* Locate a dir prefix shorter than PATH_MAX. */
632 tail += PATH_MAX - 8;
633 while (tail > a->name && *tail != '/')
634 tail--;
635 /* Exit if we find a too-long path component. */
636 if (tail <= a->name)
637 return;
638 /* Create the intermediate dir and chdir to it. */
639 *tail = '\0'; /* Terminate dir portion */
640 ret = create_dir(a, a->name);
641 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
642 ret = ARCHIVE_WARN;
643 *tail = '/'; /* Restore the / we removed. */
644 if (ret != ARCHIVE_OK)
645 return;
646 tail++;
647 /* The chdir() succeeded; we've now shortened the path. */
648 a->name = tail;
650 return;
652 #endif
655 * The main restore function.
657 static int
658 restore_entry(struct archive_write_disk *a)
660 int ret = ARCHIVE_OK, en;
662 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
663 if (unlink(a->name) == 0) {
664 /* We removed it, we're done. */
665 } else if (errno == ENOENT) {
666 /* File didn't exist, that's just as good. */
667 } else if (rmdir(a->name) == 0) {
668 /* It was a dir, but now it's gone. */
669 } else {
670 /* We tried, but couldn't get rid of it. */
671 archive_set_error(&a->archive, errno,
672 "Could not unlink");
673 return(ARCHIVE_WARN);
677 /* Try creating it first; if this fails, we'll try to recover. */
678 en = create_filesystem_object(a);
680 if (en == ENOTDIR || en == ENOENT) {
681 /* If the parent dir doesn't exist, try creating it. */
682 create_parent_dir(a, a->name);
683 /* Now try to create the object again. */
684 en = create_filesystem_object(a);
687 if (en == EEXIST) {
688 /* If we're not overwriting, we're done. */
689 if (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE) {
690 archive_set_error(&a->archive, en, "Already exists");
691 return (ARCHIVE_WARN);
694 /* Find out what's in the way before we go any further. */
695 if (lstat(a->name, &a->st) != 0) {
696 archive_set_error(&a->archive, errno,
697 "Can't stat existing object");
698 return (ARCHIVE_WARN);
701 /* TODO: if it's a symlink... */
703 /* If it's our archive, we're done. */
704 if (a->skip_file_dev > 0 &&
705 a->skip_file_ino > 0 &&
706 a->st.st_dev == a->skip_file_dev &&
707 a->st.st_ino == a->skip_file_ino) {
708 archive_set_error(&a->archive, 0, "Refusing to overwrite archive");
709 return (ARCHIVE_FAILED);
712 if (!S_ISDIR(a->st.st_mode)) {
713 /* A non-dir is in the way, unlink it. */
714 if (unlink(a->name) != 0) {
715 archive_set_error(&a->archive, errno,
716 "Can't unlink already-existing object");
717 return (ARCHIVE_WARN);
719 /* Try again. */
720 en = create_filesystem_object(a);
721 } else if (!S_ISDIR(a->mode)) {
722 /* A dir is in the way of a non-dir, rmdir it. */
723 if (rmdir(a->name) != 0) {
724 archive_set_error(&a->archive, errno,
725 "Can't remove already-existing dir");
726 return (ARCHIVE_WARN);
728 /* Try again. */
729 en = create_filesystem_object(a);
730 } else {
732 * There's a dir in the way of a dir. Don't
733 * waste time with rmdir()/mkdir(), just fix
734 * up the permissions on the existing dir.
736 if (a->mode != a->st.st_mode)
737 a->deferred |= TODO_MODE;
738 /* Ownership doesn't need deferred fixup. */
739 en = 0; /* Forget the EEXIST. */
743 if (en) {
744 /* Everything failed; give up here. */
745 archive_set_error(&a->archive, en, "Can't create '%s'", a->name);
746 return (ARCHIVE_WARN);
749 a->pst = NULL; /* Cached stat data no longer valid. */
750 return (ret);
754 * Returns 0 if creation succeeds, or else returns errno value from
755 * the failed system call. Note: This function should only ever perform
756 * a single system call.
759 create_filesystem_object(struct archive_write_disk *a)
761 /* Create the entry. */
762 const char *linkname;
763 mode_t final_mode, mode;
764 int r;
766 /* We identify hard/symlinks according to the link names. */
767 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
768 linkname = archive_entry_hardlink(a->entry);
769 if (linkname != NULL)
770 return link(linkname, a->name) ? errno : 0;
771 linkname = archive_entry_symlink(a->entry);
772 if (linkname != NULL)
773 return symlink(linkname, a->name) ? errno : 0;
776 * The remaining system calls all set permissions, so let's
777 * try to take advantage of that to avoid an extra chmod()
778 * call. (Recall that umask is set to zero right now!)
781 /* Mode we want for the final restored object (w/o file type bits). */
782 final_mode = a->mode & 07777;
784 * The mode that will actually be restored in this step. Note
785 * that SUID, SGID, etc, require additional work to ensure
786 * security, so we never restore them at this point.
788 mode = final_mode & 0777;
790 switch (a->mode & S_IFMT) {
791 default:
792 /* Fall through, as required by POSIX. */
793 case S_IFREG:
794 a->fd = open(a->name,
795 O_WRONLY | O_CREAT | O_EXCL, mode);
796 r = (a->fd < 0);
797 break;
798 case S_IFCHR:
799 r = mknod(a->name, mode | S_IFCHR,
800 archive_entry_rdev(a->entry));
801 break;
802 case S_IFBLK:
803 r = mknod(a->name, mode | S_IFBLK,
804 archive_entry_rdev(a->entry));
805 break;
806 case S_IFDIR:
807 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
808 r = mkdir(a->name, mode);
809 /* Defer setting dir times. */
810 a->deferred |= (a->todo & TODO_TIMES);
811 a->todo &= ~TODO_TIMES;
812 /* Never use an immediate chmod(). */
813 if (mode != final_mode)
814 a->deferred |= (a->todo & TODO_MODE);
815 a->todo &= ~TODO_MODE;
816 break;
817 case S_IFIFO:
818 r = mkfifo(a->name, mode);
819 break;
822 /* All the system calls above set errno on failure. */
823 if (r)
824 return (errno);
826 /* If we managed to set the final mode, we've avoided a chmod(). */
827 if (mode == final_mode)
828 a->todo &= ~TODO_MODE;
829 return (0);
833 * Cleanup function for archive_extract. Mostly, this involves processing
834 * the fixup list, which is used to address a number of problems:
835 * * Dir permissions might prevent us from restoring a file in that
836 * dir, so we restore the dir with minimum 0700 permissions first,
837 * then correct the mode at the end.
838 * * Similarly, the act of restoring a file touches the directory
839 * and changes the timestamp on the dir, so we have to touch-up dir
840 * timestamps at the end as well.
841 * * Some file flags can interfere with the restore by, for example,
842 * preventing the creation of hardlinks to those files.
844 * Note that tar/cpio do not require that archives be in a particular
845 * order; there is no way to know when the last file has been restored
846 * within a directory, so there's no way to optimize the memory usage
847 * here by fixing up the directory any earlier than the
848 * end-of-archive.
850 * XXX TODO: Directory ACLs should be restored here, for the same
851 * reason we set directory perms here. XXX
853 static int
854 _archive_write_close(struct archive *_a)
856 struct archive_write_disk *a = (struct archive_write_disk *)_a;
857 struct fixup_entry *next, *p;
858 int ret;
860 __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
861 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
862 "archive_write_disk_close");
863 ret = _archive_write_finish_entry(&a->archive);
865 /* Sort dir list so directories are fixed up in depth-first order. */
866 p = sort_dir_list(a->fixup_list);
868 while (p != NULL) {
869 a->pst = NULL; /* Mark stat cache as out-of-date. */
870 if (p->fixup & TODO_TIMES) {
871 struct timeval times[2];
872 times[1].tv_sec = p->mtime;
873 times[1].tv_usec = p->mtime_nanos / 1000;
874 times[0].tv_sec = p->atime;
875 times[0].tv_usec = p->atime_nanos / 1000;
876 #ifdef HAVE_LUTIMES
877 lutimes(p->name, times);
878 #else
879 utimes(p->name, times);
880 #endif
882 if (p->fixup & TODO_MODE_BASE)
883 chmod(p->name, p->mode);
885 if (p->fixup & TODO_FFLAGS)
886 set_fflags_platform(a, -1, p->name,
887 p->mode, p->fflags_set, 0);
889 next = p->next;
890 free(p->name);
891 free(p);
892 p = next;
894 a->fixup_list = NULL;
895 return (ret);
898 static int
899 _archive_write_finish(struct archive *_a)
901 struct archive_write_disk *a = (struct archive_write_disk *)_a;
902 int ret;
903 ret = _archive_write_close(&a->archive);
904 archive_string_free(&a->_name_data);
905 archive_string_free(&a->archive.error_string);
906 archive_string_free(&a->path_safe);
907 free(a);
908 return (ret);
912 * Simple O(n log n) merge sort to order the fixup list. In
913 * particular, we want to restore dir timestamps depth-first.
915 static struct fixup_entry *
916 sort_dir_list(struct fixup_entry *p)
918 struct fixup_entry *a, *b, *t;
920 if (p == NULL)
921 return (NULL);
922 /* A one-item list is already sorted. */
923 if (p->next == NULL)
924 return (p);
926 /* Step 1: split the list. */
927 t = p;
928 a = p->next->next;
929 while (a != NULL) {
930 /* Step a twice, t once. */
931 a = a->next;
932 if (a != NULL)
933 a = a->next;
934 t = t->next;
936 /* Now, t is at the mid-point, so break the list here. */
937 b = t->next;
938 t->next = NULL;
939 a = p;
941 /* Step 2: Recursively sort the two sub-lists. */
942 a = sort_dir_list(a);
943 b = sort_dir_list(b);
945 /* Step 3: Merge the returned lists. */
946 /* Pick the first element for the merged list. */
947 if (strcmp(a->name, b->name) > 0) {
948 t = p = a;
949 a = a->next;
950 } else {
951 t = p = b;
952 b = b->next;
955 /* Always put the later element on the list first. */
956 while (a != NULL && b != NULL) {
957 if (strcmp(a->name, b->name) > 0) {
958 t->next = a;
959 a = a->next;
960 } else {
961 t->next = b;
962 b = b->next;
964 t = t->next;
967 /* Only one list is non-empty, so just splice it on. */
968 if (a != NULL)
969 t->next = a;
970 if (b != NULL)
971 t->next = b;
973 return (p);
977 * Returns a new, initialized fixup entry.
979 * TODO: Reduce the memory requirements for this list by using a tree
980 * structure rather than a simple list of names.
982 static struct fixup_entry *
983 new_fixup(struct archive_write_disk *a, const char *pathname)
985 struct fixup_entry *fe;
987 fe = (struct fixup_entry *)malloc(sizeof(struct fixup_entry));
988 if (fe == NULL)
989 return (NULL);
990 fe->next = a->fixup_list;
991 a->fixup_list = fe;
992 fe->fixup = 0;
993 fe->name = strdup(pathname);
994 return (fe);
998 * Returns a fixup structure for the current entry.
1000 static struct fixup_entry *
1001 current_fixup(struct archive_write_disk *a, const char *pathname)
1003 if (a->current_fixup == NULL)
1004 a->current_fixup = new_fixup(a, pathname);
1005 return (a->current_fixup);
1008 /* TODO: Make this work. */
1010 * TODO: The deep-directory support bypasses this; disable deep directory
1011 * support if we're doing symlink checks.
1014 * TODO: Someday, integrate this with the deep dir support; they both
1015 * scan the path and both can be optimized by comparing against other
1016 * recent paths.
1018 static int
1019 check_symlinks(struct archive_write_disk *a)
1021 char *pn, *p;
1022 char c;
1023 int r;
1024 struct stat st;
1027 * Gaurd against symlink tricks. Reject any archive entry whose
1028 * destination would be altered by a symlink.
1030 /* Whatever we checked last time doesn't need to be re-checked. */
1031 pn = a->name;
1032 p = a->path_safe.s;
1033 while ((*pn != '\0') && (*p == *pn))
1034 ++p, ++pn;
1035 c = pn[0];
1036 /* Keep going until we've checked the entire name. */
1037 while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
1038 /* Skip the next path element. */
1039 while (*pn != '\0' && *pn != '/')
1040 ++pn;
1041 c = pn[0];
1042 pn[0] = '\0';
1043 /* Check that we haven't hit a symlink. */
1044 r = lstat(a->name, &st);
1045 if (r != 0) {
1046 /* We've hit a dir that doesn't exist; stop now. */
1047 if (errno == ENOENT)
1048 break;
1049 } else if (S_ISLNK(st.st_mode)) {
1050 if (c == '\0') {
1052 * Last element is symlink; remove it
1053 * so we can overwrite it with the
1054 * item being extracted.
1056 if (unlink(a->name)) {
1057 archive_set_error(&a->archive, errno,
1058 "Could not remove symlink %s",
1059 a->name);
1060 pn[0] = c;
1061 return (ARCHIVE_WARN);
1064 * Even if we did remove it, a warning
1065 * is in order. The warning is silly,
1066 * though, if we're just replacing one
1067 * symlink with another symlink.
1069 if (!S_ISLNK(a->mode)) {
1070 archive_set_error(&a->archive, 0,
1071 "Removing symlink %s",
1072 a->name);
1074 /* Symlink gone. No more problem! */
1075 pn[0] = c;
1076 return (0);
1077 } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
1078 /* User asked us to remove problems. */
1079 if (unlink(a->name) != 0) {
1080 archive_set_error(&a->archive, 0,
1081 "Cannot remove intervening symlink %s",
1082 a->name);
1083 pn[0] = c;
1084 return (ARCHIVE_WARN);
1086 } else {
1087 archive_set_error(&a->archive, 0,
1088 "Cannot extract through symlink %s",
1089 a->name);
1090 pn[0] = c;
1091 return (ARCHIVE_WARN);
1095 pn[0] = c;
1096 /* We've checked and/or cleaned the whole path, so remember it. */
1097 archive_strcpy(&a->path_safe, a->name);
1098 return (ARCHIVE_OK);
1102 * Canonicalize the pathname. In particular, this strips duplicate
1103 * '/' characters, '.' elements, and trailing '/'. It also raises an
1104 * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
1105 * set) any '..' in the path.
1107 static int
1108 cleanup_pathname(struct archive_write_disk *a)
1110 char *dest, *src;
1111 char separator = '\0';
1112 int lastdotdot = 0; /* True if last elt copied was '..' */
1114 dest = src = a->name;
1115 if (*src == '\0') {
1116 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1117 "Invalid empty pathname");
1118 return (ARCHIVE_WARN);
1121 /* Skip leading '/'. */
1122 if (*src == '/')
1123 separator = *src++;
1125 /* Scan the pathname one element at a time. */
1126 for (;;) {
1127 /* src points to first char after '/' */
1128 if (src[0] == '\0') {
1129 break;
1130 } else if (src[0] == '/') {
1131 /* Found '//', ignore second one. */
1132 src++;
1133 continue;
1134 } else if (src[0] == '.') {
1135 if (src[1] == '\0') {
1136 /* Ignore trailing '.' */
1137 break;
1138 } else if (src[1] == '/') {
1139 /* Skip './'. */
1140 src += 2;
1141 continue;
1142 } else if (src[1] == '.') {
1143 if (src[2] == '/' || src[2] == '\0') {
1144 /* Conditionally warn about '..' */
1145 if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
1146 archive_set_error(&a->archive,
1147 ARCHIVE_ERRNO_MISC,
1148 "Path contains '..'");
1149 return (ARCHIVE_WARN);
1151 lastdotdot = 1;
1152 } else
1153 lastdotdot = 0;
1155 * Note: Under no circumstances do we
1156 * remove '..' elements. In
1157 * particular, restoring
1158 * '/foo/../bar/' should create the
1159 * 'foo' dir as a side-effect.
1161 } else
1162 lastdotdot = 0;
1163 } else
1164 lastdotdot = 0;
1166 /* Copy current element, including leading '/'. */
1167 if (separator)
1168 *dest++ = '/';
1169 while (*src != '\0' && *src != '/') {
1170 *dest++ = *src++;
1173 if (*src == '\0')
1174 break;
1176 /* Skip '/' separator. */
1177 separator = *src++;
1180 * We've just copied zero or more path elements, not including the
1181 * final '/'.
1183 if (lastdotdot) {
1184 /* Trailing '..' is always wrong. */
1185 archive_set_error(&a->archive,
1186 ARCHIVE_ERRNO_MISC,
1187 "Path contains trailing '..'");
1188 return (ARCHIVE_WARN);
1190 if (dest == a->name) {
1192 * Nothing got copied. The path must have been something
1193 * like '.' or '/' or './' or '/././././/./'.
1195 if (separator)
1196 *dest++ = '/';
1197 else
1198 *dest++ = '.';
1200 /* Terminate the result. */
1201 *dest = '\0';
1202 return (ARCHIVE_OK);
1206 * Create the parent directory of the specified path, assuming path
1207 * is already in mutable storage.
1209 static int
1210 create_parent_dir(struct archive_write_disk *a, char *path)
1212 char *slash;
1213 int r;
1215 /* Remove tail element to obtain parent name. */
1216 slash = strrchr(path, '/');
1217 if (slash == NULL)
1218 return (ARCHIVE_OK);
1219 *slash = '\0';
1220 r = create_dir(a, path);
1221 *slash = '/';
1222 return (r);
1226 * Create the specified dir, recursing to create parents as necessary.
1228 * Returns ARCHIVE_OK if the path exists when we're done here.
1229 * Otherwise, returns ARCHIVE_WARN.
1230 * Assumes path is in mutable storage; path is unchanged on exit.
1232 static int
1233 create_dir(struct archive_write_disk *a, char *path)
1235 struct stat st;
1236 struct fixup_entry *le;
1237 char *slash, *base;
1238 mode_t mode_final, mode;
1239 int r;
1241 r = ARCHIVE_OK;
1243 /* Check for special names and just skip them. */
1244 slash = strrchr(path, '/');
1245 base = strrchr(path, '/');
1246 if (slash == NULL)
1247 base = path;
1248 else
1249 base = slash + 1;
1251 if (base[0] == '\0' ||
1252 (base[0] == '.' && base[1] == '\0') ||
1253 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
1254 /* Don't bother trying to create null path, '.', or '..'. */
1255 if (slash != NULL) {
1256 *slash = '\0';
1257 r = create_dir(a, path);
1258 *slash = '/';
1259 return (r);
1261 return (ARCHIVE_OK);
1265 * Yes, this should be stat() and not lstat(). Using lstat()
1266 * here loses the ability to extract through symlinks. Also note
1267 * that this should not use the a->st cache.
1269 if (stat(path, &st) == 0) {
1270 if (S_ISDIR(st.st_mode))
1271 return (ARCHIVE_OK);
1272 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1273 archive_set_error(&a->archive, EEXIST,
1274 "Can't create directory '%s'", path);
1275 return (ARCHIVE_WARN);
1277 if (unlink(path) != 0) {
1278 archive_set_error(&a->archive, errno,
1279 "Can't create directory '%s': "
1280 "Conflicting file cannot be removed");
1281 return (ARCHIVE_WARN);
1283 } else if (errno != ENOENT && errno != ENOTDIR) {
1284 /* Stat failed? */
1285 archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
1286 return (ARCHIVE_WARN);
1287 } else if (slash != NULL) {
1288 *slash = '\0';
1289 r = create_dir(a, path);
1290 *slash = '/';
1291 if (r != ARCHIVE_OK)
1292 return (r);
1296 * Mode we want for the final restored directory. Per POSIX,
1297 * implicitly-created dirs must be created obeying the umask.
1298 * There's no mention whether this is different for privileged
1299 * restores (which the rest of this code handles by pretending
1300 * umask=0). I've chosen here to always obey the user's umask for
1301 * implicit dirs, even if _EXTRACT_PERM was specified.
1303 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
1304 /* Mode we want on disk during the restore process. */
1305 mode = mode_final;
1306 mode |= MINIMUM_DIR_MODE;
1307 mode &= MAXIMUM_DIR_MODE;
1308 if (mkdir(path, mode) == 0) {
1309 if (mode != mode_final) {
1310 le = new_fixup(a, path);
1311 le->fixup |=TODO_MODE_BASE;
1312 le->mode = mode_final;
1314 return (ARCHIVE_OK);
1318 * Without the following check, a/b/../b/c/d fails at the
1319 * second visit to 'b', so 'd' can't be created. Note that we
1320 * don't add it to the fixup list here, as it's already been
1321 * added.
1323 if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1324 return (ARCHIVE_OK);
1326 archive_set_error(&a->archive, errno, "Failed to create dir '%s'", path);
1327 return (ARCHIVE_WARN);
1331 * Note: Although we can skip setting the user id if the desired user
1332 * id matches the current user, we cannot skip setting the group, as
1333 * many systems set the gid bit based on the containing directory. So
1334 * we have to perform a chown syscall if we want to restore the SGID
1335 * bit. (The alternative is to stat() and then possibly chown(); it's
1336 * more efficient to skip the stat() and just always chown().) Note
1337 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
1338 * allows set_mode to skip the stat() check for the GID.
1340 static int
1341 set_ownership(struct archive_write_disk *a)
1343 /* If we know we can't change it, don't bother trying. */
1344 if (a->user_uid != 0 && a->user_uid != a->uid) {
1345 archive_set_error(&a->archive, errno,
1346 "Can't set UID=%d", a->uid);
1347 return (ARCHIVE_WARN);
1350 #ifdef HAVE_FCHOWN
1351 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0)
1352 goto success;
1353 #endif
1355 #ifdef HAVE_LCHOWN
1356 if (lchown(a->name, a->uid, a->gid) == 0)
1357 goto success;
1358 #else
1359 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0)
1360 goto success;
1361 #endif
1363 archive_set_error(&a->archive, errno,
1364 "Can't set user=%d/group=%d for %s", a->uid, a->gid,
1365 a->name);
1366 return (ARCHIVE_WARN);
1367 success:
1368 a->todo &= ~TODO_OWNER;
1369 /* We know the user/group are correct now. */
1370 a->todo &= ~TODO_SGID_CHECK;
1371 a->todo &= ~TODO_SUID_CHECK;
1372 return (ARCHIVE_OK);
1375 static int
1376 set_time(struct archive_write_disk *a)
1378 const struct stat *st;
1379 struct timeval times[2];
1381 st = archive_entry_stat(a->entry);
1383 times[1].tv_sec = st->st_mtime;
1384 times[1].tv_usec = ARCHIVE_STAT_MTIME_NANOS(st) / 1000;
1386 times[0].tv_sec = st->st_atime;
1387 times[0].tv_usec = ARCHIVE_STAT_ATIME_NANOS(st) / 1000;
1389 #ifdef HAVE_FUTIMES
1390 if (a->fd >= 0 && futimes(a->fd, times) == 0) {
1391 return (ARCHIVE_OK);
1393 #endif
1395 #ifdef HAVE_LUTIMES
1396 if (lutimes(a->name, times) != 0)
1397 #else
1398 if (!S_ISLNK(a->mode) && utimes(a->name, times) != 0)
1399 #endif
1401 archive_set_error(&a->archive, errno, "Can't update time for %s",
1402 a->name);
1403 return (ARCHIVE_WARN);
1407 * Note: POSIX does not provide a portable way to restore ctime.
1408 * (Apart from resetting the system clock, which is distasteful.)
1409 * So, any restoration of ctime will necessarily be OS-specific.
1412 /* XXX TODO: Can FreeBSD restore ctime? XXX */
1413 return (ARCHIVE_OK);
1416 static int
1417 set_mode(struct archive_write_disk *a, int mode)
1419 int r = ARCHIVE_OK;
1421 if (a->todo & TODO_SGID_CHECK) {
1423 * If we don't know the GID is right, we must stat()
1424 * to verify it. We can't just check the GID of this
1425 * process, since systems sometimes set GID from
1426 * the enclosing dir or based on ACLs.
1428 if (a->pst != NULL) {
1429 /* Already have stat() data available. */
1430 #ifdef HAVE_FSTAT
1431 } else if (fd >= 0 && fstat(fd, &a->st) == 0) {
1432 a->pst = &a->st;
1433 #endif
1434 } else if (stat(a->name, &a->st) == 0) {
1435 a->pst = &a->st;
1436 } else {
1437 archive_set_error(&a->archive, errno,
1438 "Couldn't stat file");
1439 return (ARCHIVE_WARN);
1441 if (a->pst->st_gid != a->gid) {
1442 mode &= ~ S_ISGID;
1443 archive_set_error(&a->archive, -1, "Can't restore SGID bit");
1444 r = ARCHIVE_WARN;
1446 /* While we're here, double-check the UID. */
1447 if (a->pst->st_uid != a->uid
1448 && (a->todo & TODO_SUID)) {
1449 mode &= ~ S_ISUID;
1450 archive_set_error(&a->archive, -1, "Can't restore SUID bit");
1451 r = ARCHIVE_WARN;
1453 a->todo &= ~TODO_SGID_CHECK;
1454 a->todo &= ~TODO_SUID_CHECK;
1455 } else if (a->todo & TODO_SUID_CHECK) {
1457 * If we don't know the UID is right, we can just check
1458 * the user, since all systems set the file UID from
1459 * the process UID.
1461 if (a->user_uid != a->uid) {
1462 mode &= ~ S_ISUID;
1463 archive_set_error(&a->archive, -1, "Can't make file SUID");
1464 r = ARCHIVE_WARN;
1466 a->todo &= ~TODO_SUID_CHECK;
1469 if (S_ISLNK(a->mode)) {
1470 #ifdef HAVE_LCHMOD
1472 * If this is a symlink, use lchmod(). If the
1473 * platform doesn't support lchmod(), just skip it. A
1474 * platform that doesn't provide a way to set
1475 * permissions on symlinks probably ignores
1476 * permissions on symlinks, so a failure here has no
1477 * impact.
1479 if (lchmod(a->name, mode) != 0) {
1480 archive_set_error(&a->archive, errno, "Can't set permissions");
1481 r = ARCHIVE_WARN;
1483 #endif
1484 } else if (!S_ISDIR(a->mode)) {
1486 * If it's not a symlink and not a dir, then use
1487 * fchmod() or chmod(), depending on whether we have
1488 * an fd. Dirs get their perms set during the
1489 * post-extract fixup, which is handled elsewhere.
1491 #ifdef HAVE_FCHMOD
1492 if (a->fd >= 0) {
1493 if (fchmod(a->fd, mode) != 0) {
1494 archive_set_error(&a->archive, errno,
1495 "Can't set permissions");
1496 r = ARCHIVE_WARN;
1498 } else
1499 #endif
1500 /* If this platform lacks fchmod(), then
1501 * we'll just use chmod(). */
1502 if (chmod(a->name, mode) != 0) {
1503 archive_set_error(&a->archive, errno,
1504 "Can't set permissions");
1505 r = ARCHIVE_WARN;
1508 return (r);
1511 static int
1512 set_fflags(struct archive_write_disk *a)
1514 struct fixup_entry *le;
1515 long set, clear;
1516 int r;
1517 int critical_flags;
1518 mode_t mode = archive_entry_mode(a->entry);
1521 * Make 'critical_flags' hold all file flags that can't be
1522 * immediately restored. For example, on BSD systems,
1523 * SF_IMMUTABLE prevents hardlinks from being created, so
1524 * should not be set until after any hardlinks are created. To
1525 * preserve some semblance of portability, this uses #ifdef
1526 * extensively. Ugly, but it works.
1528 * Yes, Virginia, this does create a security race. It's mitigated
1529 * somewhat by the practice of creating dirs 0700 until the extract
1530 * is done, but it would be nice if we could do more than that.
1531 * People restoring critical file systems should be wary of
1532 * other programs that might try to muck with files as they're
1533 * being restored.
1535 /* Hopefully, the compiler will optimize this mess into a constant. */
1536 critical_flags = 0;
1537 #ifdef SF_IMMUTABLE
1538 critical_flags |= SF_IMMUTABLE;
1539 #endif
1540 #ifdef UF_IMMUTABLE
1541 critical_flags |= UF_IMMUTABLE;
1542 #endif
1543 #ifdef SF_APPEND
1544 critical_flags |= SF_APPEND;
1545 #endif
1546 #ifdef UF_APPEND
1547 critical_flags |= UF_APPEND;
1548 #endif
1549 #ifdef EXT2_APPEND_FL
1550 critical_flags |= EXT2_APPEND_FL;
1551 #endif
1552 #ifdef EXT2_IMMUTABLE_FL
1553 critical_flags |= EXT2_IMMUTABLE_FL;
1554 #endif
1556 if (a->todo & TODO_FFLAGS) {
1557 archive_entry_fflags(a->entry, &set, &clear);
1560 * The first test encourages the compiler to eliminate
1561 * all of this if it's not necessary.
1563 if ((critical_flags != 0) && (set & critical_flags)) {
1564 le = current_fixup(a, a->name);
1565 le->fixup |= TODO_FFLAGS;
1566 le->fflags_set = set;
1567 /* Store the mode if it's not already there. */
1568 if ((le->fixup & TODO_MODE) == 0)
1569 le->mode = mode;
1570 } else {
1571 r = set_fflags_platform(a, a->fd,
1572 a->name, mode, set, clear);
1573 if (r != ARCHIVE_OK)
1574 return (r);
1577 return (ARCHIVE_OK);
1581 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && !defined(__linux)
1582 static int
1583 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1584 mode_t mode, unsigned long set, unsigned long clear)
1586 (void)mode; /* UNUSED */
1587 if (set == 0 && clear == 0)
1588 return (ARCHIVE_OK);
1591 * XXX Is the stat here really necessary? Or can I just use
1592 * the 'set' flags directly? In particular, I'm not sure
1593 * about the correct approach if we're overwriting an existing
1594 * file that already has flags on it. XXX
1596 if (fd >= 0 && fstat(fd, &a->st) == 0)
1597 a->pst = &a->st;
1598 else if (lstat(name, &a->st) == 0)
1599 a->pst = &a->st;
1600 else {
1601 archive_set_error(&a->archive, errno,
1602 "Couldn't stat file");
1603 return (ARCHIVE_WARN);
1606 a->st.st_flags &= ~clear;
1607 a->st.st_flags |= set;
1608 #ifdef HAVE_FCHFLAGS
1609 /* If platform has fchflags() and we were given an fd, use it. */
1610 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
1611 return (ARCHIVE_OK);
1612 #endif
1614 * If we can't use the fd to set the flags, we'll use the
1615 * pathname to set flags. We prefer lchflags() but will use
1616 * chflags() if we must.
1618 #ifdef HAVE_LCHFLAGS
1619 if (lchflags(name, a->st.st_flags) == 0)
1620 return (ARCHIVE_OK);
1621 #elif defined(HAVE_CHFLAGS)
1622 if (S_ISLNK(a->st.st_mode)) {
1623 archive_set_error(&a->archive, errno,
1624 "Can't set file flags on symlink.");
1625 return (ARCHIVE_WARN);
1627 if (chflags(name, a->st.st_flags) == 0)
1628 return (ARCHIVE_OK);
1629 #endif
1630 archive_set_error(&a->archive, errno,
1631 "Failed to set file flags");
1632 return (ARCHIVE_WARN);
1635 #elif defined(__linux) && defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS)
1638 * Linux has flags too, but uses ioctl() to access them instead of
1639 * having a separate chflags() system call.
1641 static int
1642 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1643 mode_t mode, unsigned long set, unsigned long clear)
1645 int ret;
1646 int myfd = fd;
1647 unsigned long newflags, oldflags;
1648 unsigned long sf_mask = 0;
1650 if (set == 0 && clear == 0)
1651 return (ARCHIVE_OK);
1652 /* Only regular files and dirs can have flags. */
1653 if (!S_ISREG(mode) && !S_ISDIR(mode))
1654 return (ARCHIVE_OK);
1656 /* If we weren't given an fd, open it ourselves. */
1657 if (myfd < 0)
1658 myfd = open(name, O_RDONLY|O_NONBLOCK);
1659 if (myfd < 0)
1660 return (ARCHIVE_OK);
1663 * Linux has no define for the flags that are only settable by
1664 * the root user. This code may seem a little complex, but
1665 * there seem to be some Linux systems that lack these
1666 * defines. (?) The code below degrades reasonably gracefully
1667 * if sf_mask is incomplete.
1669 #ifdef EXT2_IMMUTABLE_FL
1670 sf_mask |= EXT2_IMMUTABLE_FL;
1671 #endif
1672 #ifdef EXT2_APPEND_FL
1673 sf_mask |= EXT2_APPEND_FL;
1674 #endif
1676 * XXX As above, this would be way simpler if we didn't have
1677 * to read the current flags from disk. XXX
1679 ret = ARCHIVE_OK;
1680 /* Try setting the flags as given. */
1681 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1682 newflags = (oldflags & ~clear) | set;
1683 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1684 goto cleanup;
1685 if (errno != EPERM)
1686 goto fail;
1688 /* If we couldn't set all the flags, try again with a subset. */
1689 if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1690 newflags &= ~sf_mask;
1691 oldflags &= sf_mask;
1692 newflags |= oldflags;
1693 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1694 goto cleanup;
1696 /* We couldn't set the flags, so report the failure. */
1697 fail:
1698 archive_set_error(&a->archive, errno,
1699 "Failed to set file flags");
1700 ret = ARCHIVE_WARN;
1701 cleanup:
1702 if (fd < 0)
1703 close(myfd);
1704 return (ret);
1707 #else /* Not HAVE_CHFLAGS && Not __linux */
1710 * Of course, some systems have neither BSD chflags() nor Linux' flags
1711 * support through ioctl().
1713 static int
1714 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1715 mode_t mode, unsigned long set, unsigned long clear)
1717 (void)ad; /* UNUSED */
1718 (void)fd; /* UNUSED */
1719 (void)name; /* UNUSED */
1720 (void)mode; /* UNUSED */
1721 (void)set; /* UNUSED */
1722 (void)clear; /* UNUSED */
1723 return (ARCHIVE_OK);
1726 #endif /* __linux */
1728 #ifndef HAVE_POSIX_ACL
1729 /* Default empty function body to satisfy mainline code. */
1730 static int
1731 set_acls(struct archive_write_disk *a)
1733 (void)a; /* UNUSED */
1734 return (ARCHIVE_OK);
1737 #else
1740 * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
1742 static int
1743 set_acls(struct archive_write_disk *a)
1745 int ret;
1747 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_ACCESS,
1748 ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
1749 if (ret != ARCHIVE_OK)
1750 return (ret);
1751 ret = set_acl(a, a->fd, a->entry, ACL_TYPE_DEFAULT,
1752 ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
1753 return (ret);
1757 static int
1758 set_acl(struct archive_write_disk *a, int fd, struct archive_entry *entry,
1759 acl_type_t acl_type, int ae_requested_type, const char *tname)
1761 acl_t acl;
1762 acl_entry_t acl_entry;
1763 acl_permset_t acl_permset;
1764 int ret;
1765 int ae_type, ae_permset, ae_tag, ae_id;
1766 uid_t ae_uid;
1767 gid_t ae_gid;
1768 const char *ae_name;
1769 int entries;
1770 const char *name;
1772 ret = ARCHIVE_OK;
1773 entries = archive_entry_acl_reset(entry, ae_requested_type);
1774 if (entries == 0)
1775 return (ARCHIVE_OK);
1776 acl = acl_init(entries);
1777 while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
1778 &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
1779 acl_create_entry(&acl, &acl_entry);
1781 switch (ae_tag) {
1782 case ARCHIVE_ENTRY_ACL_USER:
1783 acl_set_tag_type(acl_entry, ACL_USER);
1784 ae_uid = a->lookup_uid(a->lookup_uid_data,
1785 ae_name, ae_id);
1786 acl_set_qualifier(acl_entry, &ae_uid);
1787 break;
1788 case ARCHIVE_ENTRY_ACL_GROUP:
1789 acl_set_tag_type(acl_entry, ACL_GROUP);
1790 ae_gid = a->lookup_gid(a->lookup_gid_data,
1791 ae_name, ae_id);
1792 acl_set_qualifier(acl_entry, &ae_gid);
1793 break;
1794 case ARCHIVE_ENTRY_ACL_USER_OBJ:
1795 acl_set_tag_type(acl_entry, ACL_USER_OBJ);
1796 break;
1797 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
1798 acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
1799 break;
1800 case ARCHIVE_ENTRY_ACL_MASK:
1801 acl_set_tag_type(acl_entry, ACL_MASK);
1802 break;
1803 case ARCHIVE_ENTRY_ACL_OTHER:
1804 acl_set_tag_type(acl_entry, ACL_OTHER);
1805 break;
1806 default:
1807 /* XXX */
1808 break;
1811 acl_get_permset(acl_entry, &acl_permset);
1812 acl_clear_perms(acl_permset);
1813 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
1814 acl_add_perm(acl_permset, ACL_EXECUTE);
1815 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
1816 acl_add_perm(acl_permset, ACL_WRITE);
1817 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
1818 acl_add_perm(acl_permset, ACL_READ);
1821 name = archive_entry_pathname(entry);
1823 /* Try restoring the ACL through 'fd' if we can. */
1824 #if HAVE_ACL_SET_FD
1825 if (fd >= 0 && acl_type == ACL_TYPE_ACCESS && acl_set_fd(fd, acl) == 0)
1826 ret = ARCHIVE_OK;
1827 else
1828 #else
1829 #if HAVE_ACL_SET_FD_NP
1830 if (fd >= 0 && acl_set_fd_np(fd, acl, acl_type) == 0)
1831 ret = ARCHIVE_OK;
1832 else
1833 #endif
1834 #endif
1835 if (acl_set_file(name, acl_type, acl) != 0) {
1836 archive_set_error(&a->archive, errno, "Failed to set %s acl", tname);
1837 ret = ARCHIVE_WARN;
1839 acl_free(acl);
1840 return (ret);
1842 #endif
1844 #if HAVE_LSETXATTR
1846 * Restore extended attributes - Linux implementation
1848 static int
1849 set_xattrs(struct archive_write_disk *a)
1851 struct archive_entry *entry = a->entry;
1852 static int warning_done = 0;
1853 int ret = ARCHIVE_OK;
1854 int i = archive_entry_xattr_reset(entry);
1856 while (i--) {
1857 const char *name;
1858 const void *value;
1859 size_t size;
1860 archive_entry_xattr_next(entry, &name, &value, &size);
1861 if (name != NULL &&
1862 strncmp(name, "xfsroot.", 8) != 0 &&
1863 strncmp(name, "system.", 7) != 0) {
1864 int e;
1865 #if HAVE_FSETXATTR
1866 if (a->fd >= 0)
1867 e = fsetxattr(a->fd, name, value, size, 0);
1868 else
1869 #endif
1871 e = lsetxattr(archive_entry_pathname(entry),
1872 name, value, size, 0);
1874 if (e == -1) {
1875 if (errno == ENOTSUP) {
1876 if (!warning_done) {
1877 warning_done = 1;
1878 archive_set_error(&a->archive, errno,
1879 "Cannot restore extended "
1880 "attributes on this file "
1881 "system");
1883 } else
1884 archive_set_error(&a->archive, errno,
1885 "Failed to set extended attribute");
1886 ret = ARCHIVE_WARN;
1888 } else {
1889 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1890 "Invalid extended attribute encountered");
1891 ret = ARCHIVE_WARN;
1894 return (ret);
1896 #else
1898 * Restore extended attributes - stub implementation for unsupported systems
1900 static int
1901 set_xattrs(struct archive_write_disk *a)
1903 static int warning_done = 0;
1905 /* If there aren't any extended attributes, then it's okay not
1906 * to extract them, otherwise, issue a single warning. */
1907 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
1908 warning_done = 1;
1909 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1910 "Cannot restore extended attributes on this system");
1911 return (ARCHIVE_WARN);
1913 /* Warning was already emitted; suppress further warnings. */
1914 return (ARCHIVE_OK);
1916 #endif
1920 * Trivial implementations of gid/uid lookup functions.
1921 * These are normally overridden by the client, but these stub
1922 * versions ensure that we always have something that works.
1924 static gid_t
1925 trivial_lookup_gid(void *private_data, const char *gname, gid_t gid)
1927 (void)private_data; /* UNUSED */
1928 (void)gname; /* UNUSED */
1929 return (gid);
1932 static uid_t
1933 trivial_lookup_uid(void *private_data, const char *uname, uid_t uid)
1935 (void)private_data; /* UNUSED */
1936 (void)uname; /* UNUSED */
1937 return (uid);