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