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