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