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