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