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