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