]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libarchive/archive_write_disk.c
This commit was generated by cvs2svn to compensate for changes in r169808,
[FreeBSD/FreeBSD.git] / lib / libarchive / archive_write_disk.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
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.
14  *
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.
25  */
26
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD$");
29
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
48
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
86
87 #include "archive.h"
88 #include "archive_string.h"
89 #include "archive_entry.h"
90 #include "archive_private.h"
91
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;
102 };
103
104 /*
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.
116  */
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
129
130 struct archive_write_disk {
131         struct archive  archive;
132
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;
139
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;
146
147         /*
148          * Full path of last file to satisfy symlink checks.
149          */
150         struct archive_string   path_safe;
151
152         /*
153          * Cached stat data from disk for the current entry.
154          * If this is valid, pst points to st.  Otherwise,
155          * pst is null.
156          */
157         struct stat              st;
158         struct stat             *pst;
159
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;
181 };
182
183 /*
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."
187  */
188 #define DEFAULT_DIR_MODE 0777
189 /*
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.
194  */
195 #define MINIMUM_DIR_MODE 0700
196 #define MAXIMUM_DIR_MODE 0775
197
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);
224
225
226 static struct archive_vtable *archive_write_disk_vtable(void);
227
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);
234
235 static struct archive_vtable *
236 archive_write_disk_vtable(void)
237 {
238         static struct archive_vtable av;
239         static int inited = 0;
240
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;
248         }
249         return (&av);
250 }
251
252
253 int
254 archive_write_disk_set_options(struct archive *_a, int flags)
255 {
256         struct archive_write_disk *a = (struct archive_write_disk *)_a;
257
258         a->flags = flags;
259         return (ARCHIVE_OK);
260 }
261
262
263 /*
264  * Extract this entry to disk.
265  *
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.
272  *
273  */
274 static int
275 _archive_write_header(struct archive *_a, struct archive_entry *entry)
276 {
277         struct archive_write_disk *a = (struct archive_write_disk *)_a;
278         struct fixup_entry *fe;
279         int ret, r;
280
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);
289         }
290
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);
303
304         /*
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/.".
308          */
309         ret = cleanup_pathname(a);
310         if (ret != ARCHIVE_OK)
311                 return (ret);
312
313         /*
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.
320          */
321         a->user_umask = umask(0);
322         /* From here on, early exit requires "goto done" to clean up. */
323
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. */
328                 /*
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.
341                  */
342                 if (a->mode & S_ISGID)
343                         a->todo |= TODO_SGID | TODO_SGID_CHECK;
344                 /*
345                  * Verifying the SUID is simpler, but can still be
346                  * done in multiple ways, hence the separate "check" bit.
347                  */
348                 if (a->mode & S_ISUID)
349                         a->todo |= TODO_SUID | TODO_SUID_CHECK;
350         } else {
351                 /*
352                  * User didn't request full permissions, so don't
353                  * restore SUID, SGID bits and obey umask.
354                  */
355                 a->mode &= ~S_ISUID;
356                 a->mode &= ~S_ISGID;
357                 a->mode &= ~S_ISVTX;
358                 a->mode &= ~a->user_umask;
359         }
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;
372         }
373 #ifdef HAVE_FCHDIR
374         /* If path exceeds PATH_MAX, shorten the path. */
375         edit_deep_directories(a);
376 #endif
377
378         ret = restore_entry(a);
379
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;
386         }
387 #endif
388
389         /*
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.
394          */
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;
399         }
400
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);
408         }
409
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. */
414         }
415
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);
422
423         return (ret);
424 }
425
426 int
427 archive_write_disk_set_skip_file(struct archive *_a, dev_t d, ino_t i)
428 {
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);
435 }
436
437 static ssize_t
438 _archive_write_data_block(struct archive *_a,
439     const void *buff, size_t size, off_t offset)
440 {
441         struct archive_write_disk *a = (struct archive_write_disk *)_a;
442         ssize_t bytes_written = 0;
443
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);
449
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);
455                 }
456                 a->offset = offset;
457         }
458
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);
465                 }
466                 size -= bytes_written;
467                 a->offset += bytes_written;
468         }
469         return (ARCHIVE_OK);
470 }
471
472 static ssize_t
473 _archive_write_data(struct archive *_a, const void *buff, size_t size)
474 {
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);
480
481         return (_archive_write_data_block(_a, buff, size, a->offset));
482 }
483
484 static int
485 _archive_write_finish_entry(struct archive *_a)
486 {
487         struct archive_write_disk *a = (struct archive_write_disk *)_a;
488         int ret = ARCHIVE_OK;
489
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);
496
497         /* Restore metadata. */
498
499         /*
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.
502          */
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));
507         }
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));
513          }
514         /*
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.
518          */
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;
524         }
525         if (a->todo & TODO_TIMES) {
526                 int r2 = set_time(a);
527                 if (r2 < ret) ret = r2;
528         }
529         if (a->todo & TODO_ACLS) {
530                 int r2 = set_acls(a);
531                 if (r2 < ret) ret = r2;
532         }
533         if (a->todo & TODO_XATTR) {
534                 int r2 = set_xattrs(a);
535                 if (r2 < ret) ret = r2;
536         }
537         if (a->todo & TODO_FFLAGS) {
538                 int r2 = set_fflags(a);
539                 if (r2 < ret) ret = r2;
540         }
541
542         /* If there's an fd, we can close it now. */
543         if (a->fd >= 0) {
544                 close(a->fd);
545                 a->fd = -1;
546         }
547         a->archive.state = ARCHIVE_STATE_HEADER;
548         return (ret);
549 }
550
551 int
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))
556 {
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");
560
561         a->lookup_gid = lookup_gid;
562         a->cleanup_gid = cleanup_gid;
563         a->lookup_gid_data = private_data;
564         return (ARCHIVE_OK);
565 }
566
567 int
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))
572 {
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");
576
577         a->lookup_uid = lookup_uid;
578         a->cleanup_uid = cleanup_uid;
579         a->lookup_uid_data = private_data;
580         return (ARCHIVE_OK);
581 }
582
583
584 /*
585  * Create a new archive_write_disk object and initialize it with global state.
586  */
587 struct archive *
588 archive_write_disk_new(void)
589 {
590         struct archive_write_disk *a;
591
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);
605 }
606
607
608 /*
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.
615  */
616 #ifdef HAVE_FCHDIR
617 static void
618 edit_deep_directories(struct archive_write_disk *a)
619 {
620         int ret;
621         char *tail = a->name;
622
623         a->restore_pwd = -1;
624
625         /* If path is short, avoid the open() below. */
626         if (strlen(tail) <= PATH_MAX)
627                 return;
628
629         /* Try to record our starting dir. */
630         a->restore_pwd = open(".", O_RDONLY);
631         if (a->restore_pwd < 0)
632                 return;
633
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;
654         }
655         return;
656 }
657 #endif
658
659 /*
660  * The main restore function.
661  */
662 static int
663 restore_entry(struct archive_write_disk *a)
664 {
665         int ret = ARCHIVE_OK, en;
666
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);
679                 }
680         }
681
682         /* Try creating it first; if this fails, we'll try to recover. */
683         en = create_filesystem_object(a);
684
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);
690         }
691
692         if (en == EEXIST) {
693                 /* If we're not overwriting, we're done. */
694                 if (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE) {
695                         archive_set_error(&a->archive, en, "Already exists");
696                         return (ARCHIVE_WARN);
697                 }
698
699                 /* Find out what's in the way before we go any further. */
700                 if (lstat(a->name, &a->st) != 0) {
701                         archive_set_error(&a->archive, errno,
702                             "Can't stat existing object");
703                         return (ARCHIVE_WARN);
704                 }
705
706                 /* TODO: if it's a symlink... */
707
708                 /* If it's our archive, we're done. */
709                 if (a->skip_file_dev > 0 &&
710                     a->skip_file_ino > 0 &&
711                     a->st.st_dev == a->skip_file_dev &&
712                     a->st.st_ino == a->skip_file_ino) {
713                         archive_set_error(&a->archive, 0, "Refusing to overwrite archive");
714                         return (ARCHIVE_FAILED);
715                 }
716
717                 if (!S_ISDIR(a->st.st_mode)) {
718                         /* A non-dir is in the way, unlink it. */
719                         if (unlink(a->name) != 0) {
720                                 archive_set_error(&a->archive, errno,
721                                     "Can't unlink already-existing object");
722                                 return (ARCHIVE_WARN);
723                         }
724                         /* Try again. */
725                         en = create_filesystem_object(a);
726                 } else if (!S_ISDIR(a->mode)) {
727                         /* A dir is in the way of a non-dir, rmdir it. */
728                         if (rmdir(a->name) != 0) {
729                                 archive_set_error(&a->archive, errno,
730                                     "Can't remove already-existing dir");
731                                 return (ARCHIVE_WARN);
732                         }
733                         /* Try again. */
734                         en = create_filesystem_object(a);
735                 } else {
736                         /*
737                          * There's a dir in the way of a dir.  Don't
738                          * waste time with rmdir()/mkdir(), just fix
739                          * up the permissions on the existing dir.
740                          * Note that we don't change perms on existing
741                          * dirs unless _EXTRACT_PERM is specified.
742                          */
743                         if ((a->mode != a->st.st_mode)
744                             && (a->todo & TODO_MODE_FORCE))
745                                 a->deferred |= (a->todo & TODO_MODE);
746                         /* Ownership doesn't need deferred fixup. */
747                         en = 0; /* Forget the EEXIST. */
748                 }
749         }
750
751         if (en) {
752                 /* Everything failed; give up here. */
753                 archive_set_error(&a->archive, en, "Can't create '%s'", a->name);
754                 return (ARCHIVE_WARN);
755         }
756
757         a->pst = NULL; /* Cached stat data no longer valid. */
758         return (ret);
759 }
760
761 /*
762  * Returns 0 if creation succeeds, or else returns errno value from
763  * the failed system call.   Note:  This function should only ever perform
764  * a single system call.
765  */
766 int
767 create_filesystem_object(struct archive_write_disk *a)
768 {
769         /* Create the entry. */
770         const char *linkname;
771         mode_t final_mode, mode;
772         int r;
773
774         /* We identify hard/symlinks according to the link names. */
775         /* Since link(2) and symlink(2) don't handle modes, we're done here. */
776         linkname = archive_entry_hardlink(a->entry);
777         if (linkname != NULL)
778                 return link(linkname, a->name) ? errno : 0;
779         linkname = archive_entry_symlink(a->entry);
780         if (linkname != NULL)
781                 return symlink(linkname, a->name) ? errno : 0;
782
783         /*
784          * The remaining system calls all set permissions, so let's
785          * try to take advantage of that to avoid an extra chmod()
786          * call.  (Recall that umask is set to zero right now!)
787          */
788
789         /* Mode we want for the final restored object (w/o file type bits). */
790         final_mode = a->mode & 07777;
791         /*
792          * The mode that will actually be restored in this step.  Note
793          * that SUID, SGID, etc, require additional work to ensure
794          * security, so we never restore them at this point.
795          */
796         mode = final_mode & 0777;
797
798         switch (a->mode & S_IFMT) {
799         default:
800                 /* POSIX requires that we fall through here. */
801                 /* FALLTHROUGH */
802         case S_IFREG:
803                 a->fd = open(a->name,
804                     O_WRONLY | O_CREAT | O_EXCL, mode);
805                 r = (a->fd < 0);
806                 break;
807         case S_IFCHR:
808                 r = mknod(a->name, mode | S_IFCHR,
809                     archive_entry_rdev(a->entry));
810                 break;
811         case S_IFBLK:
812                 r = mknod(a->name, mode | S_IFBLK,
813                     archive_entry_rdev(a->entry));
814                 break;
815         case S_IFDIR:
816                 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
817                 r = mkdir(a->name, mode);
818                 if (r == 0) {
819                         /* Defer setting dir times. */
820                         a->deferred |= (a->todo & TODO_TIMES);
821                         a->todo &= ~TODO_TIMES;
822                         /* Never use an immediate chmod(). */
823                         if (mode != final_mode)
824                                 a->deferred |= (a->todo & TODO_MODE);
825                         a->todo &= ~TODO_MODE;
826                 }
827                 break;
828         case S_IFIFO:
829                 r = mkfifo(a->name, mode);
830                 break;
831         }
832
833         /* All the system calls above set errno on failure. */
834         if (r)
835                 return (errno);
836
837         /* If we managed to set the final mode, we've avoided a chmod(). */
838         if (mode == final_mode)
839                 a->todo &= ~TODO_MODE;
840         return (0);
841 }
842
843 /*
844  * Cleanup function for archive_extract.  Mostly, this involves processing
845  * the fixup list, which is used to address a number of problems:
846  *   * Dir permissions might prevent us from restoring a file in that
847  *     dir, so we restore the dir with minimum 0700 permissions first,
848  *     then correct the mode at the end.
849  *   * Similarly, the act of restoring a file touches the directory
850  *     and changes the timestamp on the dir, so we have to touch-up dir
851  *     timestamps at the end as well.
852  *   * Some file flags can interfere with the restore by, for example,
853  *     preventing the creation of hardlinks to those files.
854  *
855  * Note that tar/cpio do not require that archives be in a particular
856  * order; there is no way to know when the last file has been restored
857  * within a directory, so there's no way to optimize the memory usage
858  * here by fixing up the directory any earlier than the
859  * end-of-archive.
860  *
861  * XXX TODO: Directory ACLs should be restored here, for the same
862  * reason we set directory perms here. XXX
863  */
864 static int
865 _archive_write_close(struct archive *_a)
866 {
867         struct archive_write_disk *a = (struct archive_write_disk *)_a;
868         struct fixup_entry *next, *p;
869         int ret;
870
871         __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
872             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
873             "archive_write_disk_close");
874         ret = _archive_write_finish_entry(&a->archive);
875
876         /* Sort dir list so directories are fixed up in depth-first order. */
877         p = sort_dir_list(a->fixup_list);
878
879         while (p != NULL) {
880                 a->pst = NULL; /* Mark stat cache as out-of-date. */
881                 if (p->fixup & TODO_TIMES) {
882 #ifdef HAVE_UTIMES
883                         /* {f,l,}utimes() are preferred, when available. */
884                         struct timeval times[2];
885                         times[1].tv_sec = p->mtime;
886                         times[1].tv_usec = p->mtime_nanos / 1000;
887                         times[0].tv_sec = p->atime;
888                         times[0].tv_usec = p->atime_nanos / 1000;
889 #ifdef HAVE_LUTIMES
890                         lutimes(p->name, times);
891 #else
892                         utimes(p->name, times);
893 #endif
894 #else
895                         /* utime() is more portable, but less precise. */
896                         struct utimbuf times;
897                         times.modtime = p->mtime;
898                         times.actime = p->atime;
899
900                         utime(p->name, &times);
901 #endif
902                 }
903                 if (p->fixup & TODO_MODE_BASE)
904                         chmod(p->name, p->mode);
905
906                 if (p->fixup & TODO_FFLAGS)
907                         set_fflags_platform(a, -1, p->name,
908                             p->mode, p->fflags_set, 0);
909
910                 next = p->next;
911                 free(p->name);
912                 free(p);
913                 p = next;
914         }
915         a->fixup_list = NULL;
916         return (ret);
917 }
918
919 static int
920 _archive_write_finish(struct archive *_a)
921 {
922         struct archive_write_disk *a = (struct archive_write_disk *)_a;
923         int ret;
924         ret = _archive_write_close(&a->archive);
925         if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
926                 (a->cleanup_gid)(a->lookup_gid_data);
927         if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
928                 (a->cleanup_uid)(a->lookup_uid_data);
929         archive_string_free(&a->_name_data);
930         archive_string_free(&a->archive.error_string);
931         archive_string_free(&a->path_safe);
932         free(a);
933         return (ret);
934 }
935
936 /*
937  * Simple O(n log n) merge sort to order the fixup list.  In
938  * particular, we want to restore dir timestamps depth-first.
939  */
940 static struct fixup_entry *
941 sort_dir_list(struct fixup_entry *p)
942 {
943         struct fixup_entry *a, *b, *t;
944
945         if (p == NULL)
946                 return (NULL);
947         /* A one-item list is already sorted. */
948         if (p->next == NULL)
949                 return (p);
950
951         /* Step 1: split the list. */
952         t = p;
953         a = p->next->next;
954         while (a != NULL) {
955                 /* Step a twice, t once. */
956                 a = a->next;
957                 if (a != NULL)
958                         a = a->next;
959                 t = t->next;
960         }
961         /* Now, t is at the mid-point, so break the list here. */
962         b = t->next;
963         t->next = NULL;
964         a = p;
965
966         /* Step 2: Recursively sort the two sub-lists. */
967         a = sort_dir_list(a);
968         b = sort_dir_list(b);
969
970         /* Step 3: Merge the returned lists. */
971         /* Pick the first element for the merged list. */
972         if (strcmp(a->name, b->name) > 0) {
973                 t = p = a;
974                 a = a->next;
975         } else {
976                 t = p = b;
977                 b = b->next;
978         }
979
980         /* Always put the later element on the list first. */
981         while (a != NULL && b != NULL) {
982                 if (strcmp(a->name, b->name) > 0) {
983                         t->next = a;
984                         a = a->next;
985                 } else {
986                         t->next = b;
987                         b = b->next;
988                 }
989                 t = t->next;
990         }
991
992         /* Only one list is non-empty, so just splice it on. */
993         if (a != NULL)
994                 t->next = a;
995         if (b != NULL)
996                 t->next = b;
997
998         return (p);
999 }
1000
1001 /*
1002  * Returns a new, initialized fixup entry.
1003  *
1004  * TODO: Reduce the memory requirements for this list by using a tree
1005  * structure rather than a simple list of names.
1006  */
1007 static struct fixup_entry *
1008 new_fixup(struct archive_write_disk *a, const char *pathname)
1009 {
1010         struct fixup_entry *fe;
1011
1012         fe = (struct fixup_entry *)malloc(sizeof(struct fixup_entry));
1013         if (fe == NULL)
1014                 return (NULL);
1015         fe->next = a->fixup_list;
1016         a->fixup_list = fe;
1017         fe->fixup = 0;
1018         fe->name = strdup(pathname);
1019         return (fe);
1020 }
1021
1022 /*
1023  * Returns a fixup structure for the current entry.
1024  */
1025 static struct fixup_entry *
1026 current_fixup(struct archive_write_disk *a, const char *pathname)
1027 {
1028         if (a->current_fixup == NULL)
1029                 a->current_fixup = new_fixup(a, pathname);
1030         return (a->current_fixup);
1031 }
1032
1033 /* TODO: Make this work. */
1034 /*
1035  * TODO: The deep-directory support bypasses this; disable deep directory
1036  * support if we're doing symlink checks.
1037  */
1038 /*
1039  * TODO: Someday, integrate this with the deep dir support; they both
1040  * scan the path and both can be optimized by comparing against other
1041  * recent paths.
1042  */
1043 static int
1044 check_symlinks(struct archive_write_disk *a)
1045 {
1046         char *pn, *p;
1047         char c;
1048         int r;
1049         struct stat st;
1050
1051         /*
1052          * Gaurd against symlink tricks.  Reject any archive entry whose
1053          * destination would be altered by a symlink.
1054          */
1055         /* Whatever we checked last time doesn't need to be re-checked. */
1056         pn = a->name;
1057         p = a->path_safe.s;
1058         while ((*pn != '\0') && (*p == *pn))
1059                 ++p, ++pn;
1060         c = pn[0];
1061         /* Keep going until we've checked the entire name. */
1062         while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
1063                 /* Skip the next path element. */
1064                 while (*pn != '\0' && *pn != '/')
1065                         ++pn;
1066                 c = pn[0];
1067                 pn[0] = '\0';
1068                 /* Check that we haven't hit a symlink. */
1069                 r = lstat(a->name, &st);
1070                 if (r != 0) {
1071                         /* We've hit a dir that doesn't exist; stop now. */
1072                         if (errno == ENOENT)
1073                                 break;
1074                 } else if (S_ISLNK(st.st_mode)) {
1075                         if (c == '\0') {
1076                                 /*
1077                                  * Last element is symlink; remove it
1078                                  * so we can overwrite it with the
1079                                  * item being extracted.
1080                                  */
1081                                 if (unlink(a->name)) {
1082                                         archive_set_error(&a->archive, errno,
1083                                             "Could not remove symlink %s",
1084                                             a->name);
1085                                         pn[0] = c;
1086                                         return (ARCHIVE_WARN);
1087                                 }
1088                                 /*
1089                                  * Even if we did remove it, a warning
1090                                  * is in order.  The warning is silly,
1091                                  * though, if we're just replacing one
1092                                  * symlink with another symlink.
1093                                  */
1094                                 if (!S_ISLNK(a->mode)) {
1095                                         archive_set_error(&a->archive, 0,
1096                                             "Removing symlink %s",
1097                                             a->name);
1098                                 }
1099                                 /* Symlink gone.  No more problem! */
1100                                 pn[0] = c;
1101                                 return (0);
1102                         } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
1103                                 /* User asked us to remove problems. */
1104                                 if (unlink(a->name) != 0) {
1105                                         archive_set_error(&a->archive, 0,
1106                                             "Cannot remove intervening symlink %s",
1107                                             a->name);
1108                                         pn[0] = c;
1109                                         return (ARCHIVE_WARN);
1110                                 }
1111                         } else {
1112                                 archive_set_error(&a->archive, 0,
1113                                     "Cannot extract through symlink %s",
1114                                     a->name);
1115                                 pn[0] = c;
1116                                 return (ARCHIVE_WARN);
1117                         }
1118                 }
1119         }
1120         pn[0] = c;
1121         /* We've checked and/or cleaned the whole path, so remember it. */
1122         archive_strcpy(&a->path_safe, a->name);
1123         return (ARCHIVE_OK);
1124 }
1125
1126 /*
1127  * Canonicalize the pathname.  In particular, this strips duplicate
1128  * '/' characters, '.' elements, and trailing '/'.  It also raises an
1129  * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
1130  * set) any '..' in the path.
1131  */
1132 static int
1133 cleanup_pathname(struct archive_write_disk *a)
1134 {
1135         char *dest, *src;
1136         char separator = '\0';
1137         int lastdotdot = 0; /* True if last elt copied was '..' */
1138
1139         dest = src = a->name;
1140         if (*src == '\0') {
1141                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1142                     "Invalid empty pathname");
1143                 return (ARCHIVE_WARN);
1144         }
1145
1146         /* Skip leading '/'. */
1147         if (*src == '/')
1148                 separator = *src++;
1149
1150         /* Scan the pathname one element at a time. */
1151         for (;;) {
1152                 /* src points to first char after '/' */
1153                 if (src[0] == '\0') {
1154                         break;
1155                 } else if (src[0] == '/') {
1156                         /* Found '//', ignore second one. */
1157                         src++;
1158                         continue;
1159                 } else if (src[0] == '.') {
1160                         if (src[1] == '\0') {
1161                                 /* Ignore trailing '.' */
1162                                 break;
1163                         } else if (src[1] == '/') {
1164                                 /* Skip './'. */
1165                                 src += 2;
1166                                 continue;
1167                         } else if (src[1] == '.') {
1168                                 if (src[2] == '/' || src[2] == '\0') {
1169                                         /* Conditionally warn about '..' */
1170                                         if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
1171                                                 archive_set_error(&a->archive,
1172                                                     ARCHIVE_ERRNO_MISC,
1173                                                     "Path contains '..'");
1174                                                 return (ARCHIVE_WARN);
1175                                         }
1176                                         lastdotdot = 1;
1177                                 } else
1178                                         lastdotdot = 0;
1179                                 /*
1180                                  * Note: Under no circumstances do we
1181                                  * remove '..' elements.  In
1182                                  * particular, restoring
1183                                  * '/foo/../bar/' should create the
1184                                  * 'foo' dir as a side-effect.
1185                                  */
1186                         } else
1187                                 lastdotdot = 0;
1188                 } else
1189                         lastdotdot = 0;
1190
1191                 /* Copy current element, including leading '/'. */
1192                 if (separator)
1193                         *dest++ = '/';
1194                 while (*src != '\0' && *src != '/') {
1195                         *dest++ = *src++;
1196                 }
1197
1198                 if (*src == '\0')
1199                         break;
1200
1201                 /* Skip '/' separator. */
1202                 separator = *src++;
1203         }
1204         /*
1205          * We've just copied zero or more path elements, not including the
1206          * final '/'.
1207          */
1208         if (lastdotdot) {
1209                 /* Trailing '..' is always wrong. */
1210                 archive_set_error(&a->archive,
1211                     ARCHIVE_ERRNO_MISC,
1212                     "Path contains trailing '..'");
1213                 return (ARCHIVE_WARN);
1214         }
1215         if (dest == a->name) {
1216                 /*
1217                  * Nothing got copied.  The path must have been something
1218                  * like '.' or '/' or './' or '/././././/./'.
1219                  */
1220                 if (separator)
1221                         *dest++ = '/';
1222                 else
1223                         *dest++ = '.';
1224         }
1225         /* Terminate the result. */
1226         *dest = '\0';
1227         return (ARCHIVE_OK);
1228 }
1229
1230 /*
1231  * Create the parent directory of the specified path, assuming path
1232  * is already in mutable storage.
1233  */
1234 static int
1235 create_parent_dir(struct archive_write_disk *a, char *path)
1236 {
1237         char *slash;
1238         int r;
1239
1240         /* Remove tail element to obtain parent name. */
1241         slash = strrchr(path, '/');
1242         if (slash == NULL)
1243                 return (ARCHIVE_OK);
1244         *slash = '\0';
1245         r = create_dir(a, path);
1246         *slash = '/';
1247         return (r);
1248 }
1249
1250 /*
1251  * Create the specified dir, recursing to create parents as necessary.
1252  *
1253  * Returns ARCHIVE_OK if the path exists when we're done here.
1254  * Otherwise, returns ARCHIVE_WARN.
1255  * Assumes path is in mutable storage; path is unchanged on exit.
1256  */
1257 static int
1258 create_dir(struct archive_write_disk *a, char *path)
1259 {
1260         struct stat st;
1261         struct fixup_entry *le;
1262         char *slash, *base;
1263         mode_t mode_final, mode;
1264         int r;
1265
1266         r = ARCHIVE_OK;
1267
1268         /* Check for special names and just skip them. */
1269         slash = strrchr(path, '/');
1270         base = strrchr(path, '/');
1271         if (slash == NULL)
1272                 base = path;
1273         else
1274                 base = slash + 1;
1275
1276         if (base[0] == '\0' ||
1277             (base[0] == '.' && base[1] == '\0') ||
1278             (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
1279                 /* Don't bother trying to create null path, '.', or '..'. */
1280                 if (slash != NULL) {
1281                         *slash = '\0';
1282                         r = create_dir(a, path);
1283                         *slash = '/';
1284                         return (r);
1285                 }
1286                 return (ARCHIVE_OK);
1287         }
1288
1289         /*
1290          * Yes, this should be stat() and not lstat().  Using lstat()
1291          * here loses the ability to extract through symlinks.  Also note
1292          * that this should not use the a->st cache.
1293          */
1294         if (stat(path, &st) == 0) {
1295                 if (S_ISDIR(st.st_mode))
1296                         return (ARCHIVE_OK);
1297                 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1298                         archive_set_error(&a->archive, EEXIST,
1299                             "Can't create directory '%s'", path);
1300                         return (ARCHIVE_WARN);
1301                 }
1302                 if (unlink(path) != 0) {
1303                         archive_set_error(&a->archive, errno,
1304                             "Can't create directory '%s': "
1305                             "Conflicting file cannot be removed");
1306                         return (ARCHIVE_WARN);
1307                 }
1308         } else if (errno != ENOENT && errno != ENOTDIR) {
1309                 /* Stat failed? */
1310                 archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
1311                 return (ARCHIVE_WARN);
1312         } else if (slash != NULL) {
1313                 *slash = '\0';
1314                 r = create_dir(a, path);
1315                 *slash = '/';
1316                 if (r != ARCHIVE_OK)
1317                         return (r);
1318         }
1319
1320         /*
1321          * Mode we want for the final restored directory.  Per POSIX,
1322          * implicitly-created dirs must be created obeying the umask.
1323          * There's no mention whether this is different for privileged
1324          * restores (which the rest of this code handles by pretending
1325          * umask=0).  I've chosen here to always obey the user's umask for
1326          * implicit dirs, even if _EXTRACT_PERM was specified.
1327          */
1328         mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
1329         /* Mode we want on disk during the restore process. */
1330         mode = mode_final;
1331         mode |= MINIMUM_DIR_MODE;
1332         mode &= MAXIMUM_DIR_MODE;
1333         if (mkdir(path, mode) == 0) {
1334                 if (mode != mode_final) {
1335                         le = new_fixup(a, path);
1336                         le->fixup |=TODO_MODE_BASE;
1337                         le->mode = mode_final;
1338                 }
1339                 return (ARCHIVE_OK);
1340         }
1341
1342         /*
1343          * Without the following check, a/b/../b/c/d fails at the
1344          * second visit to 'b', so 'd' can't be created.  Note that we
1345          * don't add it to the fixup list here, as it's already been
1346          * added.
1347          */
1348         if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1349                 return (ARCHIVE_OK);
1350
1351         archive_set_error(&a->archive, errno, "Failed to create dir '%s'", path);
1352         return (ARCHIVE_WARN);
1353 }
1354
1355 /*
1356  * Note: Although we can skip setting the user id if the desired user
1357  * id matches the current user, we cannot skip setting the group, as
1358  * many systems set the gid bit based on the containing directory.  So
1359  * we have to perform a chown syscall if we want to restore the SGID
1360  * bit.  (The alternative is to stat() and then possibly chown(); it's
1361  * more efficient to skip the stat() and just always chown().)  Note
1362  * that a successful chown() here clears the TODO_SGID_CHECK bit, which
1363  * allows set_mode to skip the stat() check for the GID.
1364  */
1365 static int
1366 set_ownership(struct archive_write_disk *a)
1367 {
1368         /* If we know we can't change it, don't bother trying. */
1369         if (a->user_uid != 0  &&  a->user_uid != a->uid) {
1370                 archive_set_error(&a->archive, errno,
1371                     "Can't set UID=%d", a->uid);
1372                 return (ARCHIVE_WARN);
1373         }
1374
1375 #ifdef HAVE_FCHOWN
1376         if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0)
1377                 goto success;
1378 #endif
1379
1380 #ifdef HAVE_LCHOWN
1381         if (lchown(a->name, a->uid, a->gid) == 0)
1382                 goto success;
1383 #else
1384         if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0)
1385                 goto success;
1386 #endif
1387
1388         archive_set_error(&a->archive, errno,
1389             "Can't set user=%d/group=%d for %s", a->uid, a->gid,
1390             a->name);
1391         return (ARCHIVE_WARN);
1392 success:
1393         a->todo &= ~TODO_OWNER;
1394         /* We know the user/group are correct now. */
1395         a->todo &= ~TODO_SGID_CHECK;
1396         a->todo &= ~TODO_SUID_CHECK;
1397         return (ARCHIVE_OK);
1398 }
1399
1400 #ifdef HAVE_UTIMES
1401 /*
1402  * The utimes()-family functions provide high resolution and
1403  * a way to set time on an fd or a symlink.  We prefer them
1404  * when they're available.
1405  */
1406 static int
1407 set_time(struct archive_write_disk *a)
1408 {
1409         const struct stat *st;
1410         struct timeval times[2];
1411
1412         st = archive_entry_stat(a->entry);
1413
1414         times[1].tv_sec = st->st_mtime;
1415         times[1].tv_usec = ARCHIVE_STAT_MTIME_NANOS(st) / 1000;
1416
1417         times[0].tv_sec = st->st_atime;
1418         times[0].tv_usec = ARCHIVE_STAT_ATIME_NANOS(st) / 1000;
1419
1420 #ifdef HAVE_FUTIMES
1421         if (a->fd >= 0 && futimes(a->fd, times) == 0) {
1422                 return (ARCHIVE_OK);
1423         }
1424 #endif
1425
1426 #ifdef HAVE_LUTIMES
1427         if (lutimes(a->name, times) != 0)
1428 #else
1429         if (!S_ISLNK(a->mode) && utimes(a->name, times) != 0)
1430 #endif
1431         {
1432                 archive_set_error(&a->archive, errno, "Can't update time for %s",
1433                     a->name);
1434                 return (ARCHIVE_WARN);
1435         }
1436
1437         /*
1438          * Note: POSIX does not provide a portable way to restore ctime.
1439          * (Apart from resetting the system clock, which is distasteful.)
1440          * So, any restoration of ctime will necessarily be OS-specific.
1441          */
1442
1443         /* XXX TODO: Can FreeBSD restore ctime? XXX */
1444         return (ARCHIVE_OK);
1445 }
1446 #elif defined(HAVE_UTIME)
1447 /*
1448  * utime() is an older, more standard interface that we'll use
1449  * if utimes() isn't available.
1450  */
1451 static int
1452 set_time(struct archive_write_disk *a)
1453 {
1454         const struct stat *st = archive_entry_stat(a->entry);
1455         struct utimbuf times;
1456
1457         times.modtime = st->st_mtime;
1458         times.actime = st->st_atime;
1459         if (!S_ISLNK(a->mode) && utime(a->name, &times) != 0) {
1460                 archive_set_error(&a->archive, errno,
1461                     "Can't update time for %s", a->name);
1462                 return (ARCHIVE_WARN);
1463         }
1464         return (ARCHIVE_OK);
1465 }
1466 #else
1467 /* This platform doesn't give us a way to restore the time. */
1468 static int
1469 set_time(struct archive_write_disk *a)
1470 {
1471         (void)a; /* UNUSED */
1472         archive_set_error(&a->archive, errno,
1473             "Can't update time for %s", a->name);
1474         return (ARCHIVE_WARN);
1475 }
1476 #endif
1477
1478
1479 static int
1480 set_mode(struct archive_write_disk *a, int mode)
1481 {
1482         int r = ARCHIVE_OK;
1483
1484         if (a->todo & TODO_SGID_CHECK) {
1485                 /*
1486                  * If we don't know the GID is right, we must stat()
1487                  * to verify it.  We can't just check the GID of this
1488                  * process, since systems sometimes set GID from
1489                  * the enclosing dir or based on ACLs.
1490                  */
1491                 if (a->pst != NULL) {
1492                         /* Already have stat() data available. */
1493 #ifdef HAVE_FSTAT
1494                 } else if (fd >= 0 && fstat(fd, &a->st) == 0) {
1495                         a->pst = &a->st;
1496 #endif
1497                 } else if (stat(a->name, &a->st) == 0) {
1498                         a->pst = &a->st;
1499                 } else {
1500                         archive_set_error(&a->archive, errno,
1501                             "Couldn't stat file");
1502                         return (ARCHIVE_WARN);
1503                 }
1504                 if (a->pst->st_gid != a->gid) {
1505                         mode &= ~ S_ISGID;
1506                         archive_set_error(&a->archive, -1, "Can't restore SGID bit");
1507                         r = ARCHIVE_WARN;
1508                 }
1509                 /* While we're here, double-check the UID. */
1510                 if (a->pst->st_uid != a->uid
1511                     && (a->todo & TODO_SUID)) {
1512                         mode &= ~ S_ISUID;
1513                         archive_set_error(&a->archive, -1, "Can't restore SUID bit");
1514                         r = ARCHIVE_WARN;
1515                 }
1516                 a->todo &= ~TODO_SGID_CHECK;
1517                 a->todo &= ~TODO_SUID_CHECK;
1518         } else if (a->todo & TODO_SUID_CHECK) {
1519                 /*
1520                  * If we don't know the UID is right, we can just check
1521                  * the user, since all systems set the file UID from
1522                  * the process UID.
1523                  */
1524                 if (a->user_uid != a->uid) {
1525                         mode &= ~ S_ISUID;
1526                         archive_set_error(&a->archive, -1, "Can't make file SUID");
1527                         r = ARCHIVE_WARN;
1528                 }
1529                 a->todo &= ~TODO_SUID_CHECK;
1530         }
1531
1532         if (S_ISLNK(a->mode)) {
1533 #ifdef HAVE_LCHMOD
1534                 /*
1535                  * If this is a symlink, use lchmod().  If the
1536                  * platform doesn't support lchmod(), just skip it.  A
1537                  * platform that doesn't provide a way to set
1538                  * permissions on symlinks probably ignores
1539                  * permissions on symlinks, so a failure here has no
1540                  * impact.
1541                  */
1542                 if (lchmod(a->name, mode) != 0) {
1543                         archive_set_error(&a->archive, errno, "Can't set permissions");
1544                         r = ARCHIVE_WARN;
1545                 }
1546 #endif
1547         } else if (!S_ISDIR(a->mode)) {
1548                 /*
1549                  * If it's not a symlink and not a dir, then use
1550                  * fchmod() or chmod(), depending on whether we have
1551                  * an fd.  Dirs get their perms set during the
1552                  * post-extract fixup, which is handled elsewhere.
1553                  */
1554 #ifdef HAVE_FCHMOD
1555                 if (a->fd >= 0) {
1556                         if (fchmod(a->fd, mode) != 0) {
1557                                 archive_set_error(&a->archive, errno,
1558                                     "Can't set permissions");
1559                                 r = ARCHIVE_WARN;
1560                         }
1561                 } else
1562 #endif
1563                         /* If this platform lacks fchmod(), then
1564                          * we'll just use chmod(). */
1565                         if (chmod(a->name, mode) != 0) {
1566                                 archive_set_error(&a->archive, errno,
1567                                     "Can't set permissions");
1568                                 r = ARCHIVE_WARN;
1569                         }
1570         }
1571         return (r);
1572 }
1573
1574 static int
1575 set_fflags(struct archive_write_disk *a)
1576 {
1577         struct fixup_entry *le;
1578         unsigned long   set, clear;
1579         int             r;
1580         int             critical_flags;
1581         mode_t          mode = archive_entry_mode(a->entry);
1582
1583         /*
1584          * Make 'critical_flags' hold all file flags that can't be
1585          * immediately restored.  For example, on BSD systems,
1586          * SF_IMMUTABLE prevents hardlinks from being created, so
1587          * should not be set until after any hardlinks are created.  To
1588          * preserve some semblance of portability, this uses #ifdef
1589          * extensively.  Ugly, but it works.
1590          *
1591          * Yes, Virginia, this does create a security race.  It's mitigated
1592          * somewhat by the practice of creating dirs 0700 until the extract
1593          * is done, but it would be nice if we could do more than that.
1594          * People restoring critical file systems should be wary of
1595          * other programs that might try to muck with files as they're
1596          * being restored.
1597          */
1598         /* Hopefully, the compiler will optimize this mess into a constant. */
1599         critical_flags = 0;
1600 #ifdef SF_IMMUTABLE
1601         critical_flags |= SF_IMMUTABLE;
1602 #endif
1603 #ifdef UF_IMMUTABLE
1604         critical_flags |= UF_IMMUTABLE;
1605 #endif
1606 #ifdef SF_APPEND
1607         critical_flags |= SF_APPEND;
1608 #endif
1609 #ifdef UF_APPEND
1610         critical_flags |= UF_APPEND;
1611 #endif
1612 #ifdef EXT2_APPEND_FL
1613         critical_flags |= EXT2_APPEND_FL;
1614 #endif
1615 #ifdef EXT2_IMMUTABLE_FL
1616         critical_flags |= EXT2_IMMUTABLE_FL;
1617 #endif
1618
1619         if (a->todo & TODO_FFLAGS) {
1620                 archive_entry_fflags(a->entry, &set, &clear);
1621
1622                 /*
1623                  * The first test encourages the compiler to eliminate
1624                  * all of this if it's not necessary.
1625                  */
1626                 if ((critical_flags != 0)  &&  (set & critical_flags)) {
1627                         le = current_fixup(a, a->name);
1628                         le->fixup |= TODO_FFLAGS;
1629                         le->fflags_set = set;
1630                         /* Store the mode if it's not already there. */
1631                         if ((le->fixup & TODO_MODE) == 0)
1632                                 le->mode = mode;
1633                 } else {
1634                         r = set_fflags_platform(a, a->fd,
1635                             a->name, mode, set, clear);
1636                         if (r != ARCHIVE_OK)
1637                                 return (r);
1638                 }
1639         }
1640         return (ARCHIVE_OK);
1641 }
1642
1643
1644 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && !defined(__linux)
1645 static int
1646 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1647     mode_t mode, unsigned long set, unsigned long clear)
1648 {
1649         (void)mode; /* UNUSED */
1650         if (set == 0  && clear == 0)
1651                 return (ARCHIVE_OK);
1652
1653         /*
1654          * XXX Is the stat here really necessary?  Or can I just use
1655          * the 'set' flags directly?  In particular, I'm not sure
1656          * about the correct approach if we're overwriting an existing
1657          * file that already has flags on it. XXX
1658          */
1659         if (fd >= 0 && fstat(fd, &a->st) == 0)
1660                 a->pst = &a->st;
1661         else if (lstat(name, &a->st) == 0)
1662                 a->pst = &a->st;
1663         else {
1664                 archive_set_error(&a->archive, errno,
1665                     "Couldn't stat file");
1666                 return (ARCHIVE_WARN);
1667         }
1668
1669         a->st.st_flags &= ~clear;
1670         a->st.st_flags |= set;
1671 #ifdef HAVE_FCHFLAGS
1672         /* If platform has fchflags() and we were given an fd, use it. */
1673         if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
1674                 return (ARCHIVE_OK);
1675 #endif
1676         /*
1677          * If we can't use the fd to set the flags, we'll use the
1678          * pathname to set flags.  We prefer lchflags() but will use
1679          * chflags() if we must.
1680          */
1681 #ifdef HAVE_LCHFLAGS
1682         if (lchflags(name, a->st.st_flags) == 0)
1683                 return (ARCHIVE_OK);
1684 #elif defined(HAVE_CHFLAGS)
1685         if (S_ISLNK(a->st.st_mode)) {
1686                 archive_set_error(&a->archive, errno,
1687                     "Can't set file flags on symlink.");
1688                 return (ARCHIVE_WARN);
1689         }
1690         if (chflags(name, a->st.st_flags) == 0)
1691                 return (ARCHIVE_OK);
1692 #endif
1693         archive_set_error(&a->archive, errno,
1694             "Failed to set file flags");
1695         return (ARCHIVE_WARN);
1696 }
1697
1698 #elif defined(__linux) && defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS)
1699
1700 /*
1701  * Linux has flags too, but uses ioctl() to access them instead of
1702  * having a separate chflags() system call.
1703  */
1704 static int
1705 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1706     mode_t mode, unsigned long set, unsigned long clear)
1707 {
1708         int              ret;
1709         int              myfd = fd;
1710         unsigned long newflags, oldflags;
1711         unsigned long sf_mask = 0;
1712
1713         if (set == 0  && clear == 0)
1714                 return (ARCHIVE_OK);
1715         /* Only regular files and dirs can have flags. */
1716         if (!S_ISREG(mode) && !S_ISDIR(mode))
1717                 return (ARCHIVE_OK);
1718
1719         /* If we weren't given an fd, open it ourselves. */
1720         if (myfd < 0)
1721                 myfd = open(name, O_RDONLY|O_NONBLOCK);
1722         if (myfd < 0)
1723                 return (ARCHIVE_OK);
1724
1725         /*
1726          * Linux has no define for the flags that are only settable by
1727          * the root user.  This code may seem a little complex, but
1728          * there seem to be some Linux systems that lack these
1729          * defines. (?)  The code below degrades reasonably gracefully
1730          * if sf_mask is incomplete.
1731          */
1732 #ifdef EXT2_IMMUTABLE_FL
1733         sf_mask |= EXT2_IMMUTABLE_FL;
1734 #endif
1735 #ifdef EXT2_APPEND_FL
1736         sf_mask |= EXT2_APPEND_FL;
1737 #endif
1738         /*
1739          * XXX As above, this would be way simpler if we didn't have
1740          * to read the current flags from disk. XXX
1741          */
1742         ret = ARCHIVE_OK;
1743         /* Try setting the flags as given. */
1744         if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1745                 newflags = (oldflags & ~clear) | set;
1746                 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1747                         goto cleanup;
1748                 if (errno != EPERM)
1749                         goto fail;
1750         }
1751         /* If we couldn't set all the flags, try again with a subset. */
1752         if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1753                 newflags &= ~sf_mask;
1754                 oldflags &= sf_mask;
1755                 newflags |= oldflags;
1756                 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1757                         goto cleanup;
1758         }
1759         /* We couldn't set the flags, so report the failure. */
1760 fail:
1761         archive_set_error(&a->archive, errno,
1762             "Failed to set file flags");
1763         ret = ARCHIVE_WARN;
1764 cleanup:
1765         if (fd < 0)
1766                 close(myfd);
1767         return (ret);
1768 }
1769
1770 #else /* Not HAVE_CHFLAGS && Not __linux */
1771
1772 /*
1773  * Of course, some systems have neither BSD chflags() nor Linux' flags
1774  * support through ioctl().
1775  */
1776 static int
1777 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
1778     mode_t mode, unsigned long set, unsigned long clear)
1779 {
1780         (void)a; /* UNUSED */
1781         (void)fd; /* UNUSED */
1782         (void)name; /* UNUSED */
1783         (void)mode; /* UNUSED */
1784         (void)set; /* UNUSED */
1785         (void)clear; /* UNUSED */
1786         return (ARCHIVE_OK);
1787 }
1788
1789 #endif /* __linux */
1790
1791 #ifndef HAVE_POSIX_ACL
1792 /* Default empty function body to satisfy mainline code. */
1793 static int
1794 set_acls(struct archive_write_disk *a)
1795 {
1796         (void)a; /* UNUSED */
1797         return (ARCHIVE_OK);
1798 }
1799
1800 #else
1801
1802 /*
1803  * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
1804  */
1805 static int
1806 set_acls(struct archive_write_disk *a)
1807 {
1808         int              ret;
1809
1810         ret = set_acl(a, a->fd, a->entry, ACL_TYPE_ACCESS,
1811             ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
1812         if (ret != ARCHIVE_OK)
1813                 return (ret);
1814         ret = set_acl(a, a->fd, a->entry, ACL_TYPE_DEFAULT,
1815             ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
1816         return (ret);
1817 }
1818
1819
1820 static int
1821 set_acl(struct archive_write_disk *a, int fd, struct archive_entry *entry,
1822     acl_type_t acl_type, int ae_requested_type, const char *tname)
1823 {
1824         acl_t            acl;
1825         acl_entry_t      acl_entry;
1826         acl_permset_t    acl_permset;
1827         int              ret;
1828         int              ae_type, ae_permset, ae_tag, ae_id;
1829         uid_t            ae_uid;
1830         gid_t            ae_gid;
1831         const char      *ae_name;
1832         int              entries;
1833         const char      *name;
1834
1835         ret = ARCHIVE_OK;
1836         entries = archive_entry_acl_reset(entry, ae_requested_type);
1837         if (entries == 0)
1838                 return (ARCHIVE_OK);
1839         acl = acl_init(entries);
1840         while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
1841                    &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
1842                 acl_create_entry(&acl, &acl_entry);
1843
1844                 switch (ae_tag) {
1845                 case ARCHIVE_ENTRY_ACL_USER:
1846                         acl_set_tag_type(acl_entry, ACL_USER);
1847                         ae_uid = a->lookup_uid(a->lookup_uid_data,
1848                             ae_name, ae_id);
1849                         acl_set_qualifier(acl_entry, &ae_uid);
1850                         break;
1851                 case ARCHIVE_ENTRY_ACL_GROUP:
1852                         acl_set_tag_type(acl_entry, ACL_GROUP);
1853                         ae_gid = a->lookup_gid(a->lookup_gid_data,
1854                             ae_name, ae_id);
1855                         acl_set_qualifier(acl_entry, &ae_gid);
1856                         break;
1857                 case ARCHIVE_ENTRY_ACL_USER_OBJ:
1858                         acl_set_tag_type(acl_entry, ACL_USER_OBJ);
1859                         break;
1860                 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
1861                         acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
1862                         break;
1863                 case ARCHIVE_ENTRY_ACL_MASK:
1864                         acl_set_tag_type(acl_entry, ACL_MASK);
1865                         break;
1866                 case ARCHIVE_ENTRY_ACL_OTHER:
1867                         acl_set_tag_type(acl_entry, ACL_OTHER);
1868                         break;
1869                 default:
1870                         /* XXX */
1871                         break;
1872                 }
1873
1874                 acl_get_permset(acl_entry, &acl_permset);
1875                 acl_clear_perms(acl_permset);
1876                 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
1877                         acl_add_perm(acl_permset, ACL_EXECUTE);
1878                 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
1879                         acl_add_perm(acl_permset, ACL_WRITE);
1880                 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
1881                         acl_add_perm(acl_permset, ACL_READ);
1882         }
1883
1884         name = archive_entry_pathname(entry);
1885
1886         /* Try restoring the ACL through 'fd' if we can. */
1887 #if HAVE_ACL_SET_FD
1888         if (fd >= 0 && acl_type == ACL_TYPE_ACCESS && acl_set_fd(fd, acl) == 0)
1889                 ret = ARCHIVE_OK;
1890         else
1891 #else
1892 #if HAVE_ACL_SET_FD_NP
1893         if (fd >= 0 && acl_set_fd_np(fd, acl, acl_type) == 0)
1894                 ret = ARCHIVE_OK;
1895         else
1896 #endif
1897 #endif
1898         if (acl_set_file(name, acl_type, acl) != 0) {
1899                 archive_set_error(&a->archive, errno, "Failed to set %s acl", tname);
1900                 ret = ARCHIVE_WARN;
1901         }
1902         acl_free(acl);
1903         return (ret);
1904 }
1905 #endif
1906
1907 #if HAVE_LSETXATTR
1908 /*
1909  * Restore extended attributes -  Linux implementation
1910  */
1911 static int
1912 set_xattrs(struct archive_write_disk *a)
1913 {
1914         struct archive_entry *entry = a->entry;
1915         static int warning_done = 0;
1916         int ret = ARCHIVE_OK;
1917         int i = archive_entry_xattr_reset(entry);
1918
1919         while (i--) {
1920                 const char *name;
1921                 const void *value;
1922                 size_t size;
1923                 archive_entry_xattr_next(entry, &name, &value, &size);
1924                 if (name != NULL &&
1925                                 strncmp(name, "xfsroot.", 8) != 0 &&
1926                                 strncmp(name, "system.", 7) != 0) {
1927                         int e;
1928 #if HAVE_FSETXATTR
1929                         if (a->fd >= 0)
1930                                 e = fsetxattr(a->fd, name, value, size, 0);
1931                         else
1932 #endif
1933                         {
1934                                 e = lsetxattr(archive_entry_pathname(entry),
1935                                     name, value, size, 0);
1936                         }
1937                         if (e == -1) {
1938                                 if (errno == ENOTSUP) {
1939                                         if (!warning_done) {
1940                                                 warning_done = 1;
1941                                                 archive_set_error(&a->archive, errno,
1942                                                     "Cannot restore extended "
1943                                                     "attributes on this file "
1944                                                     "system");
1945                                         }
1946                                 } else
1947                                         archive_set_error(&a->archive, errno,
1948                                             "Failed to set extended attribute");
1949                                 ret = ARCHIVE_WARN;
1950                         }
1951                 } else {
1952                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1953                             "Invalid extended attribute encountered");
1954                         ret = ARCHIVE_WARN;
1955                 }
1956         }
1957         return (ret);
1958 }
1959 #else
1960 /*
1961  * Restore extended attributes - stub implementation for unsupported systems
1962  */
1963 static int
1964 set_xattrs(struct archive_write_disk *a)
1965 {
1966         static int warning_done = 0;
1967
1968         /* If there aren't any extended attributes, then it's okay not
1969          * to extract them, otherwise, issue a single warning. */
1970         if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
1971                 warning_done = 1;
1972                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1973                     "Cannot restore extended attributes on this system");
1974                 return (ARCHIVE_WARN);
1975         }
1976         /* Warning was already emitted; suppress further warnings. */
1977         return (ARCHIVE_OK);
1978 }
1979 #endif
1980
1981
1982 /*
1983  * Trivial implementations of gid/uid lookup functions.
1984  * These are normally overridden by the client, but these stub
1985  * versions ensure that we always have something that works.
1986  */
1987 static gid_t
1988 trivial_lookup_gid(void *private_data, const char *gname, gid_t gid)
1989 {
1990         (void)private_data; /* UNUSED */
1991         (void)gname; /* UNUSED */
1992         return (gid);
1993 }
1994
1995 static uid_t
1996 trivial_lookup_uid(void *private_data, const char *uname, uid_t uid)
1997 {
1998         (void)private_data; /* UNUSED */
1999         (void)uname; /* UNUSED */
2000         return (uid);
2001 }