1 /*-
2 * Copyright (c) 2003-2010 Tim Kientzle
3 * Copyright (c) 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_ACL_H
36 #include <sys/acl.h>
37 #endif
38 #ifdef HAVE_SYS_EXTATTR_H
39 #include <sys/extattr.h>
40 #endif
41 #if HAVE_SYS_XATTR_H
42 #include <sys/xattr.h>
43 #elif HAVE_ATTR_XATTR_H
44 #include <attr/xattr.h>
45 #endif
46 #ifdef HAVE_SYS_EA_H
47 #include <sys/ea.h>
48 #endif
49 #ifdef HAVE_SYS_IOCTL_H
50 #include <sys/ioctl.h>
51 #endif
52 #ifdef HAVE_SYS_STAT_H
53 #include <sys/stat.h>
54 #endif
55 #ifdef HAVE_SYS_TIME_H
56 #include <sys/time.h>
57 #endif
58 #ifdef HAVE_SYS_UTIME_H
59 #include <sys/utime.h>
60 #endif
61 #ifdef HAVE_COPYFILE_H
62 #include <copyfile.h>
63 #endif
64 #ifdef HAVE_ERRNO_H
65 #include <errno.h>
66 #endif
67 #ifdef HAVE_FCNTL_H
68 #include <fcntl.h>
69 #endif
70 #ifdef HAVE_GRP_H
71 #include <grp.h>
72 #endif
73 #ifdef HAVE_LANGINFO_H
74 #include <langinfo.h>
75 #endif
76 #ifdef HAVE_LINUX_FS_H
77 #include <linux/fs.h> /* for Linux file flags */
78 #endif
79 /*
80 * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
81 * As the include guards don't agree, the order of include is important.
82 */
83 #ifdef HAVE_LINUX_EXT2_FS_H
84 #include <linux/ext2_fs.h> /* for Linux file flags */
85 #endif
86 #if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
87 #include <ext2fs/ext2_fs.h> /* Linux file flags, broken on Cygwin */
88 #endif
89 #ifdef HAVE_LIMITS_H
90 #include <limits.h>
91 #endif
92 #ifdef HAVE_PWD_H
93 #include <pwd.h>
94 #endif
95 #include <stdio.h>
96 #ifdef HAVE_STDLIB_H
97 #include <stdlib.h>
98 #endif
99 #ifdef HAVE_STRING_H
100 #include <string.h>
101 #endif
102 #ifdef HAVE_UNISTD_H
103 #include <unistd.h>
104 #endif
105 #ifdef HAVE_UTIME_H
106 #include <utime.h>
107 #endif
108 #ifdef F_GETTIMES /* Tru64 specific */
109 #include <sys/fcntl1.h>
110 #endif
111
112 /*
113 * Macro to cast st_mtime and time_t to an int64 so that 2 numbers can reliably be compared.
114 *
115 * It assumes that the input is an integer type of no more than 64 bits.
116 * If the number is less than zero, t must be a signed type, so it fits in
117 * int64_t. Otherwise, it's a nonnegative value so we can cast it to uint64_t
118 * without loss. But it could be a large unsigned value, so we have to clip it
119 * to INT64_MAX.*
120 */
121 #define to_int64_time(t) \
122 ((t) < 0 ? (int64_t)(t) : (uint64_t)(t) > (uint64_t)INT64_MAX ? INT64_MAX : (int64_t)(t))
123
124 #if __APPLE__
125 #include <TargetConditionals.h>
126 #if TARGET_OS_MAC && !TARGET_OS_EMBEDDED && HAVE_QUARANTINE_H
127 #include <quarantine.h>
128 #define HAVE_QUARANTINE 1
129 #endif
130 #endif
131
132 #ifdef HAVE_ZLIB_H
133 #include <zlib.h>
134 #endif
135
136 /* TODO: Support Mac OS 'quarantine' feature. This is really just a
137 * standard tag to mark files that have been downloaded as "tainted".
138 * On Mac OS, we should mark the extracted files as tainted if the
139 * archive being read was tainted. Windows has a similar feature; we
140 * should investigate ways to support this generically. */
141
142 #include "archive.h"
143 #include "archive_acl_private.h"
144 #include "archive_string.h"
145 #include "archive_endian.h"
146 #include "archive_entry.h"
147 #include "archive_private.h"
148 #include "archive_write_disk_private.h"
149
150 #ifndef O_BINARY
151 #define O_BINARY 0
152 #endif
153 #ifndef O_CLOEXEC
154 #define O_CLOEXEC 0
155 #endif
156
157 /* Ignore non-int O_NOFOLLOW constant. */
158 /* gnulib's fcntl.h does this on AIX, but it seems practical everywhere */
159 #if defined O_NOFOLLOW && !(INT_MIN <= O_NOFOLLOW && O_NOFOLLOW <= INT_MAX)
160 #undef O_NOFOLLOW
161 #endif
162
163 #ifndef O_NOFOLLOW
164 #define O_NOFOLLOW 0
165 #endif
166
167 #ifndef AT_FDCWD
168 #define AT_FDCWD -100
169 #endif
170
171 struct fixup_entry {
172 struct fixup_entry *next;
173 struct archive_acl acl;
174 mode_t mode;
175 __LA_MODE_T filetype;
176 int64_t atime;
177 int64_t birthtime;
178 int64_t mtime;
179 int64_t ctime;
180 unsigned long atime_nanos;
181 unsigned long birthtime_nanos;
182 unsigned long mtime_nanos;
183 unsigned long ctime_nanos;
184 unsigned long fflags_set;
185 size_t mac_metadata_size;
186 void *mac_metadata;
187 int fixup; /* bitmask of what needs fixing */
188 char *name;
189 };
190
191 /*
192 * We use a bitmask to track which operations remain to be done for
193 * this file. In particular, this helps us avoid unnecessary
194 * operations when it's possible to take care of one step as a
195 * side-effect of another. For example, mkdir() can specify the mode
196 * for the newly-created object but symlink() cannot. This means we
197 * can skip chmod() if mkdir() succeeded, but we must explicitly
198 * chmod() if we're trying to create a directory that already exists
199 * (mkdir() failed) or if we're restoring a symlink. Similarly, we
200 * need to verify UID/GID before trying to restore SUID/SGID bits;
201 * that verification can occur explicitly through a stat() call or
202 * implicitly because of a successful chown() call.
203 */
204 #define TODO_MODE_FORCE 0x40000000
205 #define TODO_MODE_BASE 0x20000000
206 #define TODO_SUID 0x10000000
207 #define TODO_SUID_CHECK 0x08000000
208 #define TODO_SGID 0x04000000
209 #define TODO_SGID_CHECK 0x02000000
210 #define TODO_APPLEDOUBLE 0x01000000
211 #define TODO_MODE (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
212 #define TODO_TIMES ARCHIVE_EXTRACT_TIME
213 #define TODO_OWNER ARCHIVE_EXTRACT_OWNER
214 #define TODO_FFLAGS ARCHIVE_EXTRACT_FFLAGS
215 #define TODO_ACLS ARCHIVE_EXTRACT_ACL
216 #define TODO_XATTR ARCHIVE_EXTRACT_XATTR
217 #define TODO_MAC_METADATA ARCHIVE_EXTRACT_MAC_METADATA
218 #define TODO_HFS_COMPRESSION ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED
219
220 struct archive_write_disk {
221 struct archive archive;
222
223 mode_t user_umask;
224 struct fixup_entry *fixup_list;
225 struct fixup_entry *current_fixup;
226 int64_t user_uid;
227 int skip_file_set;
228 int64_t skip_file_dev;
229 int64_t skip_file_ino;
230 time_t start_time;
231
232 int64_t (*lookup_gid)(void *private, const char *gname, int64_t gid);
233 void (*cleanup_gid)(void *private);
234 void *lookup_gid_data;
235 int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid);
236 void (*cleanup_uid)(void *private);
237 void *lookup_uid_data;
238
239 /*
240 * Full path of last file to satisfy symlink checks.
241 */
242 struct archive_string path_safe;
243
244 /*
245 * Cached stat data from disk for the current entry.
246 * If this is valid, pst points to st. Otherwise,
247 * pst is null.
248 */
249 struct stat st;
250 struct stat *pst;
251
252 /* Information about the object being restored right now. */
253 struct archive_entry *entry; /* Entry being extracted. */
254 char *name; /* Name of entry, possibly edited. */
255 struct archive_string _name_data; /* backing store for 'name' */
256 char *tmpname; /* Temporary name * */
257 struct archive_string _tmpname_data; /* backing store for 'tmpname' */
258 /* Tasks remaining for this object. */
259 int todo;
260 /* Tasks deferred until end-of-archive. */
261 int deferred;
262 /* Options requested by the client. */
263 int flags;
264 /* Handle for the file we're restoring. */
265 int fd;
266 /* Current offset for writing data to the file. */
267 int64_t offset;
268 /* Last offset actually written to disk. */
269 int64_t fd_offset;
270 /* Total bytes actually written to files. */
271 int64_t total_bytes_written;
272 /* Maximum size of file, -1 if unknown. */
273 int64_t filesize;
274 /* Dir we were in before this restore; only for deep paths. */
275 int restore_pwd;
276 /* Mode we should use for this entry; affected by _PERM and umask. */
277 mode_t mode;
278 /* UID/GID to use in restoring this entry. */
279 int64_t uid;
280 int64_t gid;
281 /*
282 * HFS+ Compression.
283 */
284 /* Xattr "com.apple.decmpfs". */
285 uint32_t decmpfs_attr_size;
286 unsigned char *decmpfs_header_p;
287 /* ResourceFork set options used for fsetxattr. */
288 int rsrc_xattr_options;
289 /* Xattr "com.apple.ResourceFork". */
290 unsigned char *resource_fork;
291 size_t resource_fork_allocated_size;
292 unsigned int decmpfs_block_count;
293 uint32_t *decmpfs_block_info;
294 /* Buffer for compressed data. */
295 unsigned char *compressed_buffer;
296 size_t compressed_buffer_size;
297 size_t compressed_buffer_remaining;
298 /* The offset of the ResourceFork where compressed data will
299 * be placed. */
300 uint32_t compressed_rsrc_position;
301 uint32_t compressed_rsrc_position_v;
302 /* Buffer for uncompressed data. */
303 char *uncompressed_buffer;
304 size_t block_remaining_bytes;
305 size_t file_remaining_bytes;
306 #ifdef HAVE_ZLIB_H
307 z_stream stream;
308 int stream_valid;
309 int decmpfs_compression_level;
310 #endif
311 };
312
313 /*
314 * Default mode for dirs created automatically (will be modified by umask).
315 * Note that POSIX specifies 0777 for implicitly-created dirs, "modified
316 * by the process' file creation mask."
317 */
318 #define DEFAULT_DIR_MODE 0777
319 /*
320 * Dir modes are restored in two steps: During the extraction, the permissions
321 * in the archive are modified to match the following limits. During
322 * the post-extract fixup pass, the permissions from the archive are
323 * applied.
324 */
325 #define MINIMUM_DIR_MODE 0700
326 #define MAXIMUM_DIR_MODE 0775
327
328 /*
329 * Maximum uncompressed size of a decmpfs block.
330 */
331 #define MAX_DECMPFS_BLOCK_SIZE (64 * 1024)
332 /*
333 * HFS+ compression type.
334 */
335 #define CMP_XATTR 3/* Compressed data in xattr. */
336 #define CMP_RESOURCE_FORK 4/* Compressed data in resource fork. */
337 /*
338 * HFS+ compression resource fork.
339 */
340 #define RSRC_H_SIZE 260 /* Base size of Resource fork header. */
341 #define RSRC_F_SIZE 50 /* Size of Resource fork footer. */
342 /* Size to write compressed data to resource fork. */
343 #define COMPRESSED_W_SIZE (64 * 1024)
344 /* decmpfs definitions. */
345 #define MAX_DECMPFS_XATTR_SIZE 3802
346 #ifndef DECMPFS_XATTR_NAME
347 #define DECMPFS_XATTR_NAME "com.apple.decmpfs"
348 #endif
349 #define DECMPFS_MAGIC 0x636d7066
350 #define DECMPFS_COMPRESSION_MAGIC 0
351 #define DECMPFS_COMPRESSION_TYPE 4
352 #define DECMPFS_UNCOMPRESSED_SIZE 8
353 #define DECMPFS_HEADER_SIZE 16
354
355 #define HFS_BLOCKS(s) ((s) >> 12)
356
357
358 static int la_opendirat(int, const char *);
359 static int la_mktemp(struct archive_write_disk *);
360 static int la_verify_filetype(mode_t, __LA_MODE_T);
361 static void fsobj_error(int *, struct archive_string *, int, const char *,
362 const char *);
363 static int check_symlinks_fsobj(char *, int *, struct archive_string *,
364 int, int);
365 static int check_symlinks(struct archive_write_disk *);
366 static int create_filesystem_object(struct archive_write_disk *);
367 static struct fixup_entry *current_fixup(struct archive_write_disk *,
368 const char *pathname);
369 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
370 static void edit_deep_directories(struct archive_write_disk *ad);
371 #endif
372 static int cleanup_pathname_fsobj(char *, int *, struct archive_string *,
373 int);
374 static int cleanup_pathname(struct archive_write_disk *);
375 static int create_dir(struct archive_write_disk *, char *);
376 static int create_parent_dir(struct archive_write_disk *, char *);
377 static ssize_t hfs_write_data_block(struct archive_write_disk *,
378 const char *, size_t);
379 static int fixup_appledouble(struct archive_write_disk *, const char *);
380 static int older(struct stat *, struct archive_entry *);
381 static int restore_entry(struct archive_write_disk *);
382 static int set_mac_metadata(struct archive_write_disk *, const char *,
383 const void *, size_t);
384 static int set_xattrs(struct archive_write_disk *);
385 static int clear_nochange_fflags(struct archive_write_disk *);
386 static int set_fflags(struct archive_write_disk *);
387 static int set_fflags_platform(struct archive_write_disk *, int fd,
388 const char *name, mode_t mode,
389 unsigned long fflags_set, unsigned long fflags_clear);
390 static int set_ownership(struct archive_write_disk *);
391 static int set_mode(struct archive_write_disk *, int mode);
392 static int set_time(int, int, const char *, time_t, long, time_t, long);
393 static int set_times(struct archive_write_disk *, int, int, const char *,
394 time_t, long, time_t, long, time_t, long, time_t, long);
395 static int set_times_from_entry(struct archive_write_disk *);
396 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
397 static ssize_t write_data_block(struct archive_write_disk *,
398 const char *, size_t);
399 static void close_file_descriptor(struct archive_write_disk *);
400
401 static int _archive_write_disk_close(struct archive *);
402 static int _archive_write_disk_free(struct archive *);
403 static int _archive_write_disk_header(struct archive *,
404 struct archive_entry *);
405 static int64_t _archive_write_disk_filter_bytes(struct archive *, int);
406 static int _archive_write_disk_finish_entry(struct archive *);
407 static ssize_t _archive_write_disk_data(struct archive *, const void *,
408 size_t);
409 static ssize_t _archive_write_disk_data_block(struct archive *, const void *,
410 size_t, int64_t);
411
412 static int
la_mktemp(struct archive_write_disk * a)413 la_mktemp(struct archive_write_disk *a)
414 {
415 struct archive_string *tmp = &a->_tmpname_data;
416 int oerrno, fd;
417 mode_t mode;
418
419 archive_strcpy(tmp, a->name);
420 archive_string_dirname(tmp);
421 archive_strcat(tmp, "/tar.XXXXXXXX");
422 a->tmpname = tmp->s;
423
424 fd = __archive_mkstemp(a->tmpname);
425 if (fd == -1)
426 return -1;
427
428 mode = a->mode & 0777 & ~a->user_umask;
429 if (fchmod(fd, mode) == -1) {
430 oerrno = errno;
431 close(fd);
432 errno = oerrno;
433 return -1;
434 }
435 return fd;
436 }
437
438 static int
la_opendirat(int fd,const char * path)439 la_opendirat(int fd, const char *path) {
440 const int flags = O_CLOEXEC
441 #if defined(O_BINARY)
442 | O_BINARY
443 #endif
444 #if defined(O_DIRECTORY)
445 | O_DIRECTORY
446 #endif
447 #if defined(O_PATH)
448 | O_PATH
449 #elif defined(O_SEARCH)
450 | O_SEARCH
451 #elif defined(__FreeBSD__) && defined(O_EXEC)
452 | O_EXEC
453 #else
454 | O_RDONLY
455 #endif
456 ;
457
458 #if !defined(HAVE_OPENAT)
459 if (fd != AT_FDCWD) {
460 errno = ENOTSUP;
461 return (-1);
462 } else
463 return (open(path, flags));
464 #else
465 return (openat(fd, path, flags));
466 #endif
467 }
468
469 static int
la_verify_filetype(mode_t mode,__LA_MODE_T filetype)470 la_verify_filetype(mode_t mode, __LA_MODE_T filetype) {
471 int ret = 0;
472
473 switch (filetype) {
474 case AE_IFREG:
475 ret = (S_ISREG(mode));
476 break;
477 case AE_IFDIR:
478 ret = (S_ISDIR(mode));
479 break;
480 case AE_IFLNK:
481 ret = (S_ISLNK(mode));
482 break;
483 #ifdef S_ISSOCK
484 case AE_IFSOCK:
485 ret = (S_ISSOCK(mode));
486 break;
487 #endif
488 case AE_IFCHR:
489 ret = (S_ISCHR(mode));
490 break;
491 case AE_IFBLK:
492 ret = (S_ISBLK(mode));
493 break;
494 case AE_IFIFO:
495 ret = (S_ISFIFO(mode));
496 break;
497 default:
498 break;
499 }
500
501 return (ret);
502 }
503
504 static int
lazy_stat(struct archive_write_disk * a)505 lazy_stat(struct archive_write_disk *a)
506 {
507 if (a->pst != NULL) {
508 /* Already have stat() data available. */
509 return (ARCHIVE_OK);
510 }
511 #ifdef HAVE_FSTAT
512 if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
513 a->pst = &a->st;
514 return (ARCHIVE_OK);
515 }
516 #endif
517 /*
518 * XXX At this point, symlinks should not be hit, otherwise
519 * XXX a race occurred. Do we want to check explicitly for that?
520 */
521 #ifdef HAVE_LSTAT
522 if (lstat(a->name, &a->st) == 0)
523 #else
524 if (la_stat(a->name, &a->st) == 0)
525 #endif
526 {
527 a->pst = &a->st;
528 return (ARCHIVE_OK);
529 }
530 archive_set_error(&a->archive, errno, "Couldn't stat file");
531 return (ARCHIVE_WARN);
532 }
533
534 static const struct archive_vtable
535 archive_write_disk_vtable = {
536 .archive_close = _archive_write_disk_close,
537 .archive_filter_bytes = _archive_write_disk_filter_bytes,
538 .archive_free = _archive_write_disk_free,
539 .archive_write_header = _archive_write_disk_header,
540 .archive_write_finish_entry = _archive_write_disk_finish_entry,
541 .archive_write_data = _archive_write_disk_data,
542 .archive_write_data_block = _archive_write_disk_data_block,
543 };
544
545 static int64_t
_archive_write_disk_filter_bytes(struct archive * _a,int n)546 _archive_write_disk_filter_bytes(struct archive *_a, int n)
547 {
548 struct archive_write_disk *a = (struct archive_write_disk *)_a;
549 (void)n; /* UNUSED */
550 if (n == -1 || n == 0)
551 return (a->total_bytes_written);
552 return (-1);
553 }
554
555
556 int
archive_write_disk_set_options(struct archive * _a,int flags)557 archive_write_disk_set_options(struct archive *_a, int flags)
558 {
559 struct archive_write_disk *a = (struct archive_write_disk *)_a;
560
561 a->flags = flags;
562 return (ARCHIVE_OK);
563 }
564
565
566 /*
567 * Extract this entry to disk.
568 *
569 * TODO: Validate hardlinks. According to the standards, we're
570 * supposed to check each extracted hardlink and squawk if it refers
571 * to a file that we didn't restore. I'm not entirely convinced this
572 * is a good idea, but more importantly: Is there any way to validate
573 * hardlinks without keeping a complete list of filenames from the
574 * entire archive?? Ugh.
575 *
576 */
577 static int
_archive_write_disk_header(struct archive * _a,struct archive_entry * entry)578 _archive_write_disk_header(struct archive *_a, struct archive_entry *entry)
579 {
580 struct archive_write_disk *a = (struct archive_write_disk *)_a;
581 struct fixup_entry *fe;
582 const char *linkname;
583 int ret, r;
584
585 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
586 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
587 "archive_write_disk_header");
588 archive_clear_error(&a->archive);
589 if (a->archive.state & ARCHIVE_STATE_DATA) {
590 r = _archive_write_disk_finish_entry(&a->archive);
591 if (r == ARCHIVE_FATAL)
592 return (r);
593 }
594
595 /* Set up for this particular entry. */
596 a->pst = NULL;
597 a->current_fixup = NULL;
598 a->deferred = 0;
599 if (a->entry) {
600 archive_entry_free(a->entry);
601 a->entry = NULL;
602 }
603 a->entry = archive_entry_clone(entry);
604 a->fd = -1;
605 a->fd_offset = 0;
606 a->offset = 0;
607 a->restore_pwd = -1;
608 a->uid = a->user_uid;
609 a->mode = archive_entry_mode(a->entry);
610 if (archive_entry_size_is_set(a->entry))
611 a->filesize = archive_entry_size(a->entry);
612 else
613 a->filesize = -1;
614 archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
615 a->name = a->_name_data.s;
616 archive_clear_error(&a->archive);
617
618 /*
619 * Clean up the requested path. This is necessary for correct
620 * dir restores; the dir restore logic otherwise gets messed
621 * up by nonsense like "dir/.".
622 */
623 ret = cleanup_pathname(a);
624 if (ret != ARCHIVE_OK)
625 return (ret);
626
627 /*
628 * Check if we have a hardlink that points to itself.
629 */
630 linkname = archive_entry_hardlink(a->entry);
631 if (linkname != NULL && strcmp(a->name, linkname) == 0) {
632 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
633 "Skipping hardlink pointing to itself: %s",
634 a->name);
635 return (ARCHIVE_WARN);
636 }
637
638 /*
639 * Query the umask so we get predictable mode settings.
640 * This gets done on every call to _write_header in case the
641 * user edits their umask during the extraction for some
642 * reason.
643 */
644 umask(a->user_umask = umask(0));
645
646 /* Figure out what we need to do for this entry. */
647 a->todo = TODO_MODE_BASE;
648 if (a->flags & ARCHIVE_EXTRACT_PERM) {
649 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
650 /*
651 * SGID requires an extra "check" step because we
652 * cannot easily predict the GID that the system will
653 * assign. (Different systems assign GIDs to files
654 * based on a variety of criteria, including process
655 * credentials and the gid of the enclosing
656 * directory.) We can only restore the SGID bit if
657 * the file has the right GID, and we only know the
658 * GID if we either set it (see set_ownership) or if
659 * we've actually called stat() on the file after it
660 * was restored. Since there are several places at
661 * which we might verify the GID, we need a TODO bit
662 * to keep track.
663 */
664 if (a->mode & S_ISGID)
665 a->todo |= TODO_SGID | TODO_SGID_CHECK;
666 /*
667 * Verifying the SUID is simpler, but can still be
668 * done in multiple ways, hence the separate "check" bit.
669 */
670 if (a->mode & S_ISUID)
671 a->todo |= TODO_SUID | TODO_SUID_CHECK;
672 } else {
673 /*
674 * User didn't request full permissions, so don't
675 * restore SUID, SGID bits and obey umask.
676 */
677 a->mode &= ~S_ISUID;
678 a->mode &= ~S_ISGID;
679 a->mode &= ~S_ISVTX;
680 a->mode &= ~a->user_umask;
681 }
682 if (a->flags & ARCHIVE_EXTRACT_OWNER)
683 a->todo |= TODO_OWNER;
684 if (a->flags & ARCHIVE_EXTRACT_TIME)
685 a->todo |= TODO_TIMES;
686 if (a->flags & ARCHIVE_EXTRACT_ACL) {
687 #if ARCHIVE_ACL_DARWIN
688 /*
689 * On MacOS, platform ACLs get stored in mac_metadata, too.
690 * If we intend to extract mac_metadata and it is present
691 * we skip extracting libarchive NFSv4 ACLs.
692 */
693 size_t metadata_size;
694
695 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
696 archive_entry_mac_metadata(a->entry,
697 &metadata_size) == NULL || metadata_size == 0)
698 #endif
699 #if ARCHIVE_ACL_LIBRICHACL
700 /*
701 * RichACLs are stored in an extended attribute.
702 * If we intend to extract extended attributes and have this
703 * attribute we skip extracting libarchive NFSv4 ACLs.
704 */
705 short extract_acls = 1;
706 if (a->flags & ARCHIVE_EXTRACT_XATTR && (
707 archive_entry_acl_types(a->entry) &
708 ARCHIVE_ENTRY_ACL_TYPE_NFS4)) {
709 const char *attr_name;
710 const void *attr_value;
711 size_t attr_size;
712 int i = archive_entry_xattr_reset(a->entry);
713 while (i--) {
714 archive_entry_xattr_next(a->entry, &attr_name,
715 &attr_value, &attr_size);
716 if (attr_name != NULL && attr_value != NULL &&
717 attr_size > 0 && strcmp(attr_name,
718 "trusted.richacl") == 0) {
719 extract_acls = 0;
720 break;
721 }
722 }
723 }
724 if (extract_acls)
725 #endif
726 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
727 {
728 #endif
729 if (archive_entry_filetype(a->entry) == AE_IFDIR)
730 a->deferred |= TODO_ACLS;
731 else
732 a->todo |= TODO_ACLS;
733 #if ARCHIVE_ACL_DARWIN || ARCHIVE_ACL_LIBRICHACL
734 }
735 #endif
736 }
737 if (a->flags & ARCHIVE_EXTRACT_MAC_METADATA) {
738 if (archive_entry_filetype(a->entry) == AE_IFDIR)
739 a->deferred |= TODO_MAC_METADATA;
740 else
741 a->todo |= TODO_MAC_METADATA;
742 }
743 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
744 if ((a->flags & ARCHIVE_EXTRACT_NO_HFS_COMPRESSION) == 0) {
745 unsigned long set, clear;
746 archive_entry_fflags(a->entry, &set, &clear);
747 if ((set & ~clear) & UF_COMPRESSED) {
748 a->todo |= TODO_HFS_COMPRESSION;
749 a->decmpfs_block_count = (unsigned)-1;
750 }
751 }
752 if ((a->flags & ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED) != 0 &&
753 (a->mode & AE_IFMT) == AE_IFREG && a->filesize > 0) {
754 a->todo |= TODO_HFS_COMPRESSION;
755 a->decmpfs_block_count = (unsigned)-1;
756 }
757 {
758 const char *p;
759
760 /* Check if the current file name is a type of the
761 * resource fork file. */
762 p = strrchr(a->name, '/');
763 if (p == NULL)
764 p = a->name;
765 else
766 p++;
767 if (p[0] == '.' && p[1] == '_') {
768 /* Do not compress "._XXX" files. */
769 a->todo &= ~TODO_HFS_COMPRESSION;
770 if (a->filesize > 0)
771 a->todo |= TODO_APPLEDOUBLE;
772 }
773 }
774 #endif
775
776 if (a->flags & ARCHIVE_EXTRACT_XATTR) {
777 #if ARCHIVE_XATTR_DARWIN
778 /*
779 * On MacOS, extended attributes get stored in mac_metadata,
780 * too. If we intend to extract mac_metadata and it is present
781 * we skip extracting extended attributes.
782 */
783 size_t metadata_size;
784
785 if ((a->flags & ARCHIVE_EXTRACT_MAC_METADATA) == 0 ||
786 archive_entry_mac_metadata(a->entry,
787 &metadata_size) == NULL || metadata_size == 0)
788 #endif
789 a->todo |= TODO_XATTR;
790 }
791 if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
792 a->todo |= TODO_FFLAGS;
793 if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
794 ret = check_symlinks(a);
795 if (ret != ARCHIVE_OK)
796 return (ret);
797 }
798 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
799 /* If path exceeds PATH_MAX, shorten the path. */
800 edit_deep_directories(a);
801 #endif
802
803 ret = restore_entry(a);
804
805 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
806 /*
807 * Check if the filesystem the file is restoring on supports
808 * HFS+ Compression. If not, cancel HFS+ Compression.
809 */
810 if (a->todo | TODO_HFS_COMPRESSION) {
811 /*
812 * NOTE: UF_COMPRESSED is ignored even if the filesystem
813 * supports HFS+ Compression because the file should
814 * have at least an extended attribute "com.apple.decmpfs"
815 * before the flag is set to indicate that the file have
816 * been compressed. If the filesystem does not support
817 * HFS+ Compression the system call will fail.
818 */
819 if (a->fd < 0 || fchflags(a->fd, UF_COMPRESSED) != 0)
820 a->todo &= ~TODO_HFS_COMPRESSION;
821 }
822 #endif
823
824 /*
825 * TODO: There are rumours that some extended attributes must
826 * be restored before file data is written. If this is true,
827 * then we either need to write all extended attributes both
828 * before and after restoring the data, or find some rule for
829 * determining which must go first and which last. Due to the
830 * many ways people are using xattrs, this may prove to be an
831 * intractable problem.
832 */
833
834 #ifdef HAVE_FCHDIR
835 /* If we changed directory above, restore it here. */
836 if (a->restore_pwd >= 0) {
837 r = fchdir(a->restore_pwd);
838 if (r != 0) {
839 archive_set_error(&a->archive, errno,
840 "chdir() failure");
841 ret = ARCHIVE_FATAL;
842 }
843 close(a->restore_pwd);
844 a->restore_pwd = -1;
845 }
846 #endif
847
848 /*
849 * Fixup uses the unedited pathname from archive_entry_pathname(),
850 * because it is relative to the base dir and the edited path
851 * might be relative to some intermediate dir as a result of the
852 * deep restore logic.
853 */
854 if (a->deferred & TODO_MODE) {
855 fe = current_fixup(a, archive_entry_pathname(entry));
856 if (fe == NULL)
857 return (ARCHIVE_FATAL);
858 fe->filetype = archive_entry_filetype(entry);
859 fe->fixup |= TODO_MODE_BASE;
860 fe->mode = a->mode;
861 }
862
863 if ((a->deferred & TODO_TIMES)
864 && (archive_entry_mtime_is_set(entry)
865 || archive_entry_atime_is_set(entry))) {
866 fe = current_fixup(a, archive_entry_pathname(entry));
867 if (fe == NULL)
868 return (ARCHIVE_FATAL);
869 fe->filetype = archive_entry_filetype(entry);
870 fe->mode = a->mode;
871 fe->fixup |= TODO_TIMES;
872 if (archive_entry_atime_is_set(entry)) {
873 fe->atime = archive_entry_atime(entry);
874 fe->atime_nanos = archive_entry_atime_nsec(entry);
875 } else {
876 /* If atime is unset, use start time. */
877 fe->atime = a->start_time;
878 fe->atime_nanos = 0;
879 }
880 if (archive_entry_mtime_is_set(entry)) {
881 fe->mtime = archive_entry_mtime(entry);
882 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
883 } else {
884 /* If mtime is unset, use start time. */
885 fe->mtime = a->start_time;
886 fe->mtime_nanos = 0;
887 }
888 if (archive_entry_birthtime_is_set(entry)) {
889 fe->birthtime = archive_entry_birthtime(entry);
890 fe->birthtime_nanos = archive_entry_birthtime_nsec(
891 entry);
892 } else {
893 /* If birthtime is unset, use mtime. */
894 fe->birthtime = fe->mtime;
895 fe->birthtime_nanos = fe->mtime_nanos;
896 }
897 }
898
899 if (a->deferred & TODO_ACLS) {
900 fe = current_fixup(a, archive_entry_pathname(entry));
901 if (fe == NULL)
902 return (ARCHIVE_FATAL);
903 fe->filetype = archive_entry_filetype(entry);
904 fe->fixup |= TODO_ACLS;
905 archive_acl_copy(&fe->acl, archive_entry_acl(entry));
906 }
907
908 if (a->deferred & TODO_MAC_METADATA) {
909 const void *metadata;
910 size_t metadata_size;
911 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
912 if (metadata != NULL && metadata_size > 0) {
913 fe = current_fixup(a, archive_entry_pathname(entry));
914 if (fe == NULL)
915 return (ARCHIVE_FATAL);
916 fe->filetype = archive_entry_filetype(entry);
917 fe->mac_metadata = malloc(metadata_size);
918 if (fe->mac_metadata != NULL) {
919 memcpy(fe->mac_metadata, metadata,
920 metadata_size);
921 fe->mac_metadata_size = metadata_size;
922 fe->fixup |= TODO_MAC_METADATA;
923 }
924 }
925 }
926
927 if (a->deferred & TODO_FFLAGS) {
928 fe = current_fixup(a, archive_entry_pathname(entry));
929 if (fe == NULL)
930 return (ARCHIVE_FATAL);
931 fe->filetype = archive_entry_filetype(entry);
932 fe->fixup |= TODO_FFLAGS;
933 /* TODO: Complete this.. defer fflags from below. */
934 }
935
936 /* We've created the object and are ready to pour data into it. */
937 if (ret >= ARCHIVE_WARN)
938 a->archive.state = ARCHIVE_STATE_DATA;
939 /*
940 * If it's not open, tell our client not to try writing.
941 * In particular, dirs, links, etc, don't get written to.
942 */
943 if (a->fd < 0) {
944 archive_entry_set_size(entry, 0);
945 a->filesize = 0;
946 }
947
948 return (ret);
949 }
950
951 int
archive_write_disk_set_skip_file(struct archive * _a,la_int64_t d,la_int64_t i)952 archive_write_disk_set_skip_file(struct archive *_a, la_int64_t d, la_int64_t i)
953 {
954 struct archive_write_disk *a = (struct archive_write_disk *)_a;
955 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
956 ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
957 a->skip_file_set = 1;
958 a->skip_file_dev = d;
959 a->skip_file_ino = i;
960 return (ARCHIVE_OK);
961 }
962
963 static ssize_t
write_data_block(struct archive_write_disk * a,const char * buff,size_t size)964 write_data_block(struct archive_write_disk *a, const char *buff, size_t size)
965 {
966 uint64_t start_size = size;
967 ssize_t bytes_written = 0;
968 ssize_t block_size = 0, bytes_to_write;
969
970 if (size == 0)
971 return (ARCHIVE_OK);
972
973 if (a->filesize == 0 || a->fd < 0) {
974 archive_set_error(&a->archive, 0,
975 "Attempt to write to an empty file");
976 return (ARCHIVE_WARN);
977 }
978
979 if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
980 #if HAVE_STRUCT_STAT_ST_BLKSIZE
981 int r;
982 if ((r = lazy_stat(a)) != ARCHIVE_OK)
983 return (r);
984 block_size = a->pst->st_blksize;
985 #else
986 /* XXX TODO XXX Is there a more appropriate choice here ? */
987 /* This needn't match the filesystem allocation size. */
988 block_size = 16*1024;
989 #endif
990 }
991
992 /* If this write would run beyond the file size, truncate it. */
993 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
994 start_size = size = (size_t)(a->filesize - a->offset);
995
996 /* Write the data. */
997 while (size > 0) {
998 if (block_size == 0) {
999 bytes_to_write = size;
1000 } else {
1001 /* We're sparsifying the file. */
1002 const char *p, *end;
1003 int64_t block_end;
1004
1005 /* Skip leading zero bytes. */
1006 for (p = buff, end = buff + size; p < end; ++p) {
1007 if (*p != '\0')
1008 break;
1009 }
1010 a->offset += p - buff;
1011 size -= p - buff;
1012 buff = p;
1013 if (size == 0)
1014 break;
1015
1016 /* Calculate next block boundary after offset. */
1017 block_end
1018 = (a->offset / block_size + 1) * block_size;
1019
1020 /* If the adjusted write would cross block boundary,
1021 * truncate it to the block boundary. */
1022 bytes_to_write = size;
1023 if (a->offset + bytes_to_write > block_end)
1024 bytes_to_write = block_end - a->offset;
1025 }
1026 /* Seek if necessary to the specified offset. */
1027 if (a->offset != a->fd_offset) {
1028 if (lseek(a->fd, a->offset, SEEK_SET) < 0) {
1029 archive_set_error(&a->archive, errno,
1030 "Seek failed");
1031 return (ARCHIVE_FATAL);
1032 }
1033 a->fd_offset = a->offset;
1034 }
1035 bytes_written = write(a->fd, buff, bytes_to_write);
1036 if (bytes_written < 0) {
1037 archive_set_error(&a->archive, errno, "Write failed");
1038 return (ARCHIVE_WARN);
1039 }
1040 buff += bytes_written;
1041 size -= bytes_written;
1042 a->total_bytes_written += bytes_written;
1043 a->offset += bytes_written;
1044 a->fd_offset = a->offset;
1045 }
1046 return (start_size - size);
1047 }
1048
1049 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
1050 && defined(HAVE_ZLIB_H)
1051
1052 /*
1053 * Set UF_COMPRESSED file flag.
1054 * This have to be called after hfs_write_decmpfs() because if the
1055 * file does not have "com.apple.decmpfs" xattr the flag is ignored.
1056 */
1057 static int
hfs_set_compressed_fflag(struct archive_write_disk * a)1058 hfs_set_compressed_fflag(struct archive_write_disk *a)
1059 {
1060 int r;
1061
1062 if ((r = lazy_stat(a)) != ARCHIVE_OK)
1063 return (r);
1064
1065 a->st.st_flags |= UF_COMPRESSED;
1066 if (fchflags(a->fd, a->st.st_flags) != 0) {
1067 archive_set_error(&a->archive, errno,
1068 "Failed to set UF_COMPRESSED file flag");
1069 return (ARCHIVE_WARN);
1070 }
1071 return (ARCHIVE_OK);
1072 }
1073
1074 /*
1075 * HFS+ Compression decmpfs
1076 *
1077 * +------------------------------+ +0
1078 * | Magic(LE 4 bytes) |
1079 * +------------------------------+
1080 * | Type(LE 4 bytes) |
1081 * +------------------------------+
1082 * | Uncompressed size(LE 8 bytes)|
1083 * +------------------------------+ +16
1084 * | |
1085 * | Compressed data |
1086 * | (Placed only if Type == 3) |
1087 * | |
1088 * +------------------------------+ +3802 = MAX_DECMPFS_XATTR_SIZE
1089 *
1090 * Type is 3: decmpfs has compressed data.
1091 * Type is 4: Resource Fork has compressed data.
1092 */
1093 /*
1094 * Write "com.apple.decmpfs"
1095 */
1096 static int
hfs_write_decmpfs(struct archive_write_disk * a)1097 hfs_write_decmpfs(struct archive_write_disk *a)
1098 {
1099 int r;
1100 uint32_t compression_type;
1101
1102 r = fsetxattr(a->fd, DECMPFS_XATTR_NAME, a->decmpfs_header_p,
1103 a->decmpfs_attr_size, 0, 0);
1104 if (r < 0) {
1105 archive_set_error(&a->archive, errno,
1106 "Cannot restore xattr:%s", DECMPFS_XATTR_NAME);
1107 compression_type = archive_le32dec(
1108 &a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE]);
1109 if (compression_type == CMP_RESOURCE_FORK)
1110 fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME,
1111 XATTR_SHOWCOMPRESSION);
1112 return (ARCHIVE_WARN);
1113 }
1114 return (ARCHIVE_OK);
1115 }
1116
1117 /*
1118 * HFS+ Compression Resource Fork
1119 *
1120 * +-----------------------------+
1121 * | Header(260 bytes) |
1122 * +-----------------------------+
1123 * | Block count(LE 4 bytes) |
1124 * +-----------------------------+ --+
1125 * +-- | Offset (LE 4 bytes) | |
1126 * | | [distance from Block count] | | Block 0
1127 * | +-----------------------------+ |
1128 * | | Compressed size(LE 4 bytes) | |
1129 * | +-----------------------------+ --+
1130 * | | |
1131 * | | .................. |
1132 * | | |
1133 * | +-----------------------------+ --+
1134 * | | Offset (LE 4 bytes) | |
1135 * | +-----------------------------+ | Block (Block count -1)
1136 * | | Compressed size(LE 4 bytes) | |
1137 * +-> +-----------------------------+ --+
1138 * | Compressed data(n bytes) | Block 0
1139 * +-----------------------------+
1140 * | |
1141 * | .................. |
1142 * | |
1143 * +-----------------------------+
1144 * | Compressed data(n bytes) | Block (Block count -1)
1145 * +-----------------------------+
1146 * | Footer(50 bytes) |
1147 * +-----------------------------+
1148 *
1149 */
1150 /*
1151 * Write the header of "com.apple.ResourceFork"
1152 */
1153 static int
hfs_write_resource_fork(struct archive_write_disk * a,unsigned char * buff,size_t bytes,uint32_t position)1154 hfs_write_resource_fork(struct archive_write_disk *a, unsigned char *buff,
1155 size_t bytes, uint32_t position)
1156 {
1157 int ret;
1158
1159 ret = fsetxattr(a->fd, XATTR_RESOURCEFORK_NAME, buff, bytes,
1160 position, a->rsrc_xattr_options);
1161 if (ret < 0) {
1162 archive_set_error(&a->archive, errno,
1163 "Cannot restore xattr: %s at %u pos %u bytes",
1164 XATTR_RESOURCEFORK_NAME,
1165 (unsigned)position,
1166 (unsigned)bytes);
1167 return (ARCHIVE_WARN);
1168 }
1169 a->rsrc_xattr_options &= ~XATTR_CREATE;
1170 return (ARCHIVE_OK);
1171 }
1172
1173 static int
hfs_write_compressed_data(struct archive_write_disk * a,size_t bytes_compressed)1174 hfs_write_compressed_data(struct archive_write_disk *a, size_t bytes_compressed)
1175 {
1176 int ret;
1177
1178 ret = hfs_write_resource_fork(a, a->compressed_buffer,
1179 bytes_compressed, a->compressed_rsrc_position);
1180 if (ret == ARCHIVE_OK)
1181 a->compressed_rsrc_position += bytes_compressed;
1182 return (ret);
1183 }
1184
1185 static int
hfs_write_resource_fork_header(struct archive_write_disk * a)1186 hfs_write_resource_fork_header(struct archive_write_disk *a)
1187 {
1188 unsigned char *buff;
1189 uint32_t rsrc_bytes;
1190 uint32_t rsrc_header_bytes;
1191
1192 /*
1193 * Write resource fork header + block info.
1194 */
1195 buff = a->resource_fork;
1196 rsrc_bytes = a->compressed_rsrc_position - RSRC_F_SIZE;
1197 rsrc_header_bytes =
1198 RSRC_H_SIZE + /* Header base size. */
1199 4 + /* Block count. */
1200 (a->decmpfs_block_count * 8);/* Block info */
1201 archive_be32enc(buff, 0x100);
1202 archive_be32enc(buff + 4, rsrc_bytes);
1203 archive_be32enc(buff + 8, rsrc_bytes - 256);
1204 archive_be32enc(buff + 12, 0x32);
1205 memset(buff + 16, 0, 240);
1206 archive_be32enc(buff + 256, rsrc_bytes - 260);
1207 return hfs_write_resource_fork(a, buff, rsrc_header_bytes, 0);
1208 }
1209
1210 static size_t
hfs_set_resource_fork_footer(unsigned char * buff,size_t buff_size)1211 hfs_set_resource_fork_footer(unsigned char *buff, size_t buff_size)
1212 {
1213 static const char rsrc_footer[RSRC_F_SIZE] = {
1214 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1215 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1216 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1217 0x00, 0x1c, 0x00, 0x32, 0x00, 0x00, 'c', 'm',
1218 'p', 'f', 0x00, 0x00, 0x00, 0x0a, 0x00, 0x01,
1219 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1220 0x00, 0x00
1221 };
1222 if (buff_size < sizeof(rsrc_footer))
1223 return (0);
1224 memcpy(buff, rsrc_footer, sizeof(rsrc_footer));
1225 return (sizeof(rsrc_footer));
1226 }
1227
1228 static int
hfs_reset_compressor(struct archive_write_disk * a)1229 hfs_reset_compressor(struct archive_write_disk *a)
1230 {
1231 int ret;
1232
1233 if (a->stream_valid)
1234 ret = deflateReset(&a->stream);
1235 else
1236 ret = deflateInit(&a->stream, a->decmpfs_compression_level);
1237
1238 if (ret != Z_OK) {
1239 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1240 "Failed to initialize compressor");
1241 return (ARCHIVE_FATAL);
1242 } else
1243 a->stream_valid = 1;
1244
1245 return (ARCHIVE_OK);
1246 }
1247
1248 static int
hfs_decompress(struct archive_write_disk * a)1249 hfs_decompress(struct archive_write_disk *a)
1250 {
1251 uint32_t *block_info;
1252 unsigned int block_count;
1253 uint32_t data_pos, data_size;
1254 ssize_t r;
1255 ssize_t bytes_written, bytes_to_write;
1256 unsigned char *b;
1257
1258 block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1259 block_count = archive_le32dec(block_info++);
1260 while (block_count--) {
1261 data_pos = RSRC_H_SIZE + archive_le32dec(block_info++);
1262 data_size = archive_le32dec(block_info++);
1263 r = fgetxattr(a->fd, XATTR_RESOURCEFORK_NAME,
1264 a->compressed_buffer, data_size, data_pos, 0);
1265 if (r != data_size) {
1266 archive_set_error(&a->archive,
1267 (r < 0)?errno:ARCHIVE_ERRNO_MISC,
1268 "Failed to read resource fork");
1269 return (ARCHIVE_WARN);
1270 }
1271 if (a->compressed_buffer[0] == 0xff) {
1272 bytes_to_write = data_size -1;
1273 b = a->compressed_buffer + 1;
1274 } else {
1275 uLong dest_len = MAX_DECMPFS_BLOCK_SIZE;
1276 int zr;
1277
1278 zr = uncompress((Bytef *)a->uncompressed_buffer,
1279 &dest_len, a->compressed_buffer, data_size);
1280 if (zr != Z_OK) {
1281 archive_set_error(&a->archive,
1282 ARCHIVE_ERRNO_MISC,
1283 "Failed to decompress resource fork");
1284 return (ARCHIVE_WARN);
1285 }
1286 bytes_to_write = dest_len;
1287 b = (unsigned char *)a->uncompressed_buffer;
1288 }
1289 do {
1290 bytes_written = write(a->fd, b, bytes_to_write);
1291 if (bytes_written < 0) {
1292 archive_set_error(&a->archive, errno,
1293 "Write failed");
1294 return (ARCHIVE_WARN);
1295 }
1296 bytes_to_write -= bytes_written;
1297 b += bytes_written;
1298 } while (bytes_to_write > 0);
1299 }
1300 r = fremovexattr(a->fd, XATTR_RESOURCEFORK_NAME, 0);
1301 if (r == -1) {
1302 archive_set_error(&a->archive, errno,
1303 "Failed to remove resource fork");
1304 return (ARCHIVE_WARN);
1305 }
1306 return (ARCHIVE_OK);
1307 }
1308
1309 static int
hfs_drive_compressor(struct archive_write_disk * a,const char * buff,size_t size)1310 hfs_drive_compressor(struct archive_write_disk *a, const char *buff,
1311 size_t size)
1312 {
1313 unsigned char *buffer_compressed;
1314 size_t bytes_compressed;
1315 size_t bytes_used;
1316 int ret;
1317
1318 ret = hfs_reset_compressor(a);
1319 if (ret != ARCHIVE_OK)
1320 return (ret);
1321
1322 if (a->compressed_buffer == NULL) {
1323 size_t block_size;
1324
1325 block_size = COMPRESSED_W_SIZE + RSRC_F_SIZE +
1326 + compressBound(MAX_DECMPFS_BLOCK_SIZE);
1327 a->compressed_buffer = malloc(block_size);
1328 if (a->compressed_buffer == NULL) {
1329 archive_set_error(&a->archive, ENOMEM,
1330 "Can't allocate memory for Resource Fork");
1331 return (ARCHIVE_FATAL);
1332 }
1333 a->compressed_buffer_size = block_size;
1334 a->compressed_buffer_remaining = block_size;
1335 }
1336
1337 buffer_compressed = a->compressed_buffer +
1338 a->compressed_buffer_size - a->compressed_buffer_remaining;
1339 a->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
1340 a->stream.avail_in = size;
1341 a->stream.next_out = buffer_compressed;
1342 a->stream.avail_out = a->compressed_buffer_remaining;
1343 do {
1344 ret = deflate(&a->stream, Z_FINISH);
1345 switch (ret) {
1346 case Z_OK:
1347 case Z_STREAM_END:
1348 break;
1349 default:
1350 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1351 "Failed to compress data");
1352 return (ARCHIVE_FAILED);
1353 }
1354 } while (ret == Z_OK);
1355 bytes_compressed = a->compressed_buffer_remaining - a->stream.avail_out;
1356
1357 /*
1358 * If the compressed size is larger than the original size,
1359 * throw away compressed data, use uncompressed data instead.
1360 */
1361 if (bytes_compressed > size) {
1362 buffer_compressed[0] = 0xFF;/* uncompressed marker. */
1363 memcpy(buffer_compressed + 1, buff, size);
1364 bytes_compressed = size + 1;
1365 }
1366 a->compressed_buffer_remaining -= bytes_compressed;
1367
1368 /*
1369 * If the compressed size is smaller than MAX_DECMPFS_XATTR_SIZE
1370 * and the block count in the file is only one, store compressed
1371 * data to decmpfs xattr instead of the resource fork.
1372 */
1373 if (a->decmpfs_block_count == 1 &&
1374 (a->decmpfs_attr_size + bytes_compressed)
1375 <= MAX_DECMPFS_XATTR_SIZE) {
1376 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1377 CMP_XATTR);
1378 memcpy(a->decmpfs_header_p + DECMPFS_HEADER_SIZE,
1379 buffer_compressed, bytes_compressed);
1380 a->decmpfs_attr_size += bytes_compressed;
1381 a->compressed_buffer_remaining = a->compressed_buffer_size;
1382 /*
1383 * Finish HFS+ Compression.
1384 * - Write the decmpfs xattr.
1385 * - Set the UF_COMPRESSED file flag.
1386 */
1387 ret = hfs_write_decmpfs(a);
1388 if (ret == ARCHIVE_OK)
1389 ret = hfs_set_compressed_fflag(a);
1390 return (ret);
1391 }
1392
1393 /* Update block info. */
1394 archive_le32enc(a->decmpfs_block_info++,
1395 a->compressed_rsrc_position_v - RSRC_H_SIZE);
1396 archive_le32enc(a->decmpfs_block_info++, bytes_compressed);
1397 a->compressed_rsrc_position_v += bytes_compressed;
1398
1399 /*
1400 * Write the compressed data to the resource fork.
1401 */
1402 bytes_used = a->compressed_buffer_size - a->compressed_buffer_remaining;
1403 while (bytes_used >= COMPRESSED_W_SIZE) {
1404 ret = hfs_write_compressed_data(a, COMPRESSED_W_SIZE);
1405 if (ret != ARCHIVE_OK)
1406 return (ret);
1407 bytes_used -= COMPRESSED_W_SIZE;
1408 if (bytes_used > COMPRESSED_W_SIZE)
1409 memmove(a->compressed_buffer,
1410 a->compressed_buffer + COMPRESSED_W_SIZE,
1411 bytes_used);
1412 else
1413 memcpy(a->compressed_buffer,
1414 a->compressed_buffer + COMPRESSED_W_SIZE,
1415 bytes_used);
1416 }
1417 a->compressed_buffer_remaining = a->compressed_buffer_size - bytes_used;
1418
1419 /*
1420 * If the current block is the last block, write the remaining
1421 * compressed data and the resource fork footer.
1422 */
1423 if (a->file_remaining_bytes == 0) {
1424 size_t rsrc_size;
1425 int64_t bk;
1426
1427 /* Append the resource footer. */
1428 rsrc_size = hfs_set_resource_fork_footer(
1429 a->compressed_buffer + bytes_used,
1430 a->compressed_buffer_remaining);
1431 ret = hfs_write_compressed_data(a, bytes_used + rsrc_size);
1432 a->compressed_buffer_remaining = a->compressed_buffer_size;
1433
1434 /* If the compressed size is not enough smaller than
1435 * the uncompressed size. cancel HFS+ compression.
1436 * TODO: study a behavior of ditto utility and improve
1437 * the condition to fall back into no HFS+ compression. */
1438 bk = HFS_BLOCKS(a->compressed_rsrc_position);
1439 bk += bk >> 7;
1440 if (bk > HFS_BLOCKS(a->filesize))
1441 return hfs_decompress(a);
1442 /*
1443 * Write the resourcefork header.
1444 */
1445 if (ret == ARCHIVE_OK)
1446 ret = hfs_write_resource_fork_header(a);
1447 /*
1448 * Finish HFS+ Compression.
1449 * - Write the decmpfs xattr.
1450 * - Set the UF_COMPRESSED file flag.
1451 */
1452 if (ret == ARCHIVE_OK)
1453 ret = hfs_write_decmpfs(a);
1454 if (ret == ARCHIVE_OK)
1455 ret = hfs_set_compressed_fflag(a);
1456 }
1457 return (ret);
1458 }
1459
1460 static ssize_t
hfs_write_decmpfs_block(struct archive_write_disk * a,const char * buff,size_t size)1461 hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff,
1462 size_t size)
1463 {
1464 const char *buffer_to_write;
1465 size_t bytes_to_write;
1466 int ret;
1467
1468 if (a->decmpfs_block_count == (unsigned)-1) {
1469 void *new_block;
1470 size_t new_size;
1471 unsigned int block_count;
1472
1473 if (a->decmpfs_header_p == NULL) {
1474 new_block = malloc(MAX_DECMPFS_XATTR_SIZE
1475 + sizeof(uint32_t));
1476 if (new_block == NULL) {
1477 archive_set_error(&a->archive, ENOMEM,
1478 "Can't allocate memory for decmpfs");
1479 return (ARCHIVE_FATAL);
1480 }
1481 a->decmpfs_header_p = new_block;
1482 }
1483 a->decmpfs_attr_size = DECMPFS_HEADER_SIZE;
1484 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC],
1485 DECMPFS_MAGIC);
1486 archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE],
1487 CMP_RESOURCE_FORK);
1488 archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE],
1489 a->filesize);
1490
1491 /* Calculate a block count of the file. */
1492 block_count =
1493 (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) /
1494 MAX_DECMPFS_BLOCK_SIZE;
1495 /*
1496 * Allocate buffer for resource fork.
1497 * Set up related pointers;
1498 */
1499 new_size =
1500 RSRC_H_SIZE + /* header */
1501 4 + /* Block count */
1502 (block_count * sizeof(uint32_t) * 2) +
1503 RSRC_F_SIZE; /* footer */
1504 if (new_size > a->resource_fork_allocated_size) {
1505 new_block = realloc(a->resource_fork, new_size);
1506 if (new_block == NULL) {
1507 archive_set_error(&a->archive, ENOMEM,
1508 "Can't allocate memory for ResourceFork");
1509 return (ARCHIVE_FATAL);
1510 }
1511 a->resource_fork_allocated_size = new_size;
1512 a->resource_fork = new_block;
1513 }
1514
1515 /* Allocate uncompressed buffer */
1516 if (a->uncompressed_buffer == NULL) {
1517 new_block = malloc(MAX_DECMPFS_BLOCK_SIZE);
1518 if (new_block == NULL) {
1519 archive_set_error(&a->archive, ENOMEM,
1520 "Can't allocate memory for decmpfs");
1521 return (ARCHIVE_FATAL);
1522 }
1523 a->uncompressed_buffer = new_block;
1524 }
1525 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1526 a->file_remaining_bytes = a->filesize;
1527 a->compressed_buffer_remaining = a->compressed_buffer_size;
1528
1529 /*
1530 * Set up a resource fork.
1531 */
1532 a->rsrc_xattr_options = XATTR_CREATE;
1533 /* Get the position where we are going to set a bunch
1534 * of block info. */
1535 a->decmpfs_block_info =
1536 (uint32_t *)(a->resource_fork + RSRC_H_SIZE);
1537 /* Set the block count to the resource fork. */
1538 archive_le32enc(a->decmpfs_block_info++, block_count);
1539 /* Get the position where we are going to set compressed
1540 * data. */
1541 a->compressed_rsrc_position =
1542 RSRC_H_SIZE + 4 + (block_count * 8);
1543 a->compressed_rsrc_position_v = a->compressed_rsrc_position;
1544 a->decmpfs_block_count = block_count;
1545 }
1546
1547 /* Ignore redundant bytes. */
1548 if (a->file_remaining_bytes == 0)
1549 return ((ssize_t)size);
1550
1551 /* Do not overrun a block size. */
1552 if (size > a->block_remaining_bytes)
1553 bytes_to_write = a->block_remaining_bytes;
1554 else
1555 bytes_to_write = size;
1556 /* Do not overrun the file size. */
1557 if (bytes_to_write > a->file_remaining_bytes)
1558 bytes_to_write = a->file_remaining_bytes;
1559
1560 /* For efficiency, if a copy length is full of the uncompressed
1561 * buffer size, do not copy writing data to it. */
1562 if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE)
1563 buffer_to_write = buff;
1564 else {
1565 memcpy(a->uncompressed_buffer +
1566 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes,
1567 buff, bytes_to_write);
1568 buffer_to_write = a->uncompressed_buffer;
1569 }
1570 a->block_remaining_bytes -= bytes_to_write;
1571 a->file_remaining_bytes -= bytes_to_write;
1572
1573 if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) {
1574 ret = hfs_drive_compressor(a, buffer_to_write,
1575 MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes);
1576 if (ret < 0)
1577 return (ret);
1578 a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE;
1579 }
1580 /* Ignore redundant bytes. */
1581 if (a->file_remaining_bytes == 0)
1582 return ((ssize_t)size);
1583 return (bytes_to_write);
1584 }
1585
1586 static ssize_t
hfs_write_data_block(struct archive_write_disk * a,const char * buff,size_t size)1587 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1588 size_t size)
1589 {
1590 uint64_t start_size = size;
1591 ssize_t bytes_written = 0;
1592 ssize_t bytes_to_write;
1593
1594 if (size == 0)
1595 return (ARCHIVE_OK);
1596
1597 if (a->filesize == 0 || a->fd < 0) {
1598 archive_set_error(&a->archive, 0,
1599 "Attempt to write to an empty file");
1600 return (ARCHIVE_WARN);
1601 }
1602
1603 /* If this write would run beyond the file size, truncate it. */
1604 if (a->filesize >= 0 && (int64_t)(a->offset + size) > a->filesize)
1605 start_size = size = (size_t)(a->filesize - a->offset);
1606
1607 /* Write the data. */
1608 while (size > 0) {
1609 bytes_to_write = size;
1610 /* Seek if necessary to the specified offset. */
1611 if (a->offset < a->fd_offset) {
1612 /* Can't support backward move. */
1613 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1614 "Seek failed");
1615 return (ARCHIVE_FATAL);
1616 } else if (a->offset > a->fd_offset) {
1617 uint64_t skip = a->offset - a->fd_offset;
1618 char nullblock[1024];
1619
1620 memset(nullblock, 0, sizeof(nullblock));
1621 while (skip > 0) {
1622 if (skip > sizeof(nullblock))
1623 bytes_written = hfs_write_decmpfs_block(
1624 a, nullblock, sizeof(nullblock));
1625 else
1626 bytes_written = hfs_write_decmpfs_block(
1627 a, nullblock, skip);
1628 if (bytes_written < 0) {
1629 archive_set_error(&a->archive, errno,
1630 "Write failed");
1631 return (ARCHIVE_WARN);
1632 }
1633 skip -= bytes_written;
1634 }
1635
1636 a->fd_offset = a->offset;
1637 }
1638 bytes_written =
1639 hfs_write_decmpfs_block(a, buff, bytes_to_write);
1640 if (bytes_written < 0)
1641 return (bytes_written);
1642 buff += bytes_written;
1643 size -= bytes_written;
1644 a->total_bytes_written += bytes_written;
1645 a->offset += bytes_written;
1646 a->fd_offset = a->offset;
1647 }
1648 return (start_size - size);
1649 }
1650 #else
1651 static ssize_t
hfs_write_data_block(struct archive_write_disk * a,const char * buff,size_t size)1652 hfs_write_data_block(struct archive_write_disk *a, const char *buff,
1653 size_t size)
1654 {
1655 return (write_data_block(a, buff, size));
1656 }
1657 #endif
1658
1659 static ssize_t
_archive_write_disk_data_block(struct archive * _a,const void * buff,size_t size,int64_t offset)1660 _archive_write_disk_data_block(struct archive *_a,
1661 const void *buff, size_t size, int64_t offset)
1662 {
1663 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1664 ssize_t r;
1665
1666 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1667 ARCHIVE_STATE_DATA, "archive_write_data_block");
1668
1669 a->offset = offset;
1670 if (a->todo & TODO_HFS_COMPRESSION)
1671 r = hfs_write_data_block(a, buff, size);
1672 else
1673 r = write_data_block(a, buff, size);
1674 if (r < ARCHIVE_OK)
1675 return (r);
1676 if ((size_t)r < size) {
1677 archive_set_error(&a->archive, 0,
1678 "Too much data: Truncating file at %ju bytes",
1679 (uintmax_t)a->filesize);
1680 return (ARCHIVE_WARN);
1681 }
1682 #if ARCHIVE_VERSION_NUMBER < 3999000
1683 return (ARCHIVE_OK);
1684 #else
1685 return (size);
1686 #endif
1687 }
1688
1689 static ssize_t
_archive_write_disk_data(struct archive * _a,const void * buff,size_t size)1690 _archive_write_disk_data(struct archive *_a, const void *buff, size_t size)
1691 {
1692 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1693
1694 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1695 ARCHIVE_STATE_DATA, "archive_write_data");
1696
1697 if (a->todo & TODO_HFS_COMPRESSION)
1698 return (hfs_write_data_block(a, buff, size));
1699 return (write_data_block(a, buff, size));
1700 }
1701
1702 static int
_archive_write_disk_finish_entry(struct archive * _a)1703 _archive_write_disk_finish_entry(struct archive *_a)
1704 {
1705 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1706 int ret = ARCHIVE_OK;
1707
1708 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1709 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1710 "archive_write_finish_entry");
1711 if (a->archive.state & ARCHIVE_STATE_HEADER)
1712 return (ARCHIVE_OK);
1713 archive_clear_error(&a->archive);
1714
1715 /* Pad or truncate file to the right size. */
1716 if (a->fd < 0) {
1717 /* There's no file. */
1718 } else if (a->filesize < 0) {
1719 /* File size is unknown, so we can't set the size. */
1720 } else if (a->fd_offset == a->filesize) {
1721 /* Last write ended at exactly the filesize; we're done. */
1722 /* Hopefully, this is the common case. */
1723 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_ZLIB_H)
1724 } else if (a->todo & TODO_HFS_COMPRESSION) {
1725 char null_d[1024];
1726 ssize_t r;
1727
1728 if (a->file_remaining_bytes)
1729 memset(null_d, 0, sizeof(null_d));
1730 while (a->file_remaining_bytes) {
1731 if (a->file_remaining_bytes > sizeof(null_d))
1732 r = hfs_write_data_block(
1733 a, null_d, sizeof(null_d));
1734 else
1735 r = hfs_write_data_block(
1736 a, null_d, a->file_remaining_bytes);
1737 if (r < 0) {
1738 close_file_descriptor(a);
1739 return ((int)r);
1740 }
1741 }
1742 #endif
1743 } else {
1744 #if HAVE_FTRUNCATE
1745 if (ftruncate(a->fd, a->filesize) == -1 &&
1746 a->filesize == 0) {
1747 archive_set_error(&a->archive, errno,
1748 "File size could not be restored");
1749 close_file_descriptor(a);
1750 return (ARCHIVE_FAILED);
1751 }
1752 #endif
1753 /*
1754 * Not all platforms implement the XSI option to
1755 * extend files via ftruncate. Stat() the file again
1756 * to see what happened.
1757 */
1758 a->pst = NULL;
1759 if ((ret = lazy_stat(a)) != ARCHIVE_OK) {
1760 close_file_descriptor(a);
1761 return (ret);
1762 }
1763 /* We can use lseek()/write() to extend the file if
1764 * ftruncate didn't work or isn't available. */
1765 if (a->st.st_size < a->filesize) {
1766 const char nul = '\0';
1767 if (lseek(a->fd, a->filesize - 1, SEEK_SET) < 0) {
1768 archive_set_error(&a->archive, errno,
1769 "Seek failed");
1770 close_file_descriptor(a);
1771 return (ARCHIVE_FATAL);
1772 }
1773 if (write(a->fd, &nul, 1) < 0) {
1774 archive_set_error(&a->archive, errno,
1775 "Write to restore size failed");
1776 close_file_descriptor(a);
1777 return (ARCHIVE_FATAL);
1778 }
1779 a->pst = NULL;
1780 }
1781 }
1782
1783 /* Restore metadata. */
1784
1785 /*
1786 * This is specific to Mac OS X.
1787 * If the current file is an AppleDouble file, it should be
1788 * linked with the data fork file and remove it.
1789 */
1790 if (a->todo & TODO_APPLEDOUBLE) {
1791 int r2 = fixup_appledouble(a, a->name);
1792 if (r2 == ARCHIVE_EOF) {
1793 /* The current file has been successfully linked
1794 * with the data fork file and removed. So there
1795 * is nothing to do on the current file. */
1796 goto finish_metadata;
1797 }
1798 if (r2 < ret) ret = r2;
1799 }
1800
1801 /*
1802 * Look up the "real" UID only if we're going to need it.
1803 * TODO: the TODO_SGID condition can be dropped here, can't it?
1804 */
1805 if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
1806 a->uid = archive_write_disk_uid(&a->archive,
1807 archive_entry_uname(a->entry),
1808 archive_entry_uid(a->entry));
1809 }
1810 /* Look up the "real" GID only if we're going to need it. */
1811 /* TODO: the TODO_SUID condition can be dropped here, can't it? */
1812 if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
1813 a->gid = archive_write_disk_gid(&a->archive,
1814 archive_entry_gname(a->entry),
1815 archive_entry_gid(a->entry));
1816 }
1817
1818 /*
1819 * Restore ownership before set_mode tries to restore suid/sgid
1820 * bits. If we set the owner, we know what it is and can skip
1821 * a stat() call to examine the ownership of the file on disk.
1822 */
1823 if (a->todo & TODO_OWNER) {
1824 int r2 = set_ownership(a);
1825 if (r2 < ret) ret = r2;
1826 }
1827
1828 /*
1829 * HYPOTHESIS:
1830 * If we're not root, we won't be setting any security
1831 * attributes that may be wiped by the set_mode() routine
1832 * below. We also can't set xattr on non-owner-writable files,
1833 * which may be the state after set_mode(). Perform
1834 * set_xattrs() first based on these constraints.
1835 */
1836 if (a->user_uid != 0 &&
1837 (a->todo & TODO_XATTR)) {
1838 int r2 = set_xattrs(a);
1839 if (r2 < ret) ret = r2;
1840 }
1841
1842 /*
1843 * set_mode must precede ACLs on systems such as Solaris and
1844 * FreeBSD where setting the mode implicitly clears extended ACLs
1845 */
1846 if (a->todo & TODO_MODE) {
1847 int r2 = set_mode(a, a->mode);
1848 if (r2 < ret) ret = r2;
1849 }
1850
1851 /*
1852 * Security-related extended attributes (such as
1853 * security.capability on Linux) have to be restored last,
1854 * since they're implicitly removed by other file changes.
1855 * We do this last only when root.
1856 */
1857 if (a->user_uid == 0 &&
1858 (a->todo & TODO_XATTR)) {
1859 int r2 = set_xattrs(a);
1860 if (r2 < ret) ret = r2;
1861 }
1862
1863 /*
1864 * Some flags prevent file modification; they must be restored after
1865 * file contents are written.
1866 */
1867 if (a->todo & TODO_FFLAGS) {
1868 int r2 = set_fflags(a);
1869 if (r2 < ret) ret = r2;
1870 }
1871
1872 /*
1873 * Time must follow most other metadata;
1874 * otherwise atime will get changed.
1875 */
1876 if (a->todo & TODO_TIMES) {
1877 int r2 = set_times_from_entry(a);
1878 if (r2 < ret) ret = r2;
1879 }
1880
1881 /*
1882 * Mac extended metadata includes ACLs.
1883 */
1884 if (a->todo & TODO_MAC_METADATA) {
1885 const void *metadata;
1886 size_t metadata_size;
1887 metadata = archive_entry_mac_metadata(a->entry, &metadata_size);
1888 if (metadata != NULL && metadata_size > 0) {
1889 int r2 = set_mac_metadata(a, archive_entry_pathname(
1890 a->entry), metadata, metadata_size);
1891 if (r2 < ret) ret = r2;
1892 }
1893 }
1894
1895 /*
1896 * ACLs must be restored after timestamps because there are
1897 * ACLs that prevent attribute changes (including time).
1898 */
1899 if (a->todo & TODO_ACLS) {
1900 int r2;
1901 r2 = archive_write_disk_set_acls(&a->archive, a->fd,
1902 archive_entry_pathname(a->entry),
1903 archive_entry_acl(a->entry),
1904 archive_entry_mode(a->entry));
1905 if (r2 < ret) ret = r2;
1906 }
1907
1908 finish_metadata:
1909 /* If there's an fd, we can close it now. */
1910 if (a->fd >= 0) {
1911 close(a->fd);
1912 a->fd = -1;
1913 if (a->tmpname) {
1914 if (rename(a->tmpname, a->name) == -1) {
1915 archive_set_error(&a->archive, errno,
1916 "Failed to rename temporary file");
1917 ret = ARCHIVE_FAILED;
1918 unlink(a->tmpname);
1919 }
1920 a->tmpname = NULL;
1921 }
1922 }
1923 /* If there's an entry, we can release it now. */
1924 archive_entry_free(a->entry);
1925 a->entry = NULL;
1926 a->archive.state = ARCHIVE_STATE_HEADER;
1927 return (ret);
1928 }
1929
1930 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))1931 archive_write_disk_set_group_lookup(struct archive *_a,
1932 void *private_data,
1933 la_int64_t (*lookup_gid)(void *private, const char *gname, la_int64_t gid),
1934 void (*cleanup_gid)(void *private))
1935 {
1936 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1937 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1938 ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
1939
1940 if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1941 (a->cleanup_gid)(a->lookup_gid_data);
1942
1943 a->lookup_gid = lookup_gid;
1944 a->cleanup_gid = cleanup_gid;
1945 a->lookup_gid_data = private_data;
1946 return (ARCHIVE_OK);
1947 }
1948
1949 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))1950 archive_write_disk_set_user_lookup(struct archive *_a,
1951 void *private_data,
1952 int64_t (*lookup_uid)(void *private, const char *uname, int64_t uid),
1953 void (*cleanup_uid)(void *private))
1954 {
1955 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1956 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1957 ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
1958
1959 if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1960 (a->cleanup_uid)(a->lookup_uid_data);
1961
1962 a->lookup_uid = lookup_uid;
1963 a->cleanup_uid = cleanup_uid;
1964 a->lookup_uid_data = private_data;
1965 return (ARCHIVE_OK);
1966 }
1967
1968 int64_t
archive_write_disk_gid(struct archive * _a,const char * name,la_int64_t id)1969 archive_write_disk_gid(struct archive *_a, const char *name, la_int64_t id)
1970 {
1971 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1972 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1973 ARCHIVE_STATE_ANY, "archive_write_disk_gid");
1974 if (a->lookup_gid)
1975 return (a->lookup_gid)(a->lookup_gid_data, name, id);
1976 return (id);
1977 }
1978
1979 int64_t
archive_write_disk_uid(struct archive * _a,const char * name,la_int64_t id)1980 archive_write_disk_uid(struct archive *_a, const char *name, la_int64_t id)
1981 {
1982 struct archive_write_disk *a = (struct archive_write_disk *)_a;
1983 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1984 ARCHIVE_STATE_ANY, "archive_write_disk_uid");
1985 if (a->lookup_uid)
1986 return (a->lookup_uid)(a->lookup_uid_data, name, id);
1987 return (id);
1988 }
1989
1990 /*
1991 * Create a new archive_write_disk object and initialize it with global state.
1992 */
1993 struct archive *
archive_write_disk_new(void)1994 archive_write_disk_new(void)
1995 {
1996 struct archive_write_disk *a;
1997
1998 a = calloc(1, sizeof(*a));
1999 if (a == NULL)
2000 return (NULL);
2001 a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
2002 /* We're ready to write a header immediately. */
2003 a->archive.state = ARCHIVE_STATE_HEADER;
2004 a->archive.vtable = &archive_write_disk_vtable;
2005 a->start_time = time(NULL);
2006 /* Query and restore the umask. */
2007 umask(a->user_umask = umask(0));
2008 #ifdef HAVE_GETEUID
2009 a->user_uid = geteuid();
2010 #endif /* HAVE_GETEUID */
2011 if (archive_string_ensure(&a->path_safe, 512) == NULL) {
2012 free(a);
2013 return (NULL);
2014 }
2015 a->path_safe.s[0] = 0;
2016
2017 #ifdef HAVE_ZLIB_H
2018 a->decmpfs_compression_level = 5;
2019 #endif
2020 return (&a->archive);
2021 }
2022
2023
2024 /*
2025 * If pathname is longer than PATH_MAX, chdir to a suitable
2026 * intermediate dir and edit the path down to a shorter suffix. Note
2027 * that this routine never returns an error; if the chdir() attempt
2028 * fails for any reason, we just go ahead with the long pathname. The
2029 * object creation is likely to fail, but any error will get handled
2030 * at that time.
2031 */
2032 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
2033 static void
edit_deep_directories(struct archive_write_disk * a)2034 edit_deep_directories(struct archive_write_disk *a)
2035 {
2036 int ret;
2037 char *tail = a->name;
2038
2039 /* If path is short, avoid the open() below. */
2040 if (strlen(tail) < PATH_MAX)
2041 return;
2042
2043 /* Try to record our starting dir. */
2044 a->restore_pwd = la_opendirat(AT_FDCWD, ".");
2045 __archive_ensure_cloexec_flag(a->restore_pwd);
2046 if (a->restore_pwd < 0)
2047 return;
2048
2049 /* As long as the path is too long... */
2050 while (strlen(tail) >= PATH_MAX) {
2051 /* Locate a dir prefix shorter than PATH_MAX. */
2052 tail += PATH_MAX - 8;
2053 while (tail > a->name && *tail != '/')
2054 tail--;
2055 /* Exit if we find a too-long path component. */
2056 if (tail <= a->name)
2057 return;
2058 /* Create the intermediate dir and chdir to it. */
2059 *tail = '\0'; /* Terminate dir portion */
2060 ret = create_dir(a, a->name);
2061 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
2062 ret = ARCHIVE_FAILED;
2063 *tail = '/'; /* Restore the / we removed. */
2064 if (ret != ARCHIVE_OK)
2065 return;
2066 tail++;
2067 /* The chdir() succeeded; we've now shortened the path. */
2068 a->name = tail;
2069 }
2070 return;
2071 }
2072 #endif
2073
2074 /*
2075 * The main restore function.
2076 */
2077 static int
restore_entry(struct archive_write_disk * a)2078 restore_entry(struct archive_write_disk *a)
2079 {
2080 int ret = ARCHIVE_OK, en;
2081
2082 if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
2083 /*
2084 * TODO: Fix this. Apparently, there are platforms
2085 * that still allow root to hose the entire filesystem
2086 * by unlinking a dir. The S_ISDIR() test above
2087 * prevents us from using unlink() here if the new
2088 * object is a dir, but that doesn't mean the old
2089 * object isn't a dir.
2090 */
2091 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2092 (void)clear_nochange_fflags(a);
2093 if (unlink(a->name) == 0) {
2094 /* We removed it, reset cached stat. */
2095 a->pst = NULL;
2096 } else if (errno == ENOENT) {
2097 /* File didn't exist, that's just as good. */
2098 } else if (rmdir(a->name) == 0) {
2099 /* It was a dir, but now it's gone. */
2100 a->pst = NULL;
2101 } else {
2102 /* We tried, but couldn't get rid of it. */
2103 archive_set_error(&a->archive, errno,
2104 "Could not unlink");
2105 return(ARCHIVE_FAILED);
2106 }
2107 }
2108
2109 /* Try creating it first; if this fails, we'll try to recover. */
2110 en = create_filesystem_object(a);
2111
2112 if ((en == ENOTDIR || en == ENOENT)
2113 && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
2114 /* If the parent dir doesn't exist, try creating it. */
2115 create_parent_dir(a, a->name);
2116 /* Now try to create the object again. */
2117 en = create_filesystem_object(a);
2118 }
2119
2120 if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) {
2121 archive_set_error(&a->archive, en,
2122 "Hard-link target '%s' does not exist.",
2123 archive_entry_hardlink(a->entry));
2124 return (ARCHIVE_FAILED);
2125 }
2126
2127 if ((en == EISDIR || en == EEXIST)
2128 && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
2129 /* If we're not overwriting, we're done. */
2130 if (S_ISDIR(a->mode)) {
2131 /* Don't overwrite any settings on existing directories. */
2132 a->todo = 0;
2133 }
2134 archive_entry_unset_size(a->entry);
2135 return (ARCHIVE_OK);
2136 }
2137
2138 /*
2139 * Some platforms return EISDIR if you call
2140 * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
2141 * return EEXIST. POSIX is ambiguous, requiring EISDIR
2142 * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
2143 * on an existing item.
2144 */
2145 if (en == EISDIR) {
2146 /* A dir is in the way of a non-dir, rmdir it. */
2147 if (rmdir(a->name) != 0) {
2148 archive_set_error(&a->archive, errno,
2149 "Can't remove already-existing dir");
2150 return (ARCHIVE_FAILED);
2151 }
2152 a->pst = NULL;
2153 /* Try again. */
2154 en = create_filesystem_object(a);
2155 } else if (en == EEXIST) {
2156 /*
2157 * We know something is in the way, but we don't know what;
2158 * we need to find out before we go any further.
2159 */
2160 int r = 0;
2161 /*
2162 * The SECURE_SYMLINKS logic has already removed a
2163 * symlink to a dir if the client wants that. So
2164 * follow the symlink if we're creating a dir.
2165 */
2166 if (S_ISDIR(a->mode))
2167 r = la_stat(a->name, &a->st);
2168 /*
2169 * If it's not a dir (or it's a broken symlink),
2170 * then don't follow it.
2171 */
2172 if (r != 0 || !S_ISDIR(a->mode))
2173 #ifdef HAVE_LSTAT
2174 r = lstat(a->name, &a->st);
2175 #else
2176 r = la_stat(a->name, &a->st);
2177 #endif
2178 if (r != 0) {
2179 archive_set_error(&a->archive, errno,
2180 "Can't stat existing object");
2181 return (ARCHIVE_FAILED);
2182 }
2183
2184 /*
2185 * NO_OVERWRITE_NEWER doesn't apply to directories.
2186 */
2187 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
2188 && !S_ISDIR(a->st.st_mode)) {
2189 if (!older(&(a->st), a->entry)) {
2190 archive_entry_unset_size(a->entry);
2191 return (ARCHIVE_OK);
2192 }
2193 }
2194
2195 /* If it's our archive, we're done. */
2196 if (a->skip_file_set &&
2197 a->st.st_dev == (dev_t)a->skip_file_dev &&
2198 a->st.st_ino == (ino_t)a->skip_file_ino) {
2199 archive_set_error(&a->archive, 0,
2200 "Refusing to overwrite archive");
2201 return (ARCHIVE_FAILED);
2202 }
2203
2204 if (!S_ISDIR(a->st.st_mode)) {
2205 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2206 (void)clear_nochange_fflags(a);
2207
2208 if ((a->flags & ARCHIVE_EXTRACT_SAFE_WRITES) &&
2209 S_ISREG(a->mode)) {
2210 /* Use a temporary file to extract */
2211 if ((a->fd = la_mktemp(a)) == -1) {
2212 archive_set_error(&a->archive, errno,
2213 "Can't create temporary file");
2214 return ARCHIVE_FAILED;
2215 }
2216 a->pst = NULL;
2217 en = 0;
2218 } else {
2219 /* A non-dir is in the way, unlink it. */
2220 if (unlink(a->name) != 0) {
2221 archive_set_error(&a->archive, errno,
2222 "Can't unlink already-existing "
2223 "object");
2224 return (ARCHIVE_FAILED);
2225 }
2226 a->pst = NULL;
2227 /* Try again. */
2228 en = create_filesystem_object(a);
2229 }
2230 } else if (!S_ISDIR(a->mode)) {
2231 /* A dir is in the way of a non-dir, rmdir it. */
2232 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
2233 (void)clear_nochange_fflags(a);
2234 if (rmdir(a->name) != 0) {
2235 archive_set_error(&a->archive, errno,
2236 "Can't replace existing directory with non-directory");
2237 return (ARCHIVE_FAILED);
2238 }
2239 /* Try again. */
2240 en = create_filesystem_object(a);
2241 } else {
2242 /*
2243 * There's a dir in the way of a dir. Don't
2244 * waste time with rmdir()/mkdir(), just fix
2245 * up the permissions on the existing dir.
2246 * Note that we don't change perms on existing
2247 * dirs unless _EXTRACT_PERM is specified.
2248 */
2249 if ((a->mode != a->st.st_mode)
2250 && (a->todo & TODO_MODE_FORCE))
2251 a->deferred |= (a->todo & TODO_MODE);
2252 /* Ownership doesn't need deferred fixup. */
2253 en = 0; /* Forget the EEXIST. */
2254 }
2255 }
2256
2257 if (en) {
2258 /* Everything failed; give up here. */
2259 if ((&a->archive)->error == NULL)
2260 archive_set_error(&a->archive, en, "Can't create '%s'",
2261 a->name);
2262 return (ARCHIVE_FAILED);
2263 }
2264
2265 a->pst = NULL; /* Cached stat data no longer valid. */
2266 return (ret);
2267 }
2268
2269 /*
2270 * Returns 0 if creation succeeds, or else returns errno value from
2271 * the failed system call. Note: This function should only ever perform
2272 * a single system call.
2273 */
2274 static int
create_filesystem_object(struct archive_write_disk * a)2275 create_filesystem_object(struct archive_write_disk *a)
2276 {
2277 /* Create the entry. */
2278 const char *linkname;
2279 mode_t final_mode, mode;
2280 int r;
2281 /* these for check_symlinks_fsobj */
2282 char *linkname_copy; /* non-const copy of linkname */
2283 struct stat st;
2284 struct archive_string error_string;
2285 int error_number;
2286
2287 /* We identify hard/symlinks according to the link names. */
2288 /* Since link(2) and symlink(2) don't handle modes, we're done here. */
2289 linkname = archive_entry_hardlink(a->entry);
2290 if (linkname != NULL) {
2291 #if !HAVE_LINK
2292 return (EPERM);
2293 #else
2294 archive_string_init(&error_string);
2295 linkname_copy = strdup(linkname);
2296 if (linkname_copy == NULL) {
2297 return (EPERM);
2298 }
2299 /*
2300 * TODO: consider using the cleaned-up path as the link
2301 * target?
2302 */
2303 r = cleanup_pathname_fsobj(linkname_copy, &error_number,
2304 &error_string, a->flags);
2305 if (r != ARCHIVE_OK) {
2306 archive_set_error(&a->archive, error_number, "%s",
2307 error_string.s);
2308 free(linkname_copy);
2309 archive_string_free(&error_string);
2310 /*
2311 * EPERM is more appropriate than error_number for our
2312 * callers
2313 */
2314 return (EPERM);
2315 }
2316 r = check_symlinks_fsobj(linkname_copy, &error_number,
2317 &error_string, a->flags, 1);
2318 if (r != ARCHIVE_OK) {
2319 archive_set_error(&a->archive, error_number, "%s",
2320 error_string.s);
2321 free(linkname_copy);
2322 archive_string_free(&error_string);
2323 /*
2324 * EPERM is more appropriate than error_number for our
2325 * callers
2326 */
2327 return (EPERM);
2328 }
2329 free(linkname_copy);
2330 archive_string_free(&error_string);
2331 /*
2332 * Unlinking and linking here is really not atomic,
2333 * but doing it right, would require us to construct
2334 * an mktemplink() function, and then use rename(2).
2335 */
2336 if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2337 unlink(a->name);
2338 #ifdef HAVE_LINKAT
2339 r = linkat(AT_FDCWD, linkname, AT_FDCWD, a->name,
2340 0) ? errno : 0;
2341 #else
2342 r = link(linkname, a->name) ? errno : 0;
2343 #endif
2344 /*
2345 * New cpio and pax formats allow hardlink entries
2346 * to carry data, so we may have to open the file
2347 * for hardlink entries.
2348 *
2349 * If the hardlink was successfully created and
2350 * the archive doesn't have carry data for it,
2351 * consider it to be non-authoritative for meta data.
2352 * This is consistent with GNU tar and BSD pax.
2353 * If the hardlink does carry data, let the last
2354 * archive entry decide ownership.
2355 */
2356 if (r == 0 && a->filesize <= 0) {
2357 a->todo = 0;
2358 a->deferred = 0;
2359 } else if (r == 0 && a->filesize > 0) {
2360 #ifdef HAVE_LSTAT
2361 r = lstat(a->name, &st);
2362 #else
2363 r = la_stat(a->name, &st);
2364 #endif
2365 if (r != 0)
2366 r = errno;
2367 else if ((st.st_mode & AE_IFMT) == AE_IFREG) {
2368 a->fd = open(a->name, O_WRONLY | O_TRUNC |
2369 O_BINARY | O_CLOEXEC | O_NOFOLLOW);
2370 __archive_ensure_cloexec_flag(a->fd);
2371 if (a->fd < 0)
2372 r = errno;
2373 }
2374 }
2375 return (r);
2376 #endif
2377 }
2378 linkname = archive_entry_symlink(a->entry);
2379 if (linkname != NULL) {
2380 #if HAVE_SYMLINK
2381 /*
2382 * Unlinking and linking here is really not atomic,
2383 * but doing it right, would require us to construct
2384 * an mktempsymlink() function, and then use rename(2).
2385 */
2386 if (a->flags & ARCHIVE_EXTRACT_SAFE_WRITES)
2387 unlink(a->name);
2388 return symlink(linkname, a->name) ? errno : 0;
2389 #else
2390 return (EPERM);
2391 #endif
2392 }
2393
2394 /*
2395 * The remaining system calls all set permissions, so let's
2396 * try to take advantage of that to avoid an extra chmod()
2397 * call. (Recall that umask is set to zero right now!)
2398 */
2399
2400 /* Mode we want for the final restored object (w/o file type bits). */
2401 final_mode = a->mode & 07777;
2402 /*
2403 * The mode that will actually be restored in this step. Note
2404 * that SUID, SGID, etc, require additional work to ensure
2405 * security, so we never restore them at this point.
2406 */
2407 mode = final_mode & 0777 & ~a->user_umask;
2408
2409 /*
2410 * Always create writable such that [f]setxattr() works if we're not
2411 * root.
2412 */
2413 if (a->user_uid != 0 &&
2414 a->todo & (TODO_HFS_COMPRESSION | TODO_XATTR)) {
2415 mode |= 0200;
2416 }
2417
2418 switch (a->mode & AE_IFMT) {
2419 default:
2420 /* POSIX requires that we fall through here. */
2421 /* FALLTHROUGH */
2422 case AE_IFREG:
2423 a->tmpname = NULL;
2424 a->fd = open(a->name,
2425 O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
2426 __archive_ensure_cloexec_flag(a->fd);
2427 r = (a->fd < 0);
2428 break;
2429 case AE_IFCHR:
2430 #ifdef HAVE_MKNOD
2431 /* Note: we use AE_IFCHR for the case label, and
2432 * S_IFCHR for the mknod() call. This is correct. */
2433 r = mknod(a->name, mode | S_IFCHR,
2434 archive_entry_rdev(a->entry));
2435 break;
2436 #else
2437 /* TODO: Find a better way to warn about our inability
2438 * to restore a char device node. */
2439 return (EINVAL);
2440 #endif /* HAVE_MKNOD */
2441 case AE_IFBLK:
2442 #ifdef HAVE_MKNOD
2443 r = mknod(a->name, mode | S_IFBLK,
2444 archive_entry_rdev(a->entry));
2445 break;
2446 #else
2447 /* TODO: Find a better way to warn about our inability
2448 * to restore a block device node. */
2449 return (EINVAL);
2450 #endif /* HAVE_MKNOD */
2451 case AE_IFDIR:
2452 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
2453 r = mkdir(a->name, mode);
2454 if (r == 0) {
2455 /* Defer setting dir times. */
2456 a->deferred |= (a->todo & TODO_TIMES);
2457 a->todo &= ~TODO_TIMES;
2458 /* Never use an immediate chmod(). */
2459 /* We can't avoid the chmod() entirely if EXTRACT_PERM
2460 * because of SysV SGID inheritance. */
2461 if ((mode != final_mode)
2462 || (a->flags & ARCHIVE_EXTRACT_PERM))
2463 a->deferred |= (a->todo & TODO_MODE);
2464 a->todo &= ~TODO_MODE;
2465 }
2466 break;
2467 case AE_IFIFO:
2468 #ifdef HAVE_MKFIFO
2469 r = mkfifo(a->name, mode);
2470 break;
2471 #else
2472 /* TODO: Find a better way to warn about our inability
2473 * to restore a fifo. */
2474 return (EINVAL);
2475 #endif /* HAVE_MKFIFO */
2476 }
2477
2478 /* All the system calls above set errno on failure. */
2479 if (r)
2480 return (errno);
2481
2482 /* If we managed to set the final mode, we've avoided a chmod(). */
2483 if (mode == final_mode)
2484 a->todo &= ~TODO_MODE;
2485 return (0);
2486 }
2487
2488 /*
2489 * Cleanup function for archive_extract. Mostly, this involves processing
2490 * the fixup list, which is used to address a number of problems:
2491 * * Dir permissions might prevent us from restoring a file in that
2492 * dir, so we restore the dir with minimum 0700 permissions first,
2493 * then correct the mode at the end.
2494 * * Similarly, the act of restoring a file touches the directory
2495 * and changes the timestamp on the dir, so we have to touch-up dir
2496 * timestamps at the end as well.
2497 * * Some file flags can interfere with the restore by, for example,
2498 * preventing the creation of hardlinks to those files.
2499 * * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
2500 *
2501 * Note that tar/cpio do not require that archives be in a particular
2502 * order; there is no way to know when the last file has been restored
2503 * within a directory, so there's no way to optimize the memory usage
2504 * here by fixing up the directory any earlier than the
2505 * end-of-archive.
2506 *
2507 * XXX TODO: Directory ACLs should be restored here, for the same
2508 * reason we set directory perms here. XXX
2509 */
2510 static int
_archive_write_disk_close(struct archive * _a)2511 _archive_write_disk_close(struct archive *_a)
2512 {
2513 struct archive_write_disk *a = (struct archive_write_disk *)_a;
2514 struct fixup_entry *next, *p;
2515 struct stat st;
2516 char *c;
2517 int fd, ret, openflags;
2518
2519 archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
2520 ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
2521 "archive_write_disk_close");
2522 ret = _archive_write_disk_finish_entry(&a->archive);
2523
2524 /* Sort dir list so directories are fixed up in depth-first order. */
2525 p = sort_dir_list(a->fixup_list);
2526
2527 while (p != NULL) {
2528 fd = -1;
2529 a->pst = NULL; /* Mark stat cache as out-of-date. */
2530
2531 /* We must strip trailing slashes from the path to avoid
2532 dereferencing symbolic links to directories */
2533 c = p->name;
2534 while (*c != '\0')
2535 c++;
2536 while (c != p->name && *(c - 1) == '/') {
2537 c--;
2538 *c = '\0';
2539 }
2540
2541 if (p->fixup == 0)
2542 goto skip_fixup_entry;
2543 else {
2544 /*
2545 * We need to verify if the type of the file
2546 * we are going to open matches the file type
2547 * of the fixup entry.
2548 */
2549 openflags = O_BINARY | O_NOFOLLOW | O_RDONLY
2550 | O_CLOEXEC;
2551 #if defined(O_DIRECTORY)
2552 if (p->filetype == AE_IFDIR)
2553 openflags |= O_DIRECTORY;
2554 #endif
2555 fd = open(p->name, openflags);
2556
2557 #if defined(O_DIRECTORY)
2558 /*
2559 * If we support O_DIRECTORY and open was
2560 * successful we can skip the file type check
2561 * for directories. For other file types
2562 * we need to verify via fstat() or lstat()
2563 */
2564 if (fd < 0 || p->filetype != AE_IFDIR) {
2565 #if HAVE_FSTAT
2566 if (fd >= 0 && (
2567 fstat(fd, &st) != 0 ||
2568 la_verify_filetype(st.st_mode,
2569 p->filetype) == 0)) {
2570 goto skip_fixup_entry;
2571 } else
2572 #endif
2573 if (
2574 #ifdef HAVE_LSTAT
2575 lstat(p->name, &st) != 0 ||
2576 #else
2577 la_stat(p->name, &st) != 0 ||
2578 #endif
2579 la_verify_filetype(st.st_mode,
2580 p->filetype) == 0) {
2581 goto skip_fixup_entry;
2582 }
2583 }
2584 #else
2585 #if HAVE_FSTAT
2586 if (fd > 0 && (
2587 fstat(fd, &st) != 0 ||
2588 la_verify_filetype(st.st_mode,
2589 p->filetype) == 0)) {
2590 goto skip_fixup_entry;
2591 } else
2592 #endif
2593 if (
2594 #ifdef HAVE_LSTAT
2595 lstat(p->name, &st) != 0 ||
2596 #else
2597 la_stat(p->name, &st) != 0 ||
2598 #endif
2599 la_verify_filetype(st.st_mode,
2600 p->filetype) == 0) {
2601 goto skip_fixup_entry;
2602 }
2603 #endif
2604 }
2605 if (p->fixup & TODO_TIMES) {
2606 set_times(a, fd, p->mode, p->name,
2607 p->atime, p->atime_nanos,
2608 p->birthtime, p->birthtime_nanos,
2609 p->mtime, p->mtime_nanos,
2610 p->ctime, p->ctime_nanos);
2611 }
2612 if (p->fixup & TODO_MODE_BASE) {
2613 #ifdef HAVE_FCHMOD
2614 if (fd >= 0)
2615 fchmod(fd, p->mode & 07777);
2616 else
2617 #endif
2618 #ifdef HAVE_LCHMOD
2619 lchmod(p->name, p->mode & 07777);
2620 #else
2621 chmod(p->name, p->mode & 07777);
2622 #endif
2623 }
2624 if (p->fixup & TODO_ACLS)
2625 archive_write_disk_set_acls(&a->archive, fd,
2626 p->name, &p->acl, p->mode);
2627 if (p->fixup & TODO_FFLAGS)
2628 set_fflags_platform(a, fd, p->name,
2629 p->mode, p->fflags_set, 0);
2630 if (p->fixup & TODO_MAC_METADATA)
2631 set_mac_metadata(a, p->name, p->mac_metadata,
2632 p->mac_metadata_size);
2633 skip_fixup_entry:
2634 next = p->next;
2635 archive_acl_clear(&p->acl);
2636 free(p->mac_metadata);
2637 free(p->name);
2638 if (fd >= 0)
2639 close(fd);
2640 free(p);
2641 p = next;
2642 }
2643 a->fixup_list = NULL;
2644 return (ret);
2645 }
2646
2647 static int
_archive_write_disk_free(struct archive * _a)2648 _archive_write_disk_free(struct archive *_a)
2649 {
2650 struct archive_write_disk *a;
2651 int ret;
2652 if (_a == NULL)
2653 return (ARCHIVE_OK);
2654 archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
2655 ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
2656 a = (struct archive_write_disk *)_a;
2657 ret = _archive_write_disk_close(&a->archive);
2658 archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
2659 archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
2660 archive_entry_free(a->entry);
2661 archive_string_free(&a->_name_data);
2662 archive_string_free(&a->_tmpname_data);
2663 archive_string_free(&a->archive.error_string);
2664 archive_string_free(&a->path_safe);
2665 a->archive.magic = 0;
2666 __archive_clean(&a->archive);
2667 free(a->decmpfs_header_p);
2668 free(a->resource_fork);
2669 free(a->compressed_buffer);
2670 free(a->uncompressed_buffer);
2671 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
2672 && defined(HAVE_ZLIB_H)
2673 if (a->stream_valid) {
2674 switch (deflateEnd(&a->stream)) {
2675 case Z_OK:
2676 break;
2677 default:
2678 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2679 "Failed to clean up compressor");
2680 ret = ARCHIVE_FATAL;
2681 break;
2682 }
2683 }
2684 #endif
2685 free(a);
2686 return (ret);
2687 }
2688
2689 /*
2690 * Simple O(n log n) merge sort to order the fixup list. In
2691 * particular, we want to restore dir timestamps depth-first.
2692 */
2693 static struct fixup_entry *
sort_dir_list(struct fixup_entry * p)2694 sort_dir_list(struct fixup_entry *p)
2695 {
2696 struct fixup_entry *a, *b, *t;
2697
2698 if (p == NULL)
2699 return (NULL);
2700 /* A one-item list is already sorted. */
2701 if (p->next == NULL)
2702 return (p);
2703
2704 /* Step 1: split the list. */
2705 t = p;
2706 a = p->next->next;
2707 while (a != NULL) {
2708 /* Step a twice, t once. */
2709 a = a->next;
2710 if (a != NULL)
2711 a = a->next;
2712 t = t->next;
2713 }
2714 /* Now, t is at the mid-point, so break the list here. */
2715 b = t->next;
2716 t->next = NULL;
2717 a = p;
2718
2719 /* Step 2: Recursively sort the two sub-lists. */
2720 a = sort_dir_list(a);
2721 b = sort_dir_list(b);
2722
2723 /* Step 3: Merge the returned lists. */
2724 /* Pick the first element for the merged list. */
2725 if (strcmp(a->name, b->name) > 0) {
2726 t = p = a;
2727 a = a->next;
2728 } else {
2729 t = p = b;
2730 b = b->next;
2731 }
2732
2733 /* Always put the later element on the list first. */
2734 while (a != NULL && b != NULL) {
2735 if (strcmp(a->name, b->name) > 0) {
2736 t->next = a;
2737 a = a->next;
2738 } else {
2739 t->next = b;
2740 b = b->next;
2741 }
2742 t = t->next;
2743 }
2744
2745 /* Only one list is non-empty, so just splice it on. */
2746 if (a != NULL)
2747 t->next = a;
2748 if (b != NULL)
2749 t->next = b;
2750
2751 return (p);
2752 }
2753
2754 /*
2755 * Returns a new, initialized fixup entry.
2756 *
2757 * TODO: Reduce the memory requirements for this list by using a tree
2758 * structure rather than a simple list of names.
2759 */
2760 static struct fixup_entry *
new_fixup(struct archive_write_disk * a,const char * pathname)2761 new_fixup(struct archive_write_disk *a, const char *pathname)
2762 {
2763 struct fixup_entry *fe;
2764
2765 fe = calloc(1, sizeof(struct fixup_entry));
2766 if (fe == NULL) {
2767 archive_set_error(&a->archive, ENOMEM,
2768 "Can't allocate memory for a fixup");
2769 return (NULL);
2770 }
2771 fe->next = a->fixup_list;
2772 a->fixup_list = fe;
2773 fe->fixup = 0;
2774 fe->filetype = 0;
2775 fe->name = strdup(pathname);
2776 return (fe);
2777 }
2778
2779 /*
2780 * Returns a fixup structure for the current entry.
2781 */
2782 static struct fixup_entry *
current_fixup(struct archive_write_disk * a,const char * pathname)2783 current_fixup(struct archive_write_disk *a, const char *pathname)
2784 {
2785 if (a->current_fixup == NULL)
2786 a->current_fixup = new_fixup(a, pathname);
2787 return (a->current_fixup);
2788 }
2789
2790 /* Error helper for new *_fsobj functions */
2791 static void
fsobj_error(int * a_eno,struct archive_string * a_estr,int err,const char * errstr,const char * path)2792 fsobj_error(int *a_eno, struct archive_string *a_estr,
2793 int err, const char *errstr, const char *path)
2794 {
2795 if (a_eno)
2796 *a_eno = err;
2797 if (a_estr)
2798 archive_string_sprintf(a_estr, "%s%s", errstr, path);
2799 }
2800
2801 /*
2802 * TODO: Someday, integrate this with the deep dir support; they both
2803 * scan the path and both can be optimized by comparing against other
2804 * recent paths.
2805 */
2806 /*
2807 * Checks the given path to see if any elements along it are symlinks. Returns
2808 * ARCHIVE_OK if there are none, otherwise puts an error in errmsg.
2809 */
2810 static int
check_symlinks_fsobj(char * path,int * a_eno,struct archive_string * a_estr,int flags,int checking_linkname)2811 check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2812 int flags, int checking_linkname)
2813 {
2814 #if !defined(HAVE_LSTAT) && \
2815 !(defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT))
2816 /* Platform doesn't have lstat, so we can't look for symlinks. */
2817 (void)path; /* UNUSED */
2818 (void)a_eno; /* UNUSED */
2819 (void)a_estr; /* UNUSED */
2820 (void)flags; /* UNUSED */
2821 (void)checking_linkname; /* UNUSED */
2822 return (ARCHIVE_OK);
2823 #else
2824 int res = ARCHIVE_OK;
2825 char *tail;
2826 char *head;
2827 int last;
2828 char c = '\0';
2829 int r;
2830 struct stat st;
2831 int chdir_fd;
2832 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2833 int fd;
2834 #endif
2835
2836 /* Nothing to do here if name is empty */
2837 if(path[0] == '\0')
2838 return (ARCHIVE_OK);
2839
2840 /*
2841 * Guard against symlink tricks. Reject any archive entry whose
2842 * destination would be altered by a symlink.
2843 *
2844 * Walk the filename in chunks separated by '/'. For each segment:
2845 * - if it doesn't exist, continue
2846 * - if it's symlink, abort or remove it
2847 * - if it's a directory and it's not the last chunk, cd into it
2848 * As we go:
2849 * head points to the current (relative) path
2850 * tail points to the temporary \0 terminating the segment we're
2851 * currently examining
2852 * c holds what used to be in *tail
2853 * last is 1 if this is the last tail
2854 */
2855 chdir_fd = la_opendirat(AT_FDCWD, ".");
2856 __archive_ensure_cloexec_flag(chdir_fd);
2857 if (chdir_fd < 0) {
2858 fsobj_error(a_eno, a_estr, errno,
2859 "Could not open ", path);
2860 return (ARCHIVE_FATAL);
2861 }
2862 head = path;
2863 tail = path;
2864 last = 0;
2865 /* TODO: reintroduce a safe cache here? */
2866 /* Skip the root directory if the path is absolute. */
2867 if(tail == path && tail[0] == '/')
2868 ++tail;
2869 /* Keep going until we've checked the entire name.
2870 * head, tail, path all alias the same string, which is
2871 * temporarily zeroed at tail, so be careful restoring the
2872 * stashed (c=tail[0]) for error messages.
2873 * Exiting the loop with break is okay; continue is not.
2874 */
2875 while (!last) {
2876 /*
2877 * Skip the separator we just consumed, plus any adjacent ones
2878 */
2879 while (*tail == '/')
2880 ++tail;
2881 /* Skip the next path element. */
2882 while (*tail != '\0' && *tail != '/')
2883 ++tail;
2884 /* is this the last path component? */
2885 last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
2886 /* temporarily truncate the string here */
2887 c = tail[0];
2888 tail[0] = '\0';
2889 /* Check that we haven't hit a symlink. */
2890 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2891 r = fstatat(chdir_fd, head, &st, AT_SYMLINK_NOFOLLOW);
2892 #elif defined(HAVE_LSTAT)
2893 r = lstat(head, &st);
2894 #else
2895 r = la_stat(head, &st);
2896 #endif
2897 if (r != 0) {
2898 tail[0] = c;
2899 /* We've hit a dir that doesn't exist; stop now. */
2900 if (errno == ENOENT) {
2901 break;
2902 } else {
2903 /*
2904 * Treat any other error as fatal - best to be
2905 * paranoid here.
2906 * Note: This effectively disables deep
2907 * directory support when security checks are
2908 * enabled. Otherwise, very long pathnames that
2909 * trigger an error here could evade the
2910 * sandbox.
2911 * TODO: We could do better, but it would
2912 * probably require merging the symlink checks
2913 * with the deep-directory editing.
2914 */
2915 fsobj_error(a_eno, a_estr, errno,
2916 "Could not stat ", path);
2917 res = ARCHIVE_FAILED;
2918 break;
2919 }
2920 } else if (S_ISDIR(st.st_mode)) {
2921 if (!last) {
2922 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2923 fd = la_opendirat(chdir_fd, head);
2924 if (fd < 0)
2925 r = -1;
2926 else {
2927 r = 0;
2928 close(chdir_fd);
2929 chdir_fd = fd;
2930 }
2931 #else
2932 r = chdir(head);
2933 #endif
2934 if (r != 0) {
2935 tail[0] = c;
2936 fsobj_error(a_eno, a_estr, errno,
2937 "Could not chdir ", path);
2938 res = (ARCHIVE_FATAL);
2939 break;
2940 }
2941 /* Our view is now from inside this dir: */
2942 head = tail + 1;
2943 }
2944 } else if (S_ISLNK(st.st_mode)) {
2945 if (last && checking_linkname) {
2946 #ifdef HAVE_LINKAT
2947 /*
2948 * Hardlinks to symlinks are safe to write
2949 * if linkat() is supported as it does not
2950 * follow symlinks.
2951 */
2952 res = ARCHIVE_OK;
2953 #else
2954 /*
2955 * We return ARCHIVE_FAILED here as we are
2956 * not able to safely write hardlinks
2957 * to symlinks.
2958 */
2959 tail[0] = c;
2960 fsobj_error(a_eno, a_estr, errno,
2961 "Cannot write hardlink to symlink ",
2962 path);
2963 res = ARCHIVE_FAILED;
2964 #endif
2965 break;
2966 } else
2967 if (last) {
2968 /*
2969 * Last element is symlink; remove it
2970 * so we can overwrite it with the
2971 * item being extracted.
2972 */
2973 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
2974 r = unlinkat(chdir_fd, head, 0);
2975 #else
2976 r = unlink(head);
2977 #endif
2978 if (r != 0) {
2979 tail[0] = c;
2980 fsobj_error(a_eno, a_estr, errno,
2981 "Could not remove symlink ",
2982 path);
2983 res = ARCHIVE_FAILED;
2984 break;
2985 }
2986 /*
2987 * Even if we did remove it, a warning
2988 * is in order. The warning is silly,
2989 * though, if we're just replacing one
2990 * symlink with another symlink.
2991 */
2992 tail[0] = c;
2993 /*
2994 * FIXME: not sure how important this is to
2995 * restore
2996 */
2997 /*
2998 if (!S_ISLNK(path)) {
2999 fsobj_error(a_eno, a_estr, 0,
3000 "Removing symlink ", path);
3001 }
3002 */
3003 /* Symlink gone. No more problem! */
3004 res = ARCHIVE_OK;
3005 break;
3006 } else if (flags & ARCHIVE_EXTRACT_UNLINK) {
3007 /* User asked us to remove problems. */
3008 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3009 r = unlinkat(chdir_fd, head, 0);
3010 #else
3011 r = unlink(head);
3012 #endif
3013 if (r != 0) {
3014 tail[0] = c;
3015 fsobj_error(a_eno, a_estr, 0,
3016 "Cannot remove intervening "
3017 "symlink ", path);
3018 res = ARCHIVE_FAILED;
3019 break;
3020 }
3021 tail[0] = c;
3022 } else if ((flags &
3023 ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) {
3024 /*
3025 * We are not the last element and we want to
3026 * follow symlinks if they are a directory.
3027 *
3028 * This is needed to extract hardlinks over
3029 * symlinks.
3030 */
3031 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3032 r = fstatat(chdir_fd, head, &st, 0);
3033 #else
3034 r = la_stat(head, &st);
3035 #endif
3036 if (r != 0) {
3037 tail[0] = c;
3038 if (errno == ENOENT) {
3039 break;
3040 } else {
3041 fsobj_error(a_eno, a_estr,
3042 errno,
3043 "Could not stat ", path);
3044 res = (ARCHIVE_FAILED);
3045 break;
3046 }
3047 } else if (S_ISDIR(st.st_mode)) {
3048 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3049 fd = la_opendirat(chdir_fd, head);
3050 if (fd < 0)
3051 r = -1;
3052 else {
3053 r = 0;
3054 close(chdir_fd);
3055 chdir_fd = fd;
3056 }
3057 #else
3058 r = chdir(head);
3059 #endif
3060 if (r != 0) {
3061 tail[0] = c;
3062 fsobj_error(a_eno, a_estr,
3063 errno,
3064 "Could not chdir ", path);
3065 res = (ARCHIVE_FATAL);
3066 break;
3067 }
3068 /*
3069 * Our view is now from inside
3070 * this dir:
3071 */
3072 head = tail + 1;
3073 } else {
3074 tail[0] = c;
3075 fsobj_error(a_eno, a_estr, 0,
3076 "Cannot extract through "
3077 "symlink ", path);
3078 res = ARCHIVE_FAILED;
3079 break;
3080 }
3081 } else {
3082 tail[0] = c;
3083 fsobj_error(a_eno, a_estr, 0,
3084 "Cannot extract through symlink ", path);
3085 res = ARCHIVE_FAILED;
3086 break;
3087 }
3088 }
3089 /* be sure to always maintain this */
3090 tail[0] = c;
3091 if (tail[0] != '\0')
3092 tail++; /* Advance to the next segment. */
3093 }
3094 /* Catches loop exits via break */
3095 tail[0] = c;
3096 #if defined(HAVE_OPENAT) && defined(HAVE_FSTATAT) && defined(HAVE_UNLINKAT)
3097 /* If we operate with openat(), fstatat() and unlinkat() there was
3098 * no chdir(), so just close the fd */
3099 if (chdir_fd >= 0)
3100 close(chdir_fd);
3101 #elif HAVE_FCHDIR
3102 /* If we changed directory above, restore it here. */
3103 if (chdir_fd >= 0) {
3104 r = fchdir(chdir_fd);
3105 if (r != 0) {
3106 fsobj_error(a_eno, a_estr, errno,
3107 "chdir() failure", "");
3108 }
3109 close(chdir_fd);
3110 chdir_fd = -1;
3111 if (r != 0) {
3112 res = (ARCHIVE_FATAL);
3113 }
3114 }
3115 #endif
3116 /* TODO: reintroduce a safe cache here? */
3117 return res;
3118 #endif
3119 }
3120
3121 /*
3122 * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise
3123 * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED}
3124 */
3125 static int
check_symlinks(struct archive_write_disk * a)3126 check_symlinks(struct archive_write_disk *a)
3127 {
3128 struct archive_string error_string;
3129 int error_number;
3130 int rc;
3131 archive_string_init(&error_string);
3132 rc = check_symlinks_fsobj(a->name, &error_number, &error_string,
3133 a->flags, 0);
3134 if (rc != ARCHIVE_OK) {
3135 archive_set_error(&a->archive, error_number, "%s",
3136 error_string.s);
3137 }
3138 archive_string_free(&error_string);
3139 a->pst = NULL; /* to be safe */
3140 return rc;
3141 }
3142
3143
3144 #if defined(__CYGWIN__)
3145 /*
3146 * 1. Convert a path separator from '\' to '/' .
3147 * We shouldn't check multibyte character directly because some
3148 * character-set have been using the '\' character for a part of
3149 * its multibyte character code.
3150 * 2. Replace unusable characters in Windows with underscore('_').
3151 * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
3152 */
3153 static void
cleanup_pathname_win(char * path)3154 cleanup_pathname_win(char *path)
3155 {
3156 wchar_t wc;
3157 char *p;
3158 size_t alen, l;
3159 int mb, complete, utf8;
3160
3161 alen = 0;
3162 mb = 0;
3163 complete = 1;
3164 utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
3165 for (p = path; *p != '\0'; p++) {
3166 ++alen;
3167 if (*p == '\\') {
3168 /* If previous byte is smaller than 128,
3169 * this is not second byte of multibyte characters,
3170 * so we can replace '\' with '/'. */
3171 if (utf8 || !mb)
3172 *p = '/';
3173 else
3174 complete = 0;/* uncompleted. */
3175 } else if (*(unsigned char *)p > 127)
3176 mb = 1;
3177 else
3178 mb = 0;
3179 /* Rewrite the path name if its next character is unusable. */
3180 if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
3181 *p == '<' || *p == '>' || *p == '|')
3182 *p = '_';
3183 }
3184 if (complete)
3185 return;
3186
3187 /*
3188 * Convert path separator in wide-character.
3189 */
3190 p = path;
3191 while (*p != '\0' && alen) {
3192 l = mbtowc(&wc, p, alen);
3193 if (l == (size_t)-1) {
3194 while (*p != '\0') {
3195 if (*p == '\\')
3196 *p = '/';
3197 ++p;
3198 }
3199 break;
3200 }
3201 if (l == 1 && wc == L'\\')
3202 *p = '/';
3203 p += l;
3204 alen -= l;
3205 }
3206 }
3207 #endif
3208
3209 /*
3210 * Canonicalize the pathname. In particular, this strips duplicate
3211 * '/' characters, '.' elements, and trailing '/'. It also raises an
3212 * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is
3213 * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
3214 * is set) if the path is absolute.
3215 */
3216 static int
cleanup_pathname_fsobj(char * path,int * a_eno,struct archive_string * a_estr,int flags)3217 cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
3218 int flags)
3219 {
3220 char *dest, *src;
3221 char separator = '\0';
3222
3223 dest = src = path;
3224 if (*src == '\0') {
3225 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3226 "Invalid empty ", "pathname");
3227 return (ARCHIVE_FAILED);
3228 }
3229
3230 #if defined(__CYGWIN__)
3231 cleanup_pathname_win(path);
3232 #endif
3233 /* Skip leading '/'. */
3234 if (*src == '/') {
3235 if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
3236 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
3237 "Path is ", "absolute");
3238 return (ARCHIVE_FAILED);
3239 }
3240
3241 separator = *src++;
3242 }
3243
3244 /* Scan the pathname one element at a time. */
3245 for (;;) {
3246 /* src points to first char after '/' */
3247 if (src[0] == '\0') {
3248 break;
3249 } else if (src[0] == '/') {
3250 /* Found '//', ignore second one. */
3251 src++;
3252 continue;
3253 } else if (src[0] == '.') {
3254 if (src[1] == '\0') {
3255 /* Ignore trailing '.' */
3256 break;
3257 } else if (src[1] == '/') {
3258 /* Skip './'. */
3259 src += 2;
3260 continue;
3261 } else if (src[1] == '.') {
3262 if (src[2] == '/' || src[2] == '\0') {
3263 /* Conditionally warn about '..' */
3264 if (flags
3265 & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
3266 fsobj_error(a_eno, a_estr,
3267 ARCHIVE_ERRNO_MISC,
3268 "Path contains ", "'..'");
3269 return (ARCHIVE_FAILED);
3270 }
3271 }
3272 /*
3273 * Note: Under no circumstances do we
3274 * remove '..' elements. In
3275 * particular, restoring
3276 * '/foo/../bar/' should create the
3277 * 'foo' dir as a side-effect.
3278 */
3279 }
3280 }
3281
3282 /* Copy current element, including leading '/'. */
3283 if (separator)
3284 *dest++ = '/';
3285 while (*src != '\0' && *src != '/') {
3286 *dest++ = *src++;
3287 }
3288
3289 if (*src == '\0')
3290 break;
3291
3292 /* Skip '/' separator. */
3293 separator = *src++;
3294 }
3295 /*
3296 * We've just copied zero or more path elements, not including the
3297 * final '/'.
3298 */
3299 if (dest == path) {
3300 /*
3301 * Nothing got copied. The path must have been something
3302 * like '.' or '/' or './' or '/././././/./'.
3303 */
3304 if (separator)
3305 *dest++ = '/';
3306 else
3307 *dest++ = '.';
3308 }
3309 /* Terminate the result. */
3310 *dest = '\0';
3311 return (ARCHIVE_OK);
3312 }
3313
3314 static int
cleanup_pathname(struct archive_write_disk * a)3315 cleanup_pathname(struct archive_write_disk *a)
3316 {
3317 struct archive_string error_string;
3318 int error_number;
3319 int rc;
3320 archive_string_init(&error_string);
3321 rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string,
3322 a->flags);
3323 if (rc != ARCHIVE_OK) {
3324 archive_set_error(&a->archive, error_number, "%s",
3325 error_string.s);
3326 }
3327 archive_string_free(&error_string);
3328 return rc;
3329 }
3330
3331 /*
3332 * Create the parent directory of the specified path, assuming path
3333 * is already in mutable storage.
3334 */
3335 static int
create_parent_dir(struct archive_write_disk * a,char * path)3336 create_parent_dir(struct archive_write_disk *a, char *path)
3337 {
3338 char *slash;
3339 int r;
3340
3341 /* Remove tail element to obtain parent name. */
3342 slash = strrchr(path, '/');
3343 if (slash == NULL)
3344 return (ARCHIVE_OK);
3345 *slash = '\0';
3346 r = create_dir(a, path);
3347 *slash = '/';
3348 return (r);
3349 }
3350
3351 /*
3352 * Create the specified dir, recursing to create parents as necessary.
3353 *
3354 * Returns ARCHIVE_OK if the path exists when we're done here.
3355 * Otherwise, returns ARCHIVE_FAILED.
3356 * Assumes path is in mutable storage; path is unchanged on exit.
3357 */
3358 static int
create_dir(struct archive_write_disk * a,char * path)3359 create_dir(struct archive_write_disk *a, char *path)
3360 {
3361 struct stat st;
3362 struct fixup_entry *le;
3363 char *slash, *base;
3364 mode_t mode_final, mode;
3365 int r;
3366
3367 /* Check for special names and just skip them. */
3368 slash = strrchr(path, '/');
3369 if (slash == NULL)
3370 base = path;
3371 else
3372 base = slash + 1;
3373
3374 if (base[0] == '\0' ||
3375 (base[0] == '.' && base[1] == '\0') ||
3376 (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
3377 /* Don't bother trying to create null path, '.', or '..'. */
3378 if (slash != NULL) {
3379 *slash = '\0';
3380 r = create_dir(a, path);
3381 *slash = '/';
3382 return (r);
3383 }
3384 return (ARCHIVE_OK);
3385 }
3386
3387 /*
3388 * Yes, this should be stat() and not lstat(). Using lstat()
3389 * here loses the ability to extract through symlinks. Also note
3390 * that this should not use the a->st cache.
3391 */
3392 if (la_stat(path, &st) == 0) {
3393 if (S_ISDIR(st.st_mode))
3394 return (ARCHIVE_OK);
3395 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
3396 archive_set_error(&a->archive, EEXIST,
3397 "Can't create directory '%s'", path);
3398 return (ARCHIVE_FAILED);
3399 }
3400 if (unlink(path) != 0) {
3401 archive_set_error(&a->archive, errno,
3402 "Can't create directory '%s': "
3403 "Conflicting file cannot be removed",
3404 path);
3405 return (ARCHIVE_FAILED);
3406 }
3407 } else if (errno != ENOENT && errno != ENOTDIR) {
3408 /* Stat failed? */
3409 archive_set_error(&a->archive, errno,
3410 "Can't test directory '%s'", path);
3411 return (ARCHIVE_FAILED);
3412 } else if (slash != NULL) {
3413 *slash = '\0';
3414 r = create_dir(a, path);
3415 *slash = '/';
3416 if (r != ARCHIVE_OK)
3417 return (r);
3418 }
3419
3420 /*
3421 * Mode we want for the final restored directory. Per POSIX,
3422 * implicitly-created dirs must be created obeying the umask.
3423 * There's no mention whether this is different for privileged
3424 * restores (which the rest of this code handles by pretending
3425 * umask=0). I've chosen here to always obey the user's umask for
3426 * implicit dirs, even if _EXTRACT_PERM was specified.
3427 */
3428 mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
3429 /* Mode we want on disk during the restore process. */
3430 mode = mode_final;
3431 mode |= MINIMUM_DIR_MODE;
3432 mode &= MAXIMUM_DIR_MODE;
3433 if (mkdir(path, mode) == 0) {
3434 if (mode != mode_final) {
3435 le = new_fixup(a, path);
3436 if (le == NULL)
3437 return (ARCHIVE_FATAL);
3438 le->fixup |=TODO_MODE_BASE;
3439 le->mode = mode_final;
3440 }
3441 return (ARCHIVE_OK);
3442 }
3443
3444 /*
3445 * Without the following check, a/b/../b/c/d fails at the
3446 * second visit to 'b', so 'd' can't be created. Note that we
3447 * don't add it to the fixup list here, as it's already been
3448 * added.
3449 */
3450 if (la_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
3451 return (ARCHIVE_OK);
3452
3453 archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
3454 path);
3455 return (ARCHIVE_FAILED);
3456 }
3457
3458 /*
3459 * Note: Although we can skip setting the user id if the desired user
3460 * id matches the current user, we cannot skip setting the group, as
3461 * many systems set the gid based on the containing directory. So
3462 * we have to perform a chown syscall if we want to set the SGID
3463 * bit. (The alternative is to stat() and then possibly chown(); it's
3464 * more efficient to skip the stat() and just always chown().) Note
3465 * that a successful chown() here clears the TODO_SGID_CHECK bit, which
3466 * allows set_mode to skip the stat() check for the GID.
3467 */
3468 static int
set_ownership(struct archive_write_disk * a)3469 set_ownership(struct archive_write_disk *a)
3470 {
3471 #if !defined(__CYGWIN__) && !defined(__linux__)
3472 /*
3473 * On Linux, a process may have the CAP_CHOWN capability.
3474 * On Windows there is no 'root' user with uid 0.
3475 * Elsewhere we can skip calling chown if we are not root and the desired
3476 * user id does not match the current user.
3477 */
3478 if (a->user_uid != 0 && a->user_uid != a->uid) {
3479 archive_set_error(&a->archive, errno,
3480 "Can't set UID=%jd", (intmax_t)a->uid);
3481 return (ARCHIVE_WARN);
3482 }
3483 #endif
3484
3485 #ifdef HAVE_FCHOWN
3486 /* If we have an fd, we can avoid a race. */
3487 if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
3488 /* We've set owner and know uid/gid are correct. */
3489 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3490 return (ARCHIVE_OK);
3491 }
3492 #endif
3493
3494 /* We prefer lchown() but will use chown() if that's all we have. */
3495 /* Of course, if we have neither, this will always fail. */
3496 #ifdef HAVE_LCHOWN
3497 if (lchown(a->name, a->uid, a->gid) == 0) {
3498 /* We've set owner and know uid/gid are correct. */
3499 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3500 return (ARCHIVE_OK);
3501 }
3502 #elif HAVE_CHOWN
3503 if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
3504 /* We've set owner and know uid/gid are correct. */
3505 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3506 return (ARCHIVE_OK);
3507 }
3508 #endif
3509
3510 archive_set_error(&a->archive, errno,
3511 "Can't set user=%jd/group=%jd for %s",
3512 (intmax_t)a->uid, (intmax_t)a->gid, a->name);
3513 return (ARCHIVE_WARN);
3514 }
3515
3516 /*
3517 * Note: Returns 0 on success, non-zero on failure.
3518 */
3519 static int
set_time(int fd,int mode,const char * name,time_t atime,long atime_nsec,time_t mtime,long mtime_nsec)3520 set_time(int fd, int mode, const char *name,
3521 time_t atime, long atime_nsec,
3522 time_t mtime, long mtime_nsec)
3523 {
3524 /* Select the best implementation for this platform. */
3525 #if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
3526 /*
3527 * utimensat() and futimens() are defined in
3528 * POSIX.1-2008. They support ns resolution and setting times
3529 * on fds and symlinks.
3530 */
3531 struct timespec ts[2];
3532 (void)mode; /* UNUSED */
3533 ts[0].tv_sec = atime;
3534 ts[0].tv_nsec = atime_nsec;
3535 ts[1].tv_sec = mtime;
3536 ts[1].tv_nsec = mtime_nsec;
3537 if (fd >= 0)
3538 return futimens(fd, ts);
3539 return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
3540
3541 #elif HAVE_UTIMES
3542 /*
3543 * The utimes()-family functions support µs-resolution and
3544 * setting times fds and symlinks. utimes() is documented as
3545 * LEGACY by POSIX, futimes() and lutimes() are not described
3546 * in POSIX.
3547 */
3548 struct timeval times[2];
3549
3550 times[0].tv_sec = atime;
3551 times[0].tv_usec = atime_nsec / 1000;
3552 times[1].tv_sec = mtime;
3553 times[1].tv_usec = mtime_nsec / 1000;
3554
3555 #ifdef HAVE_FUTIMES
3556 if (fd >= 0)
3557 return (futimes(fd, times));
3558 #else
3559 (void)fd; /* UNUSED */
3560 #endif
3561 #ifdef HAVE_LUTIMES
3562 (void)mode; /* UNUSED */
3563 return (lutimes(name, times));
3564 #else
3565 if (S_ISLNK(mode))
3566 return (0);
3567 return (utimes(name, times));
3568 #endif
3569
3570 #elif defined(HAVE_UTIME)
3571 /*
3572 * utime() is POSIX-standard but only supports 1s resolution and
3573 * does not support fds or symlinks.
3574 */
3575 struct utimbuf times;
3576 (void)fd; /* UNUSED */
3577 (void)name; /* UNUSED */
3578 (void)atime_nsec; /* UNUSED */
3579 (void)mtime_nsec; /* UNUSED */
3580 times.actime = atime;
3581 times.modtime = mtime;
3582 if (S_ISLNK(mode))
3583 return (ARCHIVE_OK);
3584 return (utime(name, ×));
3585
3586 #else
3587 /*
3588 * We don't know how to set the time on this platform.
3589 */
3590 (void)fd; /* UNUSED */
3591 (void)mode; /* UNUSED */
3592 (void)name; /* UNUSED */
3593 (void)atime; /* UNUSED */
3594 (void)atime_nsec; /* UNUSED */
3595 (void)mtime; /* UNUSED */
3596 (void)mtime_nsec; /* UNUSED */
3597 return (ARCHIVE_WARN);
3598 #endif
3599 }
3600
3601 #ifdef F_SETTIMES
3602 static int
set_time_tru64(int fd,int mode,const char * name,time_t atime,long atime_nsec,time_t mtime,long mtime_nsec,time_t ctime,long ctime_nsec)3603 set_time_tru64(int fd, int mode, const char *name,
3604 time_t atime, long atime_nsec,
3605 time_t mtime, long mtime_nsec,
3606 time_t ctime, long ctime_nsec)
3607 {
3608 struct attr_timbuf tstamp;
3609 tstamp.atime.tv_sec = atime;
3610 tstamp.mtime.tv_sec = mtime;
3611 tstamp.ctime.tv_sec = ctime;
3612 #if defined (__hpux) && ( defined (__ia64) || defined (__hppa) )
3613 tstamp.atime.tv_nsec = atime_nsec;
3614 tstamp.mtime.tv_nsec = mtime_nsec;
3615 tstamp.ctime.tv_nsec = ctime_nsec;
3616 #else
3617 tstamp.atime.tv_usec = atime_nsec / 1000;
3618 tstamp.mtime.tv_usec = mtime_nsec / 1000;
3619 tstamp.ctime.tv_usec = ctime_nsec / 1000;
3620 #endif
3621 return (fcntl(fd,F_SETTIMES,&tstamp));
3622 }
3623 #endif /* F_SETTIMES */
3624
3625 static int
set_times(struct archive_write_disk * a,int fd,int mode,const char * name,time_t atime,long atime_nanos,time_t birthtime,long birthtime_nanos,time_t mtime,long mtime_nanos,time_t cctime,long ctime_nanos)3626 set_times(struct archive_write_disk *a,
3627 int fd, int mode, const char *name,
3628 time_t atime, long atime_nanos,
3629 time_t birthtime, long birthtime_nanos,
3630 time_t mtime, long mtime_nanos,
3631 time_t cctime, long ctime_nanos)
3632 {
3633 /* Note: set_time doesn't use libarchive return conventions!
3634 * It uses syscall conventions. So 0 here instead of ARCHIVE_OK. */
3635 int r1 = 0, r2 = 0;
3636
3637 #ifdef F_SETTIMES
3638 /*
3639 * on Tru64 try own fcntl first which can restore even the
3640 * ctime, fall back to default code path below if it fails
3641 * or if we are not running as root
3642 */
3643 if (a->user_uid == 0 &&
3644 set_time_tru64(fd, mode, name,
3645 atime, atime_nanos, mtime,
3646 mtime_nanos, cctime, ctime_nanos) == 0) {
3647 return (ARCHIVE_OK);
3648 }
3649 #else /* Tru64 */
3650 (void)cctime; /* UNUSED */
3651 (void)ctime_nanos; /* UNUSED */
3652 #endif /* Tru64 */
3653
3654 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
3655 /*
3656 * If you have struct stat.st_birthtime, we assume BSD
3657 * birthtime semantics, in which {f,l,}utimes() updates
3658 * birthtime to earliest mtime. So we set the time twice,
3659 * first using the birthtime, then using the mtime. If
3660 * birthtime == mtime, this isn't necessary, so we skip it.
3661 * If birthtime > mtime, then this won't work, so we skip it.
3662 */
3663 if (birthtime < mtime
3664 || (birthtime == mtime && birthtime_nanos < mtime_nanos))
3665 r1 = set_time(fd, mode, name,
3666 atime, atime_nanos,
3667 birthtime, birthtime_nanos);
3668 #else
3669 (void)birthtime; /* UNUSED */
3670 (void)birthtime_nanos; /* UNUSED */
3671 #endif
3672 r2 = set_time(fd, mode, name,
3673 atime, atime_nanos,
3674 mtime, mtime_nanos);
3675 if (r1 != 0 || r2 != 0) {
3676 archive_set_error(&a->archive, errno,
3677 "Can't restore time");
3678 return (ARCHIVE_WARN);
3679 }
3680 return (ARCHIVE_OK);
3681 }
3682
3683 static int
set_times_from_entry(struct archive_write_disk * a)3684 set_times_from_entry(struct archive_write_disk *a)
3685 {
3686 time_t atime, birthtime, mtime, cctime;
3687 long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
3688
3689 /* Suitable defaults. */
3690 atime = birthtime = mtime = cctime = a->start_time;
3691 atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
3692
3693 /* If no time was provided, we're done. */
3694 if (!archive_entry_atime_is_set(a->entry)
3695 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
3696 && !archive_entry_birthtime_is_set(a->entry)
3697 #endif
3698 && !archive_entry_mtime_is_set(a->entry))
3699 return (ARCHIVE_OK);
3700
3701 if (archive_entry_atime_is_set(a->entry)) {
3702 atime = archive_entry_atime(a->entry);
3703 atime_nsec = archive_entry_atime_nsec(a->entry);
3704 }
3705 if (archive_entry_birthtime_is_set(a->entry)) {
3706 birthtime = archive_entry_birthtime(a->entry);
3707 birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
3708 }
3709 if (archive_entry_mtime_is_set(a->entry)) {
3710 mtime = archive_entry_mtime(a->entry);
3711 mtime_nsec = archive_entry_mtime_nsec(a->entry);
3712 }
3713 if (archive_entry_ctime_is_set(a->entry)) {
3714 cctime = archive_entry_ctime(a->entry);
3715 ctime_nsec = archive_entry_ctime_nsec(a->entry);
3716 }
3717
3718 return set_times(a, a->fd, a->mode, a->name,
3719 atime, atime_nsec,
3720 birthtime, birthtime_nsec,
3721 mtime, mtime_nsec,
3722 cctime, ctime_nsec);
3723 }
3724
3725 static int
set_mode(struct archive_write_disk * a,int mode)3726 set_mode(struct archive_write_disk *a, int mode)
3727 {
3728 int r = ARCHIVE_OK;
3729 int r2;
3730 mode &= 07777; /* Strip off file type bits. */
3731
3732 if (a->todo & TODO_SGID_CHECK) {
3733 /*
3734 * If we don't know the GID is right, we must stat()
3735 * to verify it. We can't just check the GID of this
3736 * process, since systems sometimes set GID from
3737 * the enclosing dir or based on ACLs.
3738 */
3739 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3740 return (r);
3741 if (a->pst->st_gid != a->gid) {
3742 mode &= ~ S_ISGID;
3743 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3744 /*
3745 * This is only an error if you
3746 * requested owner restore. If you
3747 * didn't, we'll try to restore
3748 * sgid/suid, but won't consider it a
3749 * problem if we can't.
3750 */
3751 archive_set_error(&a->archive, -1,
3752 "Can't restore SGID bit");
3753 r = ARCHIVE_WARN;
3754 }
3755 }
3756 /* While we're here, double-check the UID. */
3757 if (a->pst->st_uid != a->uid
3758 && (a->todo & TODO_SUID)) {
3759 mode &= ~ S_ISUID;
3760 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3761 archive_set_error(&a->archive, -1,
3762 "Can't restore SUID bit");
3763 r = ARCHIVE_WARN;
3764 }
3765 }
3766 a->todo &= ~TODO_SGID_CHECK;
3767 a->todo &= ~TODO_SUID_CHECK;
3768 } else if (a->todo & TODO_SUID_CHECK) {
3769 /*
3770 * If we don't know the UID is right, we can just check
3771 * the user, since all systems set the file UID from
3772 * the process UID.
3773 */
3774 if (a->user_uid != a->uid) {
3775 mode &= ~ S_ISUID;
3776 if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3777 archive_set_error(&a->archive, -1,
3778 "Can't make file SUID");
3779 r = ARCHIVE_WARN;
3780 }
3781 }
3782 a->todo &= ~TODO_SUID_CHECK;
3783 }
3784
3785 if (S_ISLNK(a->mode)) {
3786 #ifdef HAVE_LCHMOD
3787 /*
3788 * If this is a symlink, use lchmod(). If the
3789 * platform doesn't support lchmod(), just skip it. A
3790 * platform that doesn't provide a way to set
3791 * permissions on symlinks probably ignores
3792 * permissions on symlinks, so a failure here has no
3793 * impact.
3794 */
3795 if (lchmod(a->name, (mode_t)mode) != 0) {
3796 switch (errno) {
3797 case ENOTSUP:
3798 case ENOSYS:
3799 #if ENOTSUP != EOPNOTSUPP
3800 case EOPNOTSUPP:
3801 #endif
3802 /*
3803 * if lchmod is defined but the platform
3804 * doesn't support it, silently ignore
3805 * error
3806 */
3807 break;
3808 default:
3809 archive_set_error(&a->archive, errno,
3810 "Can't set permissions to 0%o",
3811 (unsigned int)mode);
3812 r = ARCHIVE_WARN;
3813 }
3814 }
3815 #endif
3816 } else if (!S_ISDIR(a->mode)) {
3817 /*
3818 * If it's not a symlink and not a dir, then use
3819 * fchmod() or chmod(), depending on whether we have
3820 * an fd. Dirs get their perms set during the
3821 * post-extract fixup, which is handled elsewhere.
3822 */
3823 #ifdef HAVE_FCHMOD
3824 if (a->fd >= 0)
3825 r2 = fchmod(a->fd, (mode_t)mode);
3826 else
3827 #endif
3828 /* If this platform lacks fchmod(), then
3829 * we'll just use chmod(). */
3830 r2 = chmod(a->name, (mode_t)mode);
3831
3832 if (r2 != 0) {
3833 archive_set_error(&a->archive, errno,
3834 "Can't set permissions to 0%o", (unsigned int)mode);
3835 r = ARCHIVE_WARN;
3836 }
3837 }
3838 return (r);
3839 }
3840
3841 static int
set_fflags(struct archive_write_disk * a)3842 set_fflags(struct archive_write_disk *a)
3843 {
3844 struct fixup_entry *le;
3845 unsigned long set, clear;
3846 int r;
3847 mode_t mode = archive_entry_mode(a->entry);
3848 /*
3849 * Make 'critical_flags' hold all file flags that can't be
3850 * immediately restored. For example, on BSD systems,
3851 * SF_IMMUTABLE prevents hardlinks from being created, so
3852 * should not be set until after any hardlinks are created. To
3853 * preserve some semblance of portability, this uses #ifdef
3854 * extensively. Ugly, but it works.
3855 *
3856 * Yes, Virginia, this does create a security race. It's mitigated
3857 * somewhat by the practice of creating dirs 0700 until the extract
3858 * is done, but it would be nice if we could do more than that.
3859 * People restoring critical file systems should be wary of
3860 * other programs that might try to muck with files as they're
3861 * being restored.
3862 */
3863 const int critical_flags = 0
3864 #ifdef SF_IMMUTABLE
3865 | SF_IMMUTABLE
3866 #endif
3867 #ifdef UF_IMMUTABLE
3868 | UF_IMMUTABLE
3869 #endif
3870 #ifdef SF_APPEND
3871 | SF_APPEND
3872 #endif
3873 #ifdef UF_APPEND
3874 | UF_APPEND
3875 #endif
3876 #if defined(FS_APPEND_FL)
3877 | FS_APPEND_FL
3878 #elif defined(EXT2_APPEND_FL)
3879 | EXT2_APPEND_FL
3880 #endif
3881 #if defined(FS_IMMUTABLE_FL)
3882 | FS_IMMUTABLE_FL
3883 #elif defined(EXT2_IMMUTABLE_FL)
3884 | EXT2_IMMUTABLE_FL
3885 #endif
3886 #ifdef FS_JOURNAL_DATA_FL
3887 | FS_JOURNAL_DATA_FL
3888 #endif
3889 ;
3890
3891 if (a->todo & TODO_FFLAGS) {
3892 archive_entry_fflags(a->entry, &set, &clear);
3893
3894 /*
3895 * The first test encourages the compiler to eliminate
3896 * all of this if it's not necessary.
3897 */
3898 if ((critical_flags != 0) && (set & critical_flags)) {
3899 le = current_fixup(a, a->name);
3900 if (le == NULL)
3901 return (ARCHIVE_FATAL);
3902 le->filetype = archive_entry_filetype(a->entry);
3903 le->fixup |= TODO_FFLAGS;
3904 le->fflags_set = set;
3905 /* Store the mode if it's not already there. */
3906 if ((le->fixup & TODO_MODE) == 0)
3907 le->mode = mode;
3908 } else {
3909 r = set_fflags_platform(a, a->fd,
3910 a->name, mode, set, clear);
3911 if (r != ARCHIVE_OK)
3912 return (r);
3913 }
3914 }
3915 return (ARCHIVE_OK);
3916 }
3917
3918 static int
clear_nochange_fflags(struct archive_write_disk * a)3919 clear_nochange_fflags(struct archive_write_disk *a)
3920 {
3921 mode_t mode = archive_entry_mode(a->entry);
3922 const int nochange_flags = 0
3923 #ifdef SF_IMMUTABLE
3924 | SF_IMMUTABLE
3925 #endif
3926 #ifdef UF_IMMUTABLE
3927 | UF_IMMUTABLE
3928 #endif
3929 #ifdef SF_APPEND
3930 | SF_APPEND
3931 #endif
3932 #ifdef UF_APPEND
3933 | UF_APPEND
3934 #endif
3935 #if defined(FS_APPEND_FL)
3936 | FS_APPEND_FL
3937 #elif defined(EXT2_APPEND_FL)
3938 | EXT2_APPEND_FL
3939 #endif
3940 #if defined(FS_IMMUTABLE_FL)
3941 | FS_IMMUTABLE_FL
3942 #elif defined(EXT2_IMMUTABLE_FL)
3943 | EXT2_IMMUTABLE_FL
3944 #endif
3945 ;
3946
3947 return (set_fflags_platform(a, a->fd, a->name, mode, 0,
3948 nochange_flags));
3949 }
3950
3951
3952 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
3953 /*
3954 * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
3955 */
3956 static int
set_fflags_platform(struct archive_write_disk * a,int fd,const char * name,mode_t mode,unsigned long set,unsigned long clear)3957 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3958 mode_t mode, unsigned long set, unsigned long clear)
3959 {
3960 int r;
3961 const int sf_mask = 0
3962 #ifdef SF_APPEND
3963 | SF_APPEND
3964 #endif
3965 #ifdef SF_ARCHIVED
3966 | SF_ARCHIVED
3967 #endif
3968 #ifdef SF_IMMUTABLE
3969 | SF_IMMUTABLE
3970 #endif
3971 #ifdef SF_NOUNLINK
3972 | SF_NOUNLINK
3973 #endif
3974 ;
3975 (void)mode; /* UNUSED */
3976
3977 if (set == 0 && clear == 0)
3978 return (ARCHIVE_OK);
3979
3980 /*
3981 * XXX Is the stat here really necessary? Or can I just use
3982 * the 'set' flags directly? In particular, I'm not sure
3983 * about the correct approach if we're overwriting an existing
3984 * file that already has flags on it. XXX
3985 */
3986 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3987 return (r);
3988
3989 a->st.st_flags &= ~clear;
3990 a->st.st_flags |= set;
3991
3992 /* Only super-user may change SF_* flags */
3993
3994 if (a->user_uid != 0)
3995 a->st.st_flags &= ~sf_mask;
3996
3997 #ifdef HAVE_FCHFLAGS
3998 /* If platform has fchflags() and we were given an fd, use it. */
3999 if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
4000 return (ARCHIVE_OK);
4001 #endif
4002 /*
4003 * If we can't use the fd to set the flags, we'll use the
4004 * pathname to set flags. We prefer lchflags() but will use
4005 * chflags() if we must.
4006 */
4007 #ifdef HAVE_LCHFLAGS
4008 if (lchflags(name, a->st.st_flags) == 0)
4009 return (ARCHIVE_OK);
4010 #elif defined(HAVE_CHFLAGS)
4011 if (S_ISLNK(a->st.st_mode)) {
4012 archive_set_error(&a->archive, errno,
4013 "Can't set file flags on symlink.");
4014 return (ARCHIVE_WARN);
4015 }
4016 if (chflags(name, a->st.st_flags) == 0)
4017 return (ARCHIVE_OK);
4018 #endif
4019 archive_set_error(&a->archive, errno,
4020 "Failed to set file flags");
4021 return (ARCHIVE_WARN);
4022 }
4023
4024 #elif (defined(FS_IOC_GETFLAGS) && defined(FS_IOC_SETFLAGS) && \
4025 defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \
4026 (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && \
4027 defined(HAVE_WORKING_EXT2_IOC_GETFLAGS))
4028 /*
4029 * Linux uses ioctl() to read and write file flags.
4030 */
4031 static int
set_fflags_platform(struct archive_write_disk * a,int fd,const char * name,mode_t mode,unsigned long set,unsigned long clear)4032 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
4033 mode_t mode, unsigned long set, unsigned long clear)
4034 {
4035 int ret;
4036 int myfd = fd;
4037 int newflags, oldflags;
4038 /*
4039 * Linux has no define for the flags that are only settable by
4040 * the root user. This code may seem a little complex, but
4041 * there seem to be some Linux systems that lack these
4042 * defines. (?) The code below degrades reasonably gracefully
4043 * if sf_mask is incomplete.
4044 */
4045 const int sf_mask = 0
4046 #if defined(FS_IMMUTABLE_FL)
4047 | FS_IMMUTABLE_FL
4048 #elif defined(EXT2_IMMUTABLE_FL)
4049 | EXT2_IMMUTABLE_FL
4050 #endif
4051 #if defined(FS_APPEND_FL)
4052 | FS_APPEND_FL
4053 #elif defined(EXT2_APPEND_FL)
4054 | EXT2_APPEND_FL
4055 #endif
4056 #if defined(FS_JOURNAL_DATA_FL)
4057 | FS_JOURNAL_DATA_FL
4058 #endif
4059 ;
4060
4061 if (set == 0 && clear == 0)
4062 return (ARCHIVE_OK);
4063 /* Only regular files and dirs can have flags. */
4064 if (!S_ISREG(mode) && !S_ISDIR(mode))
4065 return (ARCHIVE_OK);
4066
4067 /* If we weren't given an fd, open it ourselves. */
4068 if (myfd < 0) {
4069 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY |
4070 O_CLOEXEC | O_NOFOLLOW);
4071 __archive_ensure_cloexec_flag(myfd);
4072 }
4073 if (myfd < 0)
4074 return (ARCHIVE_OK);
4075
4076 /*
4077 * XXX As above, this would be way simpler if we didn't have
4078 * to read the current flags from disk. XXX
4079 */
4080 ret = ARCHIVE_OK;
4081
4082 /* Read the current file flags. */
4083 if (ioctl(myfd,
4084 #ifdef FS_IOC_GETFLAGS
4085 FS_IOC_GETFLAGS,
4086 #else
4087 EXT2_IOC_GETFLAGS,
4088 #endif
4089 &oldflags) < 0)
4090 goto fail;
4091
4092 /* Try setting the flags as given. */
4093 newflags = (oldflags & ~clear) | set;
4094 if (ioctl(myfd,
4095 #ifdef FS_IOC_SETFLAGS
4096 FS_IOC_SETFLAGS,
4097 #else
4098 EXT2_IOC_SETFLAGS,
4099 #endif
4100 &newflags) >= 0)
4101 goto cleanup;
4102 if (errno != EPERM)
4103 goto fail;
4104
4105 /* If we couldn't set all the flags, try again with a subset. */
4106 newflags &= ~sf_mask;
4107 oldflags &= sf_mask;
4108 newflags |= oldflags;
4109 if (ioctl(myfd,
4110 #ifdef FS_IOC_SETFLAGS
4111 FS_IOC_SETFLAGS,
4112 #else
4113 EXT2_IOC_SETFLAGS,
4114 #endif
4115 &newflags) >= 0)
4116 goto cleanup;
4117
4118 /* We couldn't set the flags, so report the failure. */
4119 fail:
4120 archive_set_error(&a->archive, errno,
4121 "Failed to set file flags");
4122 ret = ARCHIVE_WARN;
4123 cleanup:
4124 if (fd < 0)
4125 close(myfd);
4126 return (ret);
4127 }
4128
4129 #else
4130
4131 /*
4132 * Of course, some systems have neither BSD chflags() nor Linux' flags
4133 * support through ioctl().
4134 */
4135 static int
set_fflags_platform(struct archive_write_disk * a,int fd,const char * name,mode_t mode,unsigned long set,unsigned long clear)4136 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
4137 mode_t mode, unsigned long set, unsigned long clear)
4138 {
4139 (void)a; /* UNUSED */
4140 (void)fd; /* UNUSED */
4141 (void)name; /* UNUSED */
4142 (void)mode; /* UNUSED */
4143 (void)set; /* UNUSED */
4144 (void)clear; /* UNUSED */
4145 return (ARCHIVE_OK);
4146 }
4147
4148 #endif /* __linux */
4149
4150 #ifndef HAVE_COPYFILE_H
4151 /* Default is to simply drop Mac extended metadata. */
4152 static int
set_mac_metadata(struct archive_write_disk * a,const char * pathname,const void * metadata,size_t metadata_size)4153 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4154 const void *metadata, size_t metadata_size)
4155 {
4156 (void)a; /* UNUSED */
4157 (void)pathname; /* UNUSED */
4158 (void)metadata; /* UNUSED */
4159 (void)metadata_size; /* UNUSED */
4160 return (ARCHIVE_OK);
4161 }
4162
4163 static int
fixup_appledouble(struct archive_write_disk * a,const char * pathname)4164 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4165 {
4166 (void)a; /* UNUSED */
4167 (void)pathname; /* UNUSED */
4168 return (ARCHIVE_OK);
4169 }
4170 #else
4171
4172 /*
4173 * On Mac OS, we use copyfile() to unpack the metadata and
4174 * apply it to the target file.
4175 */
4176
4177 #if defined(HAVE_SYS_XATTR_H)
4178 static int
copy_xattrs(struct archive_write_disk * a,int tmpfd,int dffd)4179 copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
4180 {
4181 ssize_t xattr_size;
4182 char *xattr_names = NULL, *xattr_val = NULL;
4183 int ret = ARCHIVE_OK, xattr_i;
4184
4185 xattr_size = flistxattr(tmpfd, NULL, 0, 0);
4186 if (xattr_size == -1) {
4187 archive_set_error(&a->archive, errno,
4188 "Failed to read metadata(xattr)");
4189 ret = ARCHIVE_WARN;
4190 goto exit_xattr;
4191 }
4192 xattr_names = malloc(xattr_size);
4193 if (xattr_names == NULL) {
4194 archive_set_error(&a->archive, ENOMEM,
4195 "Can't allocate memory for metadata(xattr)");
4196 ret = ARCHIVE_FATAL;
4197 goto exit_xattr;
4198 }
4199 xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
4200 if (xattr_size == -1) {
4201 archive_set_error(&a->archive, errno,
4202 "Failed to read metadata(xattr)");
4203 ret = ARCHIVE_WARN;
4204 goto exit_xattr;
4205 }
4206 for (xattr_i = 0; xattr_i < xattr_size;
4207 xattr_i += strlen(xattr_names + xattr_i) + 1) {
4208 char *p;
4209 ssize_t s;
4210 int f;
4211
4212 s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
4213 if (s == -1) {
4214 archive_set_error(&a->archive, errno,
4215 "Failed to get metadata(xattr)");
4216 ret = ARCHIVE_WARN;
4217 goto exit_xattr;
4218 }
4219 p = realloc(xattr_val, s);
4220 if (p == NULL) {
4221 archive_set_error(&a->archive, ENOMEM,
4222 "Failed to get metadata(xattr)");
4223 ret = ARCHIVE_WARN;
4224 goto exit_xattr;
4225 }
4226 xattr_val = p;
4227 s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4228 if (s == -1) {
4229 archive_set_error(&a->archive, errno,
4230 "Failed to get metadata(xattr)");
4231 ret = ARCHIVE_WARN;
4232 goto exit_xattr;
4233 }
4234 f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
4235 if (f == -1) {
4236 archive_set_error(&a->archive, errno,
4237 "Failed to get metadata(xattr)");
4238 ret = ARCHIVE_WARN;
4239 goto exit_xattr;
4240 }
4241 }
4242 exit_xattr:
4243 free(xattr_names);
4244 free(xattr_val);
4245 return (ret);
4246 }
4247 #endif
4248
4249 static int
copy_acls(struct archive_write_disk * a,int tmpfd,int dffd)4250 copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
4251 {
4252 #ifndef HAVE_SYS_ACL_H
4253 return 0;
4254 #else
4255 acl_t acl, dfacl = NULL;
4256 int acl_r, ret = ARCHIVE_OK;
4257
4258 acl = acl_get_fd(tmpfd);
4259 if (acl == NULL) {
4260 if (errno == ENOENT)
4261 /* There are not any ACLs. */
4262 return (ret);
4263 archive_set_error(&a->archive, errno,
4264 "Failed to get metadata(acl)");
4265 ret = ARCHIVE_WARN;
4266 goto exit_acl;
4267 }
4268 dfacl = acl_dup(acl);
4269 acl_r = acl_set_fd(dffd, dfacl);
4270 if (acl_r == -1) {
4271 archive_set_error(&a->archive, errno,
4272 "Failed to get metadata(acl)");
4273 ret = ARCHIVE_WARN;
4274 goto exit_acl;
4275 }
4276 exit_acl:
4277 if (acl)
4278 acl_free(acl);
4279 if (dfacl)
4280 acl_free(dfacl);
4281 return (ret);
4282 #endif
4283 }
4284
4285 static int
create_tempdatafork(struct archive_write_disk * a,const char * pathname)4286 create_tempdatafork(struct archive_write_disk *a, const char *pathname)
4287 {
4288 struct archive_string tmpdatafork;
4289 int tmpfd;
4290
4291 archive_string_init(&tmpdatafork);
4292 archive_strcpy(&tmpdatafork, pathname);
4293 archive_string_dirname(&tmpdatafork);
4294 archive_strcat(&tmpdatafork, "/tar.XXXXXXXX");
4295 tmpfd = __archive_mkstemp(tmpdatafork.s);
4296 if (tmpfd < 0) {
4297 archive_set_error(&a->archive, errno,
4298 "Failed to mkstemp");
4299 archive_string_free(&tmpdatafork);
4300 return (-1);
4301 }
4302 if (copyfile(pathname, tmpdatafork.s, 0,
4303 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4304 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4305 archive_set_error(&a->archive, errno,
4306 "Failed to restore metadata");
4307 close(tmpfd);
4308 tmpfd = -1;
4309 }
4310 unlink(tmpdatafork.s);
4311 archive_string_free(&tmpdatafork);
4312 return (tmpfd);
4313 }
4314
4315 static int
copy_metadata(struct archive_write_disk * a,const char * metadata,const char * datafork,int datafork_compressed)4316 copy_metadata(struct archive_write_disk *a, const char *metadata,
4317 const char *datafork, int datafork_compressed)
4318 {
4319 int ret = ARCHIVE_OK;
4320
4321 if (datafork_compressed) {
4322 int dffd, tmpfd;
4323
4324 tmpfd = create_tempdatafork(a, metadata);
4325 if (tmpfd == -1)
4326 return (ARCHIVE_WARN);
4327
4328 /*
4329 * Do not open the data fork compressed by HFS+ compression
4330 * with at least a writing mode(O_RDWR or O_WRONLY). it
4331 * makes the data fork uncompressed.
4332 */
4333 dffd = open(datafork, 0);
4334 if (dffd == -1) {
4335 archive_set_error(&a->archive, errno,
4336 "Failed to open the data fork for metadata");
4337 close(tmpfd);
4338 return (ARCHIVE_WARN);
4339 }
4340
4341 #if defined(HAVE_SYS_XATTR_H)
4342 ret = copy_xattrs(a, tmpfd, dffd);
4343 if (ret == ARCHIVE_OK)
4344 #endif
4345 ret = copy_acls(a, tmpfd, dffd);
4346 close(tmpfd);
4347 close(dffd);
4348 } else {
4349 if (copyfile(metadata, datafork, 0,
4350 COPYFILE_UNPACK | COPYFILE_NOFOLLOW
4351 | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
4352 archive_set_error(&a->archive, errno,
4353 "Failed to restore metadata");
4354 ret = ARCHIVE_WARN;
4355 }
4356 }
4357 return (ret);
4358 }
4359
4360 static int
set_mac_metadata(struct archive_write_disk * a,const char * pathname,const void * metadata,size_t metadata_size)4361 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
4362 const void *metadata, size_t metadata_size)
4363 {
4364 struct archive_string tmp;
4365 ssize_t written;
4366 int fd;
4367 int ret = ARCHIVE_OK;
4368
4369 /* This would be simpler if copyfile() could just accept the
4370 * metadata as a block of memory; then we could sidestep this
4371 * silly dance of writing the data to disk just so that
4372 * copyfile() can read it back in again. */
4373 archive_string_init(&tmp);
4374 archive_strcpy(&tmp, pathname);
4375 archive_string_dirname(&tmp);
4376 archive_strcat(&tmp, "/tar.XXXXXXXX");
4377 fd = __archive_mkstemp(tmp.s);
4378
4379 if (fd < 0) {
4380 archive_set_error(&a->archive, errno,
4381 "Failed to restore metadata");
4382 archive_string_free(&tmp);
4383 return (ARCHIVE_WARN);
4384 }
4385 written = write(fd, metadata, metadata_size);
4386 close(fd);
4387 if ((size_t)written != metadata_size) {
4388 archive_set_error(&a->archive, errno,
4389 "Failed to restore metadata");
4390 ret = ARCHIVE_WARN;
4391 } else {
4392 int compressed;
4393
4394 #if defined(UF_COMPRESSED)
4395 if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
4396 (ret = lazy_stat(a)) == ARCHIVE_OK)
4397 compressed = a->st.st_flags & UF_COMPRESSED;
4398 else
4399 #endif
4400 compressed = 0;
4401 ret = copy_metadata(a, tmp.s, pathname, compressed);
4402 }
4403 unlink(tmp.s);
4404 archive_string_free(&tmp);
4405 return (ret);
4406 }
4407
4408 static int
fixup_appledouble(struct archive_write_disk * a,const char * pathname)4409 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
4410 {
4411 char buff[8];
4412 struct stat st;
4413 const char *p;
4414 struct archive_string datafork;
4415 int fd = -1, ret = ARCHIVE_OK;
4416
4417 archive_string_init(&datafork);
4418 /* Check if the current file name is a type of the resource
4419 * fork file. */
4420 p = strrchr(pathname, '/');
4421 if (p == NULL)
4422 p = pathname;
4423 else
4424 p++;
4425 if (p[0] != '.' || p[1] != '_')
4426 goto skip_appledouble;
4427
4428 /*
4429 * Check if the data fork file exists.
4430 *
4431 * TODO: Check if this write disk object has handled it.
4432 */
4433 archive_strncpy(&datafork, pathname, p - pathname);
4434 archive_strcat(&datafork, p + 2);
4435 if (
4436 #ifdef HAVE_LSTAT
4437 lstat(datafork.s, &st) == -1 ||
4438 #else
4439 la_stat(datafork.s, &st) == -1 ||
4440 #endif
4441 (((st.st_mode & AE_IFMT) != AE_IFREG) &&
4442 ((st.st_mode & AE_IFMT) != AE_IFDIR)))
4443 goto skip_appledouble;
4444
4445 /*
4446 * Check if the file is in the AppleDouble form.
4447 */
4448 fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
4449 __archive_ensure_cloexec_flag(fd);
4450 if (fd < 0) {
4451 archive_set_error(&a->archive, errno,
4452 "Failed to open a restoring file");
4453 ret = ARCHIVE_WARN;
4454 goto skip_appledouble;
4455 }
4456 if (read(fd, buff, 8) == -1) {
4457 archive_set_error(&a->archive, errno,
4458 "Failed to read a restoring file");
4459 close(fd);
4460 ret = ARCHIVE_WARN;
4461 goto skip_appledouble;
4462 }
4463 close(fd);
4464 /* Check AppleDouble Magic Code. */
4465 if (archive_be32dec(buff) != 0x00051607)
4466 goto skip_appledouble;
4467 /* Check AppleDouble Version. */
4468 if (archive_be32dec(buff+4) != 0x00020000)
4469 goto skip_appledouble;
4470
4471 ret = copy_metadata(a, pathname, datafork.s,
4472 #if defined(UF_COMPRESSED)
4473 st.st_flags & UF_COMPRESSED);
4474 #else
4475 0);
4476 #endif
4477 if (ret == ARCHIVE_OK) {
4478 unlink(pathname);
4479 ret = ARCHIVE_EOF;
4480 }
4481 skip_appledouble:
4482 archive_string_free(&datafork);
4483 return (ret);
4484 }
4485 #endif
4486
4487 #if ARCHIVE_XATTR_LINUX || ARCHIVE_XATTR_DARWIN || ARCHIVE_XATTR_AIX
4488 /*
4489 * Restore extended attributes - Linux, Darwin and AIX implementations:
4490 * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
4491 */
4492 static int
set_xattrs(struct archive_write_disk * a)4493 set_xattrs(struct archive_write_disk *a)
4494 {
4495 struct archive_entry *entry = a->entry;
4496 struct archive_string errlist;
4497 int ret = ARCHIVE_OK;
4498 int i = archive_entry_xattr_reset(entry);
4499 short fail = 0;
4500
4501 archive_string_init(&errlist);
4502
4503 while (i--) {
4504 const char *name;
4505 const void *value;
4506 size_t size;
4507 int e;
4508
4509 archive_entry_xattr_next(entry, &name, &value, &size);
4510
4511 if (name == NULL)
4512 continue;
4513 #if ARCHIVE_XATTR_LINUX
4514 /* Linux: quietly skip POSIX.1e ACL extended attributes */
4515 if (strncmp(name, "system.", 7) == 0 &&
4516 (strcmp(name + 7, "posix_acl_access") == 0 ||
4517 strcmp(name + 7, "posix_acl_default") == 0))
4518 continue;
4519 if (strncmp(name, "trusted.SGI_", 12) == 0 &&
4520 (strcmp(name + 12, "ACL_DEFAULT") == 0 ||
4521 strcmp(name + 12, "ACL_FILE") == 0))
4522 continue;
4523
4524 /* Linux: xfsroot namespace is obsolete and unsupported */
4525 if (strncmp(name, "xfsroot.", 8) == 0) {
4526 fail = 1;
4527 archive_strcat(&errlist, name);
4528 archive_strappend_char(&errlist, ' ');
4529 continue;
4530 }
4531 #endif
4532
4533 if (a->fd >= 0) {
4534 #if ARCHIVE_XATTR_LINUX
4535 e = fsetxattr(a->fd, name, value, size, 0);
4536 #elif ARCHIVE_XATTR_DARWIN
4537 e = fsetxattr(a->fd, name, value, size, 0, 0);
4538 #elif ARCHIVE_XATTR_AIX
4539 e = fsetea(a->fd, name, value, size, 0);
4540 #endif
4541 } else {
4542 #if ARCHIVE_XATTR_LINUX
4543 e = lsetxattr(archive_entry_pathname(entry),
4544 name, value, size, 0);
4545 #elif ARCHIVE_XATTR_DARWIN
4546 e = setxattr(archive_entry_pathname(entry),
4547 name, value, size, 0, XATTR_NOFOLLOW);
4548 #elif ARCHIVE_XATTR_AIX
4549 e = lsetea(archive_entry_pathname(entry),
4550 name, value, size, 0);
4551 #endif
4552 }
4553 if (e == -1) {
4554 ret = ARCHIVE_WARN;
4555 archive_strcat(&errlist, name);
4556 archive_strappend_char(&errlist, ' ');
4557 if (errno != ENOTSUP && errno != ENOSYS)
4558 fail = 1;
4559 }
4560 }
4561
4562 if (ret == ARCHIVE_WARN) {
4563 if (fail && errlist.length > 0) {
4564 errlist.length--;
4565 errlist.s[errlist.length] = '\0';
4566 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4567 "Cannot restore extended attributes: %s",
4568 errlist.s);
4569 } else
4570 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4571 "Cannot restore extended "
4572 "attributes on this file system.");
4573 }
4574
4575 archive_string_free(&errlist);
4576 return (ret);
4577 }
4578 #elif ARCHIVE_XATTR_FREEBSD
4579 /*
4580 * Restore extended attributes - FreeBSD implementation
4581 */
4582 static int
set_xattrs(struct archive_write_disk * a)4583 set_xattrs(struct archive_write_disk *a)
4584 {
4585 struct archive_entry *entry = a->entry;
4586 struct archive_string errlist;
4587 int ret = ARCHIVE_OK;
4588 int i = archive_entry_xattr_reset(entry);
4589 short fail = 0;
4590
4591 archive_string_init(&errlist);
4592
4593 while (i--) {
4594 const char *name;
4595 const void *value;
4596 size_t size;
4597 archive_entry_xattr_next(entry, &name, &value, &size);
4598 if (name != NULL) {
4599 ssize_t e;
4600 int namespace;
4601
4602 namespace = EXTATTR_NAMESPACE_USER;
4603
4604 if (strncmp(name, "user.", 5) == 0) {
4605 /* "user." attributes go to user namespace */
4606 name += 5;
4607 namespace = EXTATTR_NAMESPACE_USER;
4608 } else if (strncmp(name, "system.", 7) == 0) {
4609 name += 7;
4610 namespace = EXTATTR_NAMESPACE_SYSTEM;
4611 if (!strcmp(name, "nfs4.acl") ||
4612 !strcmp(name, "posix1e.acl_access") ||
4613 !strcmp(name, "posix1e.acl_default"))
4614 continue;
4615 } else {
4616 /* Other namespaces are unsupported */
4617 archive_strcat(&errlist, name);
4618 archive_strappend_char(&errlist, ' ');
4619 fail = 1;
4620 ret = ARCHIVE_WARN;
4621 continue;
4622 }
4623
4624 if (a->fd >= 0) {
4625 /*
4626 * On FreeBSD, extattr_set_fd does not
4627 * return the same as
4628 * extattr_set_file. It returns zero
4629 * on success, non-zero on failure.
4630 *
4631 * We can detect the failure by
4632 * manually setting errno prior to the
4633 * call and checking after.
4634 *
4635 * If errno remains zero, fake the
4636 * return value by setting e to size.
4637 *
4638 * This is a hack for now until I
4639 * (Shawn Webb) get FreeBSD to fix the
4640 * issue, if that's even possible.
4641 */
4642 errno = 0;
4643 e = extattr_set_fd(a->fd, namespace, name,
4644 value, size);
4645 if (e == 0 && errno == 0) {
4646 e = size;
4647 }
4648 } else {
4649 e = extattr_set_link(
4650 archive_entry_pathname(entry), namespace,
4651 name, value, size);
4652 }
4653 if (e != (ssize_t)size) {
4654 archive_strcat(&errlist, name);
4655 archive_strappend_char(&errlist, ' ');
4656 ret = ARCHIVE_WARN;
4657 if (errno != ENOTSUP && errno != ENOSYS)
4658 fail = 1;
4659 }
4660 }
4661 }
4662
4663 if (ret == ARCHIVE_WARN) {
4664 if (fail && errlist.length > 0) {
4665 errlist.length--;
4666 errlist.s[errlist.length] = '\0';
4667
4668 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4669 "Cannot restore extended attributes: %s",
4670 errlist.s);
4671 } else
4672 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
4673 "Cannot restore extended "
4674 "attributes on this file system.");
4675 }
4676
4677 archive_string_free(&errlist);
4678 return (ret);
4679 }
4680 #else
4681 /*
4682 * Restore extended attributes - stub implementation for unsupported systems
4683 */
4684 static int
set_xattrs(struct archive_write_disk * a)4685 set_xattrs(struct archive_write_disk *a)
4686 {
4687 static int warning_done = 0;
4688
4689 /* If there aren't any extended attributes, then it's okay not
4690 * to extract them, otherwise, issue a single warning. */
4691 if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
4692 warning_done = 1;
4693 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4694 "Cannot restore extended attributes on this system");
4695 return (ARCHIVE_WARN);
4696 }
4697 /* Warning was already emitted; suppress further warnings. */
4698 return (ARCHIVE_OK);
4699 }
4700 #endif
4701
4702 /*
4703 * Test if file on disk is older than entry.
4704 */
4705 static int
older(struct stat * st,struct archive_entry * entry)4706 older(struct stat *st, struct archive_entry *entry)
4707 {
4708 /* First, test the seconds and return if we have a definite answer. */
4709 /* Definitely older. */
4710 if (to_int64_time(st->st_mtime) < to_int64_time(archive_entry_mtime(entry)))
4711 return (1);
4712 /* Definitely younger. */
4713 if (to_int64_time(st->st_mtime) > to_int64_time(archive_entry_mtime(entry)))
4714 return (0);
4715 /* If this platform supports fractional seconds, try those. */
4716 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
4717 /* Definitely older. */
4718 if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
4719 return (1);
4720 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
4721 /* Definitely older. */
4722 if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
4723 return (1);
4724 #elif HAVE_STRUCT_STAT_ST_MTIME_N
4725 /* older. */
4726 if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
4727 return (1);
4728 #elif HAVE_STRUCT_STAT_ST_UMTIME
4729 /* older. */
4730 if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
4731 return (1);
4732 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
4733 /* older. */
4734 if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
4735 return (1);
4736 #else
4737 /* This system doesn't have high-res timestamps. */
4738 #endif
4739 /* Same age or newer, so not older. */
4740 return (0);
4741 }
4742
4743 #ifndef ARCHIVE_ACL_SUPPORT
4744 int
archive_write_disk_set_acls(struct archive * a,int fd,const char * name,struct archive_acl * abstract_acl,__LA_MODE_T mode)4745 archive_write_disk_set_acls(struct archive *a, int fd, const char *name,
4746 struct archive_acl *abstract_acl, __LA_MODE_T mode)
4747 {
4748 (void)a; /* UNUSED */
4749 (void)fd; /* UNUSED */
4750 (void)name; /* UNUSED */
4751 (void)abstract_acl; /* UNUSED */
4752 (void)mode; /* UNUSED */
4753 return (ARCHIVE_OK);
4754 }
4755 #endif
4756
4757 /*
4758 * Close the file descriptor if one is open.
4759 */
close_file_descriptor(struct archive_write_disk * a)4760 static void close_file_descriptor(struct archive_write_disk* a)
4761 {
4762 if (a->fd >= 0) {
4763 close(a->fd);
4764 a->fd = -1;
4765 }
4766 }
4767
4768
4769 #endif /* !_WIN32 || __CYGWIN__ */
4770
4771