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