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