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