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