]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libarchive/archive_write_disk.c
Merge from libarchive.googlecode.com: If we're
[FreeBSD/FreeBSD.git] / lib / libarchive / archive_write_disk.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD$");
29
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33 #ifdef HAVE_SYS_ACL_H
34 #include <sys/acl.h>
35 #endif
36 #ifdef HAVE_SYS_EXTATTR_H
37 #include <sys/extattr.h>
38 #endif
39 #ifdef HAVE_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         archive_string_free(&a->_name_data);
1282         archive_string_free(&a->archive.error_string);
1283         archive_string_free(&a->path_safe);
1284         free(a);
1285         return (ret);
1286 }
1287
1288 /*
1289  * Simple O(n log n) merge sort to order the fixup list.  In
1290  * particular, we want to restore dir timestamps depth-first.
1291  */
1292 static struct fixup_entry *
1293 sort_dir_list(struct fixup_entry *p)
1294 {
1295         struct fixup_entry *a, *b, *t;
1296
1297         if (p == NULL)
1298                 return (NULL);
1299         /* A one-item list is already sorted. */
1300         if (p->next == NULL)
1301                 return (p);
1302
1303         /* Step 1: split the list. */
1304         t = p;
1305         a = p->next->next;
1306         while (a != NULL) {
1307                 /* Step a twice, t once. */
1308                 a = a->next;
1309                 if (a != NULL)
1310                         a = a->next;
1311                 t = t->next;
1312         }
1313         /* Now, t is at the mid-point, so break the list here. */
1314         b = t->next;
1315         t->next = NULL;
1316         a = p;
1317
1318         /* Step 2: Recursively sort the two sub-lists. */
1319         a = sort_dir_list(a);
1320         b = sort_dir_list(b);
1321
1322         /* Step 3: Merge the returned lists. */
1323         /* Pick the first element for the merged list. */
1324         if (strcmp(a->name, b->name) > 0) {
1325                 t = p = a;
1326                 a = a->next;
1327         } else {
1328                 t = p = b;
1329                 b = b->next;
1330         }
1331
1332         /* Always put the later element on the list first. */
1333         while (a != NULL && b != NULL) {
1334                 if (strcmp(a->name, b->name) > 0) {
1335                         t->next = a;
1336                         a = a->next;
1337                 } else {
1338                         t->next = b;
1339                         b = b->next;
1340                 }
1341                 t = t->next;
1342         }
1343
1344         /* Only one list is non-empty, so just splice it on. */
1345         if (a != NULL)
1346                 t->next = a;
1347         if (b != NULL)
1348                 t->next = b;
1349
1350         return (p);
1351 }
1352
1353 /*
1354  * Returns a new, initialized fixup entry.
1355  *
1356  * TODO: Reduce the memory requirements for this list by using a tree
1357  * structure rather than a simple list of names.
1358  */
1359 static struct fixup_entry *
1360 new_fixup(struct archive_write_disk *a, const char *pathname)
1361 {
1362         struct fixup_entry *fe;
1363
1364         fe = (struct fixup_entry *)malloc(sizeof(struct fixup_entry));
1365         if (fe == NULL)
1366                 return (NULL);
1367         fe->next = a->fixup_list;
1368         a->fixup_list = fe;
1369         fe->fixup = 0;
1370         fe->name = strdup(pathname);
1371         return (fe);
1372 }
1373
1374 /*
1375  * Returns a fixup structure for the current entry.
1376  */
1377 static struct fixup_entry *
1378 current_fixup(struct archive_write_disk *a, const char *pathname)
1379 {
1380         if (a->current_fixup == NULL)
1381                 a->current_fixup = new_fixup(a, pathname);
1382         return (a->current_fixup);
1383 }
1384
1385 /* TODO: Make this work. */
1386 /*
1387  * TODO: The deep-directory support bypasses this; disable deep directory
1388  * support if we're doing symlink checks.
1389  */
1390 /*
1391  * TODO: Someday, integrate this with the deep dir support; they both
1392  * scan the path and both can be optimized by comparing against other
1393  * recent paths.
1394  */
1395 static int
1396 check_symlinks(struct archive_write_disk *a)
1397 {
1398         char *pn, *p;
1399         char c;
1400         int r;
1401         struct stat st;
1402
1403         /*
1404          * Guard against symlink tricks.  Reject any archive entry whose
1405          * destination would be altered by a symlink.
1406          */
1407         /* Whatever we checked last time doesn't need to be re-checked. */
1408         pn = a->name;
1409         p = a->path_safe.s;
1410         while ((*pn != '\0') && (*p == *pn))
1411                 ++p, ++pn;
1412         c = pn[0];
1413         /* Keep going until we've checked the entire name. */
1414         while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
1415                 /* Skip the next path element. */
1416                 while (*pn != '\0' && *pn != '/')
1417                         ++pn;
1418                 c = pn[0];
1419                 pn[0] = '\0';
1420                 /* Check that we haven't hit a symlink. */
1421                 r = lstat(a->name, &st);
1422                 if (r != 0) {
1423                         /* We've hit a dir that doesn't exist; stop now. */
1424                         if (errno == ENOENT)
1425                                 break;
1426                 } else if (S_ISLNK(st.st_mode)) {
1427                         if (c == '\0') {
1428                                 /*
1429                                  * Last element is symlink; remove it
1430                                  * so we can overwrite it with the
1431                                  * item being extracted.
1432                                  */
1433                                 if (unlink(a->name)) {
1434                                         archive_set_error(&a->archive, errno,
1435                                             "Could not remove symlink %s",
1436                                             a->name);
1437                                         pn[0] = c;
1438                                         return (ARCHIVE_FAILED);
1439                                 }
1440                                 a->pst = NULL;
1441                                 /*
1442                                  * Even if we did remove it, a warning
1443                                  * is in order.  The warning is silly,
1444                                  * though, if we're just replacing one
1445                                  * symlink with another symlink.
1446                                  */
1447                                 if (!S_ISLNK(a->mode)) {
1448                                         archive_set_error(&a->archive, 0,
1449                                             "Removing symlink %s",
1450                                             a->name);
1451                                 }
1452                                 /* Symlink gone.  No more problem! */
1453                                 pn[0] = c;
1454                                 return (0);
1455                         } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
1456                                 /* User asked us to remove problems. */
1457                                 if (unlink(a->name) != 0) {
1458                                         archive_set_error(&a->archive, 0,
1459                                             "Cannot remove intervening symlink %s",
1460                                             a->name);
1461                                         pn[0] = c;
1462                                         return (ARCHIVE_FAILED);
1463                                 }
1464                                 a->pst = NULL;
1465                         } else {
1466                                 archive_set_error(&a->archive, 0,
1467                                     "Cannot extract through symlink %s",
1468                                     a->name);
1469                                 pn[0] = c;
1470                                 return (ARCHIVE_FAILED);
1471                         }
1472                 }
1473         }
1474         pn[0] = c;
1475         /* We've checked and/or cleaned the whole path, so remember it. */
1476         archive_strcpy(&a->path_safe, a->name);
1477         return (ARCHIVE_OK);
1478 }
1479
1480 #if defined(_WIN32) || defined(__CYGWIN__)
1481 /*
1482  * 1. Convert a path separator from '\' to '/' .
1483  *    We shouldn't check multi-byte character directly because some
1484  *    character-set have been using the '\' character for a part of
1485  *    its multibyte character code.
1486  * 2. Replace unusable characters in Windows with underscore('_').
1487  * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
1488  */
1489 static void
1490 cleanup_pathname_win(struct archive_write_disk *a)
1491 {
1492         wchar_t wc;
1493         char *p;
1494         size_t alen, l;
1495
1496         alen = 0;
1497         l = 0;
1498         for (p = a->name; *p != '\0'; p++) {
1499                 ++alen;
1500                 if (*p == '\\')
1501                         l = 1;
1502                 /* Rewrite the path name if its character is a unusable. */
1503                 if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
1504                     *p == '<' || *p == '>' || *p == '|')
1505                         *p = '_';
1506         }
1507         if (alen == 0 || l == 0)
1508                 return;
1509         /*
1510          * Convert path separator.
1511          */
1512         p = a->name;
1513         while (*p != '\0' && alen) {
1514                 l = mbtowc(&wc, p, alen);
1515                 if (l == -1) {
1516                         while (*p != '\0') {
1517                                 if (*p == '\\')
1518                                         *p = '/';
1519                                 ++p;
1520                         }
1521                         break;
1522                 }
1523                 if (l == 1 && wc == L'\\')
1524                         *p = '/';
1525                 p += l;
1526                 alen -= l;
1527         }
1528 }
1529 #endif
1530
1531 /*
1532  * Canonicalize the pathname.  In particular, this strips duplicate
1533  * '/' characters, '.' elements, and trailing '/'.  It also raises an
1534  * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
1535  * set) any '..' in the path.
1536  */
1537 static int
1538 cleanup_pathname(struct archive_write_disk *a)
1539 {
1540         char *dest, *src;
1541         char separator = '\0';
1542
1543         dest = src = a->name;
1544         if (*src == '\0') {
1545                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1546                     "Invalid empty pathname");
1547                 return (ARCHIVE_FAILED);
1548         }
1549
1550 #if defined(_WIN32) || defined(__CYGWIN__)
1551         cleanup_pathname_win(a);
1552 #endif
1553         /* Skip leading '/'. */
1554         if (*src == '/')
1555                 separator = *src++;
1556
1557         /* Scan the pathname one element at a time. */
1558         for (;;) {
1559                 /* src points to first char after '/' */
1560                 if (src[0] == '\0') {
1561                         break;
1562                 } else if (src[0] == '/') {
1563                         /* Found '//', ignore second one. */
1564                         src++;
1565                         continue;
1566                 } else if (src[0] == '.') {
1567                         if (src[1] == '\0') {
1568                                 /* Ignore trailing '.' */
1569                                 break;
1570                         } else if (src[1] == '/') {
1571                                 /* Skip './'. */
1572                                 src += 2;
1573                                 continue;
1574                         } else if (src[1] == '.') {
1575                                 if (src[2] == '/' || src[2] == '\0') {
1576                                         /* Conditionally warn about '..' */
1577                                         if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
1578                                                 archive_set_error(&a->archive,
1579                                                     ARCHIVE_ERRNO_MISC,
1580                                                     "Path contains '..'");
1581                                                 return (ARCHIVE_FAILED);
1582                                         }
1583                                 }
1584                                 /*
1585                                  * Note: Under no circumstances do we
1586                                  * remove '..' elements.  In
1587                                  * particular, restoring
1588                                  * '/foo/../bar/' should create the
1589                                  * 'foo' dir as a side-effect.
1590                                  */
1591                         }
1592                 }
1593
1594                 /* Copy current element, including leading '/'. */
1595                 if (separator)
1596                         *dest++ = '/';
1597                 while (*src != '\0' && *src != '/') {
1598                         *dest++ = *src++;
1599                 }
1600
1601                 if (*src == '\0')
1602                         break;
1603
1604                 /* Skip '/' separator. */
1605                 separator = *src++;
1606         }
1607         /*
1608          * We've just copied zero or more path elements, not including the
1609          * final '/'.
1610          */
1611         if (dest == a->name) {
1612                 /*
1613                  * Nothing got copied.  The path must have been something
1614                  * like '.' or '/' or './' or '/././././/./'.
1615                  */
1616                 if (separator)
1617                         *dest++ = '/';
1618                 else
1619                         *dest++ = '.';
1620         }
1621         /* Terminate the result. */
1622         *dest = '\0';
1623         return (ARCHIVE_OK);
1624 }
1625
1626 /*
1627  * Create the parent directory of the specified path, assuming path
1628  * is already in mutable storage.
1629  */
1630 static int
1631 create_parent_dir(struct archive_write_disk *a, char *path)
1632 {
1633         char *slash;
1634         int r;
1635
1636         /* Remove tail element to obtain parent name. */
1637         slash = strrchr(path, '/');
1638         if (slash == NULL)
1639                 return (ARCHIVE_OK);
1640         *slash = '\0';
1641         r = create_dir(a, path);
1642         *slash = '/';
1643         return (r);
1644 }
1645
1646 /*
1647  * Create the specified dir, recursing to create parents as necessary.
1648  *
1649  * Returns ARCHIVE_OK if the path exists when we're done here.
1650  * Otherwise, returns ARCHIVE_FAILED.
1651  * Assumes path is in mutable storage; path is unchanged on exit.
1652  */
1653 static int
1654 create_dir(struct archive_write_disk *a, char *path)
1655 {
1656         struct stat st;
1657         struct fixup_entry *le;
1658         char *slash, *base;
1659         mode_t mode_final, mode;
1660         int r;
1661
1662         r = ARCHIVE_OK;
1663
1664         /* Check for special names and just skip them. */
1665         slash = strrchr(path, '/');
1666         if (slash == NULL)
1667                 base = path;
1668         else
1669                 base = slash + 1;
1670
1671         if (base[0] == '\0' ||
1672             (base[0] == '.' && base[1] == '\0') ||
1673             (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
1674                 /* Don't bother trying to create null path, '.', or '..'. */
1675                 if (slash != NULL) {
1676                         *slash = '\0';
1677                         r = create_dir(a, path);
1678                         *slash = '/';
1679                         return (r);
1680                 }
1681                 return (ARCHIVE_OK);
1682         }
1683
1684         /*
1685          * Yes, this should be stat() and not lstat().  Using lstat()
1686          * here loses the ability to extract through symlinks.  Also note
1687          * that this should not use the a->st cache.
1688          */
1689         if (stat(path, &st) == 0) {
1690                 if (S_ISDIR(st.st_mode))
1691                         return (ARCHIVE_OK);
1692                 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1693                         archive_set_error(&a->archive, EEXIST,
1694                             "Can't create directory '%s'", path);
1695                         return (ARCHIVE_FAILED);
1696                 }
1697                 if (unlink(path) != 0) {
1698                         archive_set_error(&a->archive, errno,
1699                             "Can't create directory '%s': "
1700                             "Conflicting file cannot be removed");
1701                         return (ARCHIVE_FAILED);
1702                 }
1703         } else if (errno != ENOENT && errno != ENOTDIR) {
1704                 /* Stat failed? */
1705                 archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
1706                 return (ARCHIVE_FAILED);
1707         } else if (slash != NULL) {
1708                 *slash = '\0';
1709                 r = create_dir(a, path);
1710                 *slash = '/';
1711                 if (r != ARCHIVE_OK)
1712                         return (r);
1713         }
1714
1715         /*
1716          * Mode we want for the final restored directory.  Per POSIX,
1717          * implicitly-created dirs must be created obeying the umask.
1718          * There's no mention whether this is different for privileged
1719          * restores (which the rest of this code handles by pretending
1720          * umask=0).  I've chosen here to always obey the user's umask for
1721          * implicit dirs, even if _EXTRACT_PERM was specified.
1722          */
1723         mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
1724         /* Mode we want on disk during the restore process. */
1725         mode = mode_final;
1726         mode |= MINIMUM_DIR_MODE;
1727         mode &= MAXIMUM_DIR_MODE;
1728         if (mkdir(path, mode) == 0) {
1729                 if (mode != mode_final) {
1730                         le = new_fixup(a, path);
1731                         le->fixup |=TODO_MODE_BASE;
1732                         le->mode = mode_final;
1733                 }
1734                 return (ARCHIVE_OK);
1735         }
1736
1737         /*
1738          * Without the following check, a/b/../b/c/d fails at the
1739          * second visit to 'b', so 'd' can't be created.  Note that we
1740          * don't add it to the fixup list here, as it's already been
1741          * added.
1742          */
1743         if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1744                 return (ARCHIVE_OK);
1745
1746         archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
1747             path);
1748         return (ARCHIVE_FAILED);
1749 }
1750
1751 /*
1752  * Note: Although we can skip setting the user id if the desired user
1753  * id matches the current user, we cannot skip setting the group, as
1754  * many systems set the gid based on the containing directory.  So
1755  * we have to perform a chown syscall if we want to set the SGID
1756  * bit.  (The alternative is to stat() and then possibly chown(); it's
1757  * more efficient to skip the stat() and just always chown().)  Note
1758  * that a successful chown() here clears the TODO_SGID_CHECK bit, which
1759  * allows set_mode to skip the stat() check for the GID.
1760  */
1761 static int
1762 set_ownership(struct archive_write_disk *a)
1763 {
1764 #ifndef __CYGWIN__
1765 /* unfortunately, on win32 there is no 'root' user with uid 0,
1766    so we just have to try the chown and see if it works */
1767
1768         /* If we know we can't change it, don't bother trying. */
1769         if (a->user_uid != 0  &&  a->user_uid != a->uid) {
1770                 archive_set_error(&a->archive, errno,
1771                     "Can't set UID=%d", a->uid);
1772                 return (ARCHIVE_WARN);
1773         }
1774 #endif
1775
1776 #ifdef HAVE_FCHOWN
1777         /* If we have an fd, we can avoid a race. */
1778         if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
1779                 /* We've set owner and know uid/gid are correct. */
1780                 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1781                 return (ARCHIVE_OK);
1782         }
1783 #endif
1784
1785         /* We prefer lchown() but will use chown() if that's all we have. */
1786         /* Of course, if we have neither, this will always fail. */
1787 #ifdef HAVE_LCHOWN
1788         if (lchown(a->name, a->uid, a->gid) == 0) {
1789                 /* We've set owner and know uid/gid are correct. */
1790                 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1791                 return (ARCHIVE_OK);
1792         }
1793 #elif HAVE_CHOWN
1794         if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
1795                 /* We've set owner and know uid/gid are correct. */
1796                 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1797                 return (ARCHIVE_OK);
1798         }
1799 #endif
1800
1801         archive_set_error(&a->archive, errno,
1802             "Can't set user=%d/group=%d for %s", a->uid, a->gid,
1803             a->name);
1804         return (ARCHIVE_WARN);
1805 }
1806
1807 #ifdef HAVE_UTIMES
1808 /*
1809  * The utimes()-family functions provide high resolution and
1810  * a way to set time on an fd or a symlink.  We prefer them
1811  * when they're available.
1812  */
1813 static int
1814 set_time(int fd, int mode, const char *name,
1815     time_t atime, long atime_nsec,
1816     time_t mtime, long mtime_nsec)
1817 {
1818 #if defined(_WIN32) && !defined(__CYGWIN__)
1819         struct __timeval times[2];
1820 #else
1821         struct timeval times[2];
1822 #endif
1823
1824         times[0].tv_sec = atime;
1825         times[0].tv_usec = atime_nsec / 1000;
1826         times[1].tv_sec = mtime;
1827         times[1].tv_usec = mtime_nsec / 1000;
1828
1829 #ifdef HAVE_FUTIMES
1830         if (fd >= 0)
1831                 return (futimes(fd, times));
1832 #else
1833         (void)fd; /* UNUSED */
1834 #endif
1835 #ifdef HAVE_LUTIMES
1836         (void)mode; /* UNUSED */
1837         return (lutimes(name, times));
1838 #else
1839         if (S_ISLNK(mode))
1840                 return (0);
1841         return (utimes(name, times));
1842 #endif
1843 }
1844 #elif defined(HAVE_UTIME)
1845 /*
1846  * utime() is an older, more standard interface that we'll use
1847  * if utimes() isn't available.
1848  */
1849 static int
1850 set_time(int fd, int mode, const char *name,
1851     time_t atime, long atime_nsec,
1852     time_t mtime, long mtime_nsec)
1853 {
1854         struct utimbuf times;
1855         (void)fd; /* UNUSED */
1856         (void)name; /* UNUSED */
1857         (void)atime_nsec; /* UNUSED */
1858         (void)mtime_nsec; /* UNUSED */
1859         times.actime = atime;
1860         times.modtime = mtime;
1861         if (S_ISLNK(mode))
1862                 return (ARCHIVE_OK);
1863         return (utime(name, &times));
1864 }
1865 #else
1866 static int
1867 set_time(int fd, int mode, const char *name,
1868     time_t atime, long atime_nsec,
1869     time_t mtime, long mtime_nsec)
1870 {
1871         return (ARCHIVE_WARN);
1872 }
1873 #endif
1874
1875 static int
1876 set_times(struct archive_write_disk *a)
1877 {
1878         time_t atime = a->start_time, mtime = a->start_time;
1879         long atime_nsec = 0, mtime_nsec = 0;
1880
1881         /* If no time was provided, we're done. */
1882         if (!archive_entry_atime_is_set(a->entry)
1883 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
1884             && !archive_entry_birthtime_is_set(a->entry)
1885 #endif
1886             && !archive_entry_mtime_is_set(a->entry))
1887                 return (ARCHIVE_OK);
1888
1889         /* If no atime was specified, use start time instead. */
1890         /* In theory, it would be marginally more correct to use
1891          * time(NULL) here, but that would cost us an extra syscall
1892          * for little gain. */
1893         if (archive_entry_atime_is_set(a->entry)) {
1894                 atime = archive_entry_atime(a->entry);
1895                 atime_nsec = archive_entry_atime_nsec(a->entry);
1896         }
1897
1898         /*
1899          * If you have struct stat.st_birthtime, we assume BSD birthtime
1900          * semantics, in which {f,l,}utimes() updates birthtime to earliest
1901          * mtime.  So we set the time twice, first using the birthtime,
1902          * then using the mtime.
1903          */
1904 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
1905         /* If birthtime is set, flush that through to disk first. */
1906         if (archive_entry_birthtime_is_set(a->entry))
1907                 if (set_time(a->fd, a->mode, a->name, atime, atime_nsec,
1908                         archive_entry_birthtime(a->entry),
1909                         archive_entry_birthtime_nsec(a->entry))) {
1910                         archive_set_error(&a->archive, errno,
1911                             "Can't update time for %s",
1912                             a->name);
1913                         return (ARCHIVE_WARN);
1914                 }
1915 #endif
1916
1917         if (archive_entry_mtime_is_set(a->entry)) {
1918                 mtime = archive_entry_mtime(a->entry);
1919                 mtime_nsec = archive_entry_mtime_nsec(a->entry);
1920         }
1921         if (set_time(a->fd, a->mode, a->name,
1922                 atime, atime_nsec, mtime, mtime_nsec)) {
1923                 archive_set_error(&a->archive, errno,
1924                     "Can't update time for %s",
1925                     a->name);
1926                 return (ARCHIVE_WARN);
1927         }
1928
1929         /*
1930          * Note: POSIX does not provide a portable way to restore ctime.
1931          * (Apart from resetting the system clock, which is distasteful.)
1932          * So, any restoration of ctime will necessarily be OS-specific.
1933          */
1934
1935         return (ARCHIVE_OK);
1936 }
1937
1938 static int
1939 set_mode(struct archive_write_disk *a, int mode)
1940 {
1941         int r = ARCHIVE_OK;
1942         mode &= 07777; /* Strip off file type bits. */
1943
1944         if (a->todo & TODO_SGID_CHECK) {
1945                 /*
1946                  * If we don't know the GID is right, we must stat()
1947                  * to verify it.  We can't just check the GID of this
1948                  * process, since systems sometimes set GID from
1949                  * the enclosing dir or based on ACLs.
1950                  */
1951                 if ((r = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
1952                         return (r);
1953                 if (a->pst->st_gid != a->gid) {
1954                         mode &= ~ S_ISGID;
1955 #if !defined(_WIN32) || defined(__CYGWIN__)
1956                         if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1957                                 /*
1958                                  * This is only an error if you
1959                                  * requested owner restore.  If you
1960                                  * didn't, we'll try to restore
1961                                  * sgid/suid, but won't consider it a
1962                                  * problem if we can't.
1963                                  */
1964                                 archive_set_error(&a->archive, -1,
1965                                     "Can't restore SGID bit");
1966                                 r = ARCHIVE_WARN;
1967                         }
1968 #endif
1969                 }
1970                 /* While we're here, double-check the UID. */
1971                 if (a->pst->st_uid != a->uid
1972                     && (a->todo & TODO_SUID)) {
1973                         mode &= ~ S_ISUID;
1974 #if !defined(_WIN32) || defined(__CYGWIN__)
1975                         if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1976                                 archive_set_error(&a->archive, -1,
1977                                     "Can't restore SUID bit");
1978                                 r = ARCHIVE_WARN;
1979                         }
1980 #endif
1981                 }
1982                 a->todo &= ~TODO_SGID_CHECK;
1983                 a->todo &= ~TODO_SUID_CHECK;
1984         } else if (a->todo & TODO_SUID_CHECK) {
1985                 /*
1986                  * If we don't know the UID is right, we can just check
1987                  * the user, since all systems set the file UID from
1988                  * the process UID.
1989                  */
1990                 if (a->user_uid != a->uid) {
1991                         mode &= ~ S_ISUID;
1992 #if !defined(_WIN32) || defined(__CYGWIN__)
1993                         if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1994                                 archive_set_error(&a->archive, -1,
1995                                     "Can't make file SUID");
1996                                 r = ARCHIVE_WARN;
1997                         }
1998 #endif
1999                 }
2000                 a->todo &= ~TODO_SUID_CHECK;
2001         }
2002
2003         if (S_ISLNK(a->mode)) {
2004 #ifdef HAVE_LCHMOD
2005                 /*
2006                  * If this is a symlink, use lchmod().  If the
2007                  * platform doesn't support lchmod(), just skip it.  A
2008                  * platform that doesn't provide a way to set
2009                  * permissions on symlinks probably ignores
2010                  * permissions on symlinks, so a failure here has no
2011                  * impact.
2012                  */
2013                 if (lchmod(a->name, mode) != 0) {
2014                         archive_set_error(&a->archive, errno,
2015                             "Can't set permissions to 0%o", (int)mode);
2016                         r = ARCHIVE_WARN;
2017                 }
2018 #endif
2019         } else if (!S_ISDIR(a->mode)) {
2020                 /*
2021                  * If it's not a symlink and not a dir, then use
2022                  * fchmod() or chmod(), depending on whether we have
2023                  * an fd.  Dirs get their perms set during the
2024                  * post-extract fixup, which is handled elsewhere.
2025                  */
2026 #ifdef HAVE_FCHMOD
2027                 if (a->fd >= 0) {
2028                         if (fchmod(a->fd, mode) != 0) {
2029                                 archive_set_error(&a->archive, errno,
2030                                     "Can't set permissions to 0%o", (int)mode);
2031                                 r = ARCHIVE_WARN;
2032                         }
2033                 } else
2034 #endif
2035                         /* If this platform lacks fchmod(), then
2036                          * we'll just use chmod(). */
2037                         if (chmod(a->name, mode) != 0) {
2038                                 archive_set_error(&a->archive, errno,
2039                                     "Can't set permissions to 0%o", (int)mode);
2040                                 r = ARCHIVE_WARN;
2041                         }
2042         }
2043         return (r);
2044 }
2045
2046 static int
2047 set_fflags(struct archive_write_disk *a)
2048 {
2049         struct fixup_entry *le;
2050         unsigned long   set, clear;
2051         int             r;
2052         int             critical_flags;
2053         mode_t          mode = archive_entry_mode(a->entry);
2054
2055         /*
2056          * Make 'critical_flags' hold all file flags that can't be
2057          * immediately restored.  For example, on BSD systems,
2058          * SF_IMMUTABLE prevents hardlinks from being created, so
2059          * should not be set until after any hardlinks are created.  To
2060          * preserve some semblance of portability, this uses #ifdef
2061          * extensively.  Ugly, but it works.
2062          *
2063          * Yes, Virginia, this does create a security race.  It's mitigated
2064          * somewhat by the practice of creating dirs 0700 until the extract
2065          * is done, but it would be nice if we could do more than that.
2066          * People restoring critical file systems should be wary of
2067          * other programs that might try to muck with files as they're
2068          * being restored.
2069          */
2070         /* Hopefully, the compiler will optimize this mess into a constant. */
2071         critical_flags = 0;
2072 #ifdef SF_IMMUTABLE
2073         critical_flags |= SF_IMMUTABLE;
2074 #endif
2075 #ifdef UF_IMMUTABLE
2076         critical_flags |= UF_IMMUTABLE;
2077 #endif
2078 #ifdef SF_APPEND
2079         critical_flags |= SF_APPEND;
2080 #endif
2081 #ifdef UF_APPEND
2082         critical_flags |= UF_APPEND;
2083 #endif
2084 #ifdef EXT2_APPEND_FL
2085         critical_flags |= EXT2_APPEND_FL;
2086 #endif
2087 #ifdef EXT2_IMMUTABLE_FL
2088         critical_flags |= EXT2_IMMUTABLE_FL;
2089 #endif
2090
2091         if (a->todo & TODO_FFLAGS) {
2092                 archive_entry_fflags(a->entry, &set, &clear);
2093
2094                 /*
2095                  * The first test encourages the compiler to eliminate
2096                  * all of this if it's not necessary.
2097                  */
2098                 if ((critical_flags != 0)  &&  (set & critical_flags)) {
2099                         le = current_fixup(a, a->name);
2100                         le->fixup |= TODO_FFLAGS;
2101                         le->fflags_set = set;
2102                         /* Store the mode if it's not already there. */
2103                         if ((le->fixup & TODO_MODE) == 0)
2104                                 le->mode = mode;
2105                 } else {
2106                         r = set_fflags_platform(a, a->fd,
2107                             a->name, mode, set, clear);
2108                         if (r != ARCHIVE_OK)
2109                                 return (r);
2110                 }
2111         }
2112         return (ARCHIVE_OK);
2113 }
2114
2115
2116 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
2117 /*
2118  * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
2119  */
2120 static int
2121 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2122     mode_t mode, unsigned long set, unsigned long clear)
2123 {
2124         int r;
2125
2126         (void)mode; /* UNUSED */
2127         if (set == 0  && clear == 0)
2128                 return (ARCHIVE_OK);
2129
2130         /*
2131          * XXX Is the stat here really necessary?  Or can I just use
2132          * the 'set' flags directly?  In particular, I'm not sure
2133          * about the correct approach if we're overwriting an existing
2134          * file that already has flags on it. XXX
2135          */
2136         if ((r = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
2137                 return (r);
2138
2139         a->st.st_flags &= ~clear;
2140         a->st.st_flags |= set;
2141 #ifdef HAVE_FCHFLAGS
2142         /* If platform has fchflags() and we were given an fd, use it. */
2143         if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
2144                 return (ARCHIVE_OK);
2145 #endif
2146         /*
2147          * If we can't use the fd to set the flags, we'll use the
2148          * pathname to set flags.  We prefer lchflags() but will use
2149          * chflags() if we must.
2150          */
2151 #ifdef HAVE_LCHFLAGS
2152         if (lchflags(name, a->st.st_flags) == 0)
2153                 return (ARCHIVE_OK);
2154 #elif defined(HAVE_CHFLAGS)
2155         if (S_ISLNK(a->st.st_mode)) {
2156                 archive_set_error(&a->archive, errno,
2157                     "Can't set file flags on symlink.");
2158                 return (ARCHIVE_WARN);
2159         }
2160         if (chflags(name, a->st.st_flags) == 0)
2161                 return (ARCHIVE_OK);
2162 #endif
2163         archive_set_error(&a->archive, errno,
2164             "Failed to set file flags");
2165         return (ARCHIVE_WARN);
2166 }
2167
2168 #elif defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS)
2169 /*
2170  * Linux uses ioctl() to read and write file flags.
2171  */
2172 static int
2173 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2174     mode_t mode, unsigned long set, unsigned long clear)
2175 {
2176         int              ret;
2177         int              myfd = fd;
2178         unsigned long newflags, oldflags;
2179         unsigned long sf_mask = 0;
2180
2181         if (set == 0  && clear == 0)
2182                 return (ARCHIVE_OK);
2183         /* Only regular files and dirs can have flags. */
2184         if (!S_ISREG(mode) && !S_ISDIR(mode))
2185                 return (ARCHIVE_OK);
2186
2187         /* If we weren't given an fd, open it ourselves. */
2188         if (myfd < 0)
2189                 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY);
2190         if (myfd < 0)
2191                 return (ARCHIVE_OK);
2192
2193         /*
2194          * Linux has no define for the flags that are only settable by
2195          * the root user.  This code may seem a little complex, but
2196          * there seem to be some Linux systems that lack these
2197          * defines. (?)  The code below degrades reasonably gracefully
2198          * if sf_mask is incomplete.
2199          */
2200 #ifdef EXT2_IMMUTABLE_FL
2201         sf_mask |= EXT2_IMMUTABLE_FL;
2202 #endif
2203 #ifdef EXT2_APPEND_FL
2204         sf_mask |= EXT2_APPEND_FL;
2205 #endif
2206         /*
2207          * XXX As above, this would be way simpler if we didn't have
2208          * to read the current flags from disk. XXX
2209          */
2210         ret = ARCHIVE_OK;
2211         /* Try setting the flags as given. */
2212         if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
2213                 newflags = (oldflags & ~clear) | set;
2214                 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
2215                         goto cleanup;
2216                 if (errno != EPERM)
2217                         goto fail;
2218         }
2219         /* If we couldn't set all the flags, try again with a subset. */
2220         if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
2221                 newflags &= ~sf_mask;
2222                 oldflags &= sf_mask;
2223                 newflags |= oldflags;
2224                 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
2225                         goto cleanup;
2226         }
2227         /* We couldn't set the flags, so report the failure. */
2228 fail:
2229         archive_set_error(&a->archive, errno,
2230             "Failed to set file flags");
2231         ret = ARCHIVE_WARN;
2232 cleanup:
2233         if (fd < 0)
2234                 close(myfd);
2235         return (ret);
2236 }
2237
2238 #else
2239
2240 /*
2241  * Of course, some systems have neither BSD chflags() nor Linux' flags
2242  * support through ioctl().
2243  */
2244 static int
2245 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2246     mode_t mode, unsigned long set, unsigned long clear)
2247 {
2248         (void)a; /* UNUSED */
2249         (void)fd; /* UNUSED */
2250         (void)name; /* UNUSED */
2251         (void)mode; /* UNUSED */
2252         (void)set; /* UNUSED */
2253         (void)clear; /* UNUSED */
2254         return (ARCHIVE_OK);
2255 }
2256
2257 #endif /* __linux */
2258
2259 #ifndef HAVE_POSIX_ACL
2260 /* Default empty function body to satisfy mainline code. */
2261 static int
2262 set_acls(struct archive_write_disk *a)
2263 {
2264         (void)a; /* UNUSED */
2265         return (ARCHIVE_OK);
2266 }
2267
2268 #else
2269
2270 /*
2271  * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
2272  */
2273 static int
2274 set_acls(struct archive_write_disk *a)
2275 {
2276         int              ret;
2277
2278         ret = set_acl(a, a->fd, a->entry, ACL_TYPE_ACCESS,
2279             ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
2280         if (ret != ARCHIVE_OK)
2281                 return (ret);
2282         ret = set_acl(a, a->fd, a->entry, ACL_TYPE_DEFAULT,
2283             ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
2284         return (ret);
2285 }
2286
2287
2288 static int
2289 set_acl(struct archive_write_disk *a, int fd, struct archive_entry *entry,
2290     acl_type_t acl_type, int ae_requested_type, const char *tname)
2291 {
2292         acl_t            acl;
2293         acl_entry_t      acl_entry;
2294         acl_permset_t    acl_permset;
2295         int              ret;
2296         int              ae_type, ae_permset, ae_tag, ae_id;
2297         uid_t            ae_uid;
2298         gid_t            ae_gid;
2299         const char      *ae_name;
2300         int              entries;
2301         const char      *name;
2302
2303         ret = ARCHIVE_OK;
2304         entries = archive_entry_acl_reset(entry, ae_requested_type);
2305         if (entries == 0)
2306                 return (ARCHIVE_OK);
2307         acl = acl_init(entries);
2308         while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
2309                    &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
2310                 acl_create_entry(&acl, &acl_entry);
2311
2312                 switch (ae_tag) {
2313                 case ARCHIVE_ENTRY_ACL_USER:
2314                         acl_set_tag_type(acl_entry, ACL_USER);
2315                         ae_uid = a->lookup_uid(a->lookup_uid_data,
2316                             ae_name, ae_id);
2317                         acl_set_qualifier(acl_entry, &ae_uid);
2318                         break;
2319                 case ARCHIVE_ENTRY_ACL_GROUP:
2320                         acl_set_tag_type(acl_entry, ACL_GROUP);
2321                         ae_gid = a->lookup_gid(a->lookup_gid_data,
2322                             ae_name, ae_id);
2323                         acl_set_qualifier(acl_entry, &ae_gid);
2324                         break;
2325                 case ARCHIVE_ENTRY_ACL_USER_OBJ:
2326                         acl_set_tag_type(acl_entry, ACL_USER_OBJ);
2327                         break;
2328                 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
2329                         acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
2330                         break;
2331                 case ARCHIVE_ENTRY_ACL_MASK:
2332                         acl_set_tag_type(acl_entry, ACL_MASK);
2333                         break;
2334                 case ARCHIVE_ENTRY_ACL_OTHER:
2335                         acl_set_tag_type(acl_entry, ACL_OTHER);
2336                         break;
2337                 default:
2338                         /* XXX */
2339                         break;
2340                 }
2341
2342                 acl_get_permset(acl_entry, &acl_permset);
2343                 acl_clear_perms(acl_permset);
2344                 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
2345                         acl_add_perm(acl_permset, ACL_EXECUTE);
2346                 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
2347                         acl_add_perm(acl_permset, ACL_WRITE);
2348                 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
2349                         acl_add_perm(acl_permset, ACL_READ);
2350         }
2351
2352         name = archive_entry_pathname(entry);
2353
2354         /* Try restoring the ACL through 'fd' if we can. */
2355 #if HAVE_ACL_SET_FD
2356         if (fd >= 0 && acl_type == ACL_TYPE_ACCESS && acl_set_fd(fd, acl) == 0)
2357                 ret = ARCHIVE_OK;
2358         else
2359 #else
2360 #if HAVE_ACL_SET_FD_NP
2361         if (fd >= 0 && acl_set_fd_np(fd, acl, acl_type) == 0)
2362                 ret = ARCHIVE_OK;
2363         else
2364 #endif
2365 #endif
2366         if (acl_set_file(name, acl_type, acl) != 0) {
2367                 archive_set_error(&a->archive, errno, "Failed to set %s acl", tname);
2368                 ret = ARCHIVE_WARN;
2369         }
2370         acl_free(acl);
2371         return (ret);
2372 }
2373 #endif
2374
2375 #if HAVE_LSETXATTR
2376 /*
2377  * Restore extended attributes -  Linux implementation
2378  */
2379 static int
2380 set_xattrs(struct archive_write_disk *a)
2381 {
2382         struct archive_entry *entry = a->entry;
2383         static int warning_done = 0;
2384         int ret = ARCHIVE_OK;
2385         int i = archive_entry_xattr_reset(entry);
2386
2387         while (i--) {
2388                 const char *name;
2389                 const void *value;
2390                 size_t size;
2391                 archive_entry_xattr_next(entry, &name, &value, &size);
2392                 if (name != NULL &&
2393                                 strncmp(name, "xfsroot.", 8) != 0 &&
2394                                 strncmp(name, "system.", 7) != 0) {
2395                         int e;
2396 #if HAVE_FSETXATTR
2397                         if (a->fd >= 0)
2398                                 e = fsetxattr(a->fd, name, value, size, 0);
2399                         else
2400 #endif
2401                         {
2402                                 e = lsetxattr(archive_entry_pathname(entry),
2403                                     name, value, size, 0);
2404                         }
2405                         if (e == -1) {
2406                                 if (errno == ENOTSUP) {
2407                                         if (!warning_done) {
2408                                                 warning_done = 1;
2409                                                 archive_set_error(&a->archive, errno,
2410                                                     "Cannot restore extended "
2411                                                     "attributes on this file "
2412                                                     "system");
2413                                         }
2414                                 } else
2415                                         archive_set_error(&a->archive, errno,
2416                                             "Failed to set extended attribute");
2417                                 ret = ARCHIVE_WARN;
2418                         }
2419                 } else {
2420                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2421                             "Invalid extended attribute encountered");
2422                         ret = ARCHIVE_WARN;
2423                 }
2424         }
2425         return (ret);
2426 }
2427 #elif HAVE_EXTATTR_SET_FILE
2428 /*
2429  * Restore extended attributes -  FreeBSD implementation
2430  */
2431 static int
2432 set_xattrs(struct archive_write_disk *a)
2433 {
2434         struct archive_entry *entry = a->entry;
2435         static int warning_done = 0;
2436         int ret = ARCHIVE_OK;
2437         int i = archive_entry_xattr_reset(entry);
2438
2439         while (i--) {
2440                 const char *name;
2441                 const void *value;
2442                 size_t size;
2443                 archive_entry_xattr_next(entry, &name, &value, &size);
2444                 if (name != NULL) {
2445                         int e;
2446                         int namespace;
2447
2448                         if (strncmp(name, "user.", 5) == 0) {
2449                                 /* "user." attributes go to user namespace */
2450                                 name += 5;
2451                                 namespace = EXTATTR_NAMESPACE_USER;
2452                         } else {
2453                                 /* Warn about other extended attributes. */
2454                                 archive_set_error(&a->archive,
2455                                     ARCHIVE_ERRNO_FILE_FORMAT,
2456                                     "Can't restore extended attribute ``%s''",
2457                                     name);
2458                                 ret = ARCHIVE_WARN;
2459                                 continue;
2460                         }
2461                         errno = 0;
2462 #if HAVE_EXTATTR_SET_FD
2463                         if (a->fd >= 0)
2464                                 e = extattr_set_fd(a->fd, namespace, name, value, size);
2465                         else
2466 #endif
2467                         /* TODO: should we use extattr_set_link() instead? */
2468                         {
2469                                 e = extattr_set_file(archive_entry_pathname(entry),
2470                                     namespace, name, value, size);
2471                         }
2472                         if (e != (int)size) {
2473                                 if (errno == ENOTSUP) {
2474                                         if (!warning_done) {
2475                                                 warning_done = 1;
2476                                                 archive_set_error(&a->archive, errno,
2477                                                     "Cannot restore extended "
2478                                                     "attributes on this file "
2479                                                     "system");
2480                                         }
2481                                 } else {
2482                                         archive_set_error(&a->archive, errno,
2483                                             "Failed to set extended attribute");
2484                                 }
2485
2486                                 ret = ARCHIVE_WARN;
2487                         }
2488                 }
2489         }
2490         return (ret);
2491 }
2492 #else
2493 /*
2494  * Restore extended attributes - stub implementation for unsupported systems
2495  */
2496 static int
2497 set_xattrs(struct archive_write_disk *a)
2498 {
2499         static int warning_done = 0;
2500
2501         /* If there aren't any extended attributes, then it's okay not
2502          * to extract them, otherwise, issue a single warning. */
2503         if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
2504                 warning_done = 1;
2505                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2506                     "Cannot restore extended attributes on this system");
2507                 return (ARCHIVE_WARN);
2508         }
2509         /* Warning was already emitted; suppress further warnings. */
2510         return (ARCHIVE_OK);
2511 }
2512 #endif
2513
2514
2515 /*
2516  * Trivial implementations of gid/uid lookup functions.
2517  * These are normally overridden by the client, but these stub
2518  * versions ensure that we always have something that works.
2519  */
2520 static gid_t
2521 trivial_lookup_gid(void *private_data, const char *gname, gid_t gid)
2522 {
2523         (void)private_data; /* UNUSED */
2524         (void)gname; /* UNUSED */
2525         return (gid);
2526 }
2527
2528 static uid_t
2529 trivial_lookup_uid(void *private_data, const char *uname, uid_t uid)
2530 {
2531         (void)private_data; /* UNUSED */
2532         (void)uname; /* UNUSED */
2533         return (uid);
2534 }
2535
2536 /*
2537  * Test if file on disk is older than entry.
2538  */
2539 static int
2540 older(struct stat *st, struct archive_entry *entry)
2541 {
2542         /* First, test the seconds and return if we have a definite answer. */
2543         /* Definitely older. */
2544         if (st->st_mtime < archive_entry_mtime(entry))
2545                 return (1);
2546         /* Definitely younger. */
2547         if (st->st_mtime > archive_entry_mtime(entry))
2548                 return (0);
2549         /* If this platform supports fractional seconds, try those. */
2550 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
2551         /* Definitely older. */
2552         if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
2553                 return (1);
2554 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
2555         /* Definitely older. */
2556         if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
2557                 return (1);
2558 #elif HAVE_STRUCT_STAT_ST_MTIME_N
2559         /* older. */
2560         if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
2561                 return (1);
2562 #elif HAVE_STRUCT_STAT_ST_UMTIME
2563         /* older. */
2564         if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
2565                 return (1);
2566 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
2567         /* older. */
2568         if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
2569                 return (1);
2570 #else
2571         /* This system doesn't have high-res timestamps. */
2572 #endif
2573         /* Same age or newer, so not older. */
2574         return (0);
2575 }