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