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