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