]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/libarchive/libarchive/archive_write_disk_posix.c
MFC r309300,r309363,r309405,r309523,r309590,r310185,r310623:
[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 *)calloc(1, sizeof(*a));
1783         if (a == NULL)
1784                 return (NULL);
1785         a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
1786         /* We're ready to write a header immediately. */
1787         a->archive.state = ARCHIVE_STATE_HEADER;
1788         a->archive.vtable = archive_write_disk_vtable();
1789         a->start_time = time(NULL);
1790         /* Query and restore the umask. */
1791         umask(a->user_umask = umask(0));
1792 #ifdef HAVE_GETEUID
1793         a->user_uid = geteuid();
1794 #endif /* HAVE_GETEUID */
1795         if (archive_string_ensure(&a->path_safe, 512) == NULL) {
1796                 free(a);
1797                 return (NULL);
1798         }
1799 #ifdef HAVE_ZLIB_H
1800         a->decmpfs_compression_level = 5;
1801 #endif
1802         return (&a->archive);
1803 }
1804
1805
1806 /*
1807  * If pathname is longer than PATH_MAX, chdir to a suitable
1808  * intermediate dir and edit the path down to a shorter suffix.  Note
1809  * that this routine never returns an error; if the chdir() attempt
1810  * fails for any reason, we just go ahead with the long pathname.  The
1811  * object creation is likely to fail, but any error will get handled
1812  * at that time.
1813  */
1814 #if defined(HAVE_FCHDIR) && defined(PATH_MAX)
1815 static void
1816 edit_deep_directories(struct archive_write_disk *a)
1817 {
1818         int ret;
1819         char *tail = a->name;
1820
1821         /* If path is short, avoid the open() below. */
1822         if (strlen(tail) < PATH_MAX)
1823                 return;
1824
1825         /* Try to record our starting dir. */
1826         a->restore_pwd = open(".", O_RDONLY | O_BINARY | O_CLOEXEC);
1827         __archive_ensure_cloexec_flag(a->restore_pwd);
1828         if (a->restore_pwd < 0)
1829                 return;
1830
1831         /* As long as the path is too long... */
1832         while (strlen(tail) >= PATH_MAX) {
1833                 /* Locate a dir prefix shorter than PATH_MAX. */
1834                 tail += PATH_MAX - 8;
1835                 while (tail > a->name && *tail != '/')
1836                         tail--;
1837                 /* Exit if we find a too-long path component. */
1838                 if (tail <= a->name)
1839                         return;
1840                 /* Create the intermediate dir and chdir to it. */
1841                 *tail = '\0'; /* Terminate dir portion */
1842                 ret = create_dir(a, a->name);
1843                 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
1844                         ret = ARCHIVE_FAILED;
1845                 *tail = '/'; /* Restore the / we removed. */
1846                 if (ret != ARCHIVE_OK)
1847                         return;
1848                 tail++;
1849                 /* The chdir() succeeded; we've now shortened the path. */
1850                 a->name = tail;
1851         }
1852         return;
1853 }
1854 #endif
1855
1856 /*
1857  * The main restore function.
1858  */
1859 static int
1860 restore_entry(struct archive_write_disk *a)
1861 {
1862         int ret = ARCHIVE_OK, en;
1863
1864         if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
1865                 /*
1866                  * TODO: Fix this.  Apparently, there are platforms
1867                  * that still allow root to hose the entire filesystem
1868                  * by unlinking a dir.  The S_ISDIR() test above
1869                  * prevents us from using unlink() here if the new
1870                  * object is a dir, but that doesn't mean the old
1871                  * object isn't a dir.
1872                  */
1873                 if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
1874                         (void)clear_nochange_fflags(a);
1875                 if (unlink(a->name) == 0) {
1876                         /* We removed it, reset cached stat. */
1877                         a->pst = NULL;
1878                 } else if (errno == ENOENT) {
1879                         /* File didn't exist, that's just as good. */
1880                 } else if (rmdir(a->name) == 0) {
1881                         /* It was a dir, but now it's gone. */
1882                         a->pst = NULL;
1883                 } else {
1884                         /* We tried, but couldn't get rid of it. */
1885                         archive_set_error(&a->archive, errno,
1886                             "Could not unlink");
1887                         return(ARCHIVE_FAILED);
1888                 }
1889         }
1890
1891         /* Try creating it first; if this fails, we'll try to recover. */
1892         en = create_filesystem_object(a);
1893
1894         if ((en == ENOTDIR || en == ENOENT)
1895             && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
1896                 /* If the parent dir doesn't exist, try creating it. */
1897                 create_parent_dir(a, a->name);
1898                 /* Now try to create the object again. */
1899                 en = create_filesystem_object(a);
1900         }
1901
1902         if ((en == ENOENT) && (archive_entry_hardlink(a->entry) != NULL)) {
1903                 archive_set_error(&a->archive, en,
1904                     "Hard-link target '%s' does not exist.",
1905                     archive_entry_hardlink(a->entry));
1906                 return (ARCHIVE_FAILED);
1907         }
1908
1909         if ((en == EISDIR || en == EEXIST)
1910             && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1911                 /* If we're not overwriting, we're done. */
1912                 archive_entry_unset_size(a->entry);
1913                 return (ARCHIVE_OK);
1914         }
1915
1916         /*
1917          * Some platforms return EISDIR if you call
1918          * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
1919          * return EEXIST.  POSIX is ambiguous, requiring EISDIR
1920          * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
1921          * on an existing item.
1922          */
1923         if (en == EISDIR) {
1924                 /* A dir is in the way of a non-dir, rmdir it. */
1925                 if (rmdir(a->name) != 0) {
1926                         archive_set_error(&a->archive, errno,
1927                             "Can't remove already-existing dir");
1928                         return (ARCHIVE_FAILED);
1929                 }
1930                 a->pst = NULL;
1931                 /* Try again. */
1932                 en = create_filesystem_object(a);
1933         } else if (en == EEXIST) {
1934                 /*
1935                  * We know something is in the way, but we don't know what;
1936                  * we need to find out before we go any further.
1937                  */
1938                 int r = 0;
1939                 /*
1940                  * The SECURE_SYMLINKS logic has already removed a
1941                  * symlink to a dir if the client wants that.  So
1942                  * follow the symlink if we're creating a dir.
1943                  */
1944                 if (S_ISDIR(a->mode))
1945                         r = stat(a->name, &a->st);
1946                 /*
1947                  * If it's not a dir (or it's a broken symlink),
1948                  * then don't follow it.
1949                  */
1950                 if (r != 0 || !S_ISDIR(a->mode))
1951                         r = lstat(a->name, &a->st);
1952                 if (r != 0) {
1953                         archive_set_error(&a->archive, errno,
1954                             "Can't stat existing object");
1955                         return (ARCHIVE_FAILED);
1956                 }
1957
1958                 /*
1959                  * NO_OVERWRITE_NEWER doesn't apply to directories.
1960                  */
1961                 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
1962                     &&  !S_ISDIR(a->st.st_mode)) {
1963                         if (!older(&(a->st), a->entry)) {
1964                                 archive_entry_unset_size(a->entry);
1965                                 return (ARCHIVE_OK);
1966                         }
1967                 }
1968
1969                 /* If it's our archive, we're done. */
1970                 if (a->skip_file_set &&
1971                     a->st.st_dev == (dev_t)a->skip_file_dev &&
1972                     a->st.st_ino == (ino_t)a->skip_file_ino) {
1973                         archive_set_error(&a->archive, 0,
1974                             "Refusing to overwrite archive");
1975                         return (ARCHIVE_FAILED);
1976                 }
1977
1978                 if (!S_ISDIR(a->st.st_mode)) {
1979                         /* A non-dir is in the way, unlink it. */
1980                         if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
1981                                 (void)clear_nochange_fflags(a);
1982                         if (unlink(a->name) != 0) {
1983                                 archive_set_error(&a->archive, errno,
1984                                     "Can't unlink already-existing object");
1985                                 return (ARCHIVE_FAILED);
1986                         }
1987                         a->pst = NULL;
1988                         /* Try again. */
1989                         en = create_filesystem_object(a);
1990                 } else if (!S_ISDIR(a->mode)) {
1991                         /* A dir is in the way of a non-dir, rmdir it. */
1992                         if (a->flags & ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS)
1993                                 (void)clear_nochange_fflags(a);
1994                         if (rmdir(a->name) != 0) {
1995                                 archive_set_error(&a->archive, errno,
1996                                     "Can't replace existing directory with non-directory");
1997                                 return (ARCHIVE_FAILED);
1998                         }
1999                         /* Try again. */
2000                         en = create_filesystem_object(a);
2001                 } else {
2002                         /*
2003                          * There's a dir in the way of a dir.  Don't
2004                          * waste time with rmdir()/mkdir(), just fix
2005                          * up the permissions on the existing dir.
2006                          * Note that we don't change perms on existing
2007                          * dirs unless _EXTRACT_PERM is specified.
2008                          */
2009                         if ((a->mode != a->st.st_mode)
2010                             && (a->todo & TODO_MODE_FORCE))
2011                                 a->deferred |= (a->todo & TODO_MODE);
2012                         /* Ownership doesn't need deferred fixup. */
2013                         en = 0; /* Forget the EEXIST. */
2014                 }
2015         }
2016
2017         if (en) {
2018                 /* Everything failed; give up here. */
2019                 if ((&a->archive)->error == NULL)
2020                         archive_set_error(&a->archive, en, "Can't create '%s'",
2021                             a->name);
2022                 return (ARCHIVE_FAILED);
2023         }
2024
2025         a->pst = NULL; /* Cached stat data no longer valid. */
2026         return (ret);
2027 }
2028
2029 /*
2030  * Returns 0 if creation succeeds, or else returns errno value from
2031  * the failed system call.   Note:  This function should only ever perform
2032  * a single system call.
2033  */
2034 static int
2035 create_filesystem_object(struct archive_write_disk *a)
2036 {
2037         /* Create the entry. */
2038         const char *linkname;
2039         mode_t final_mode, mode;
2040         int r;
2041         /* these for check_symlinks_fsobj */
2042         char *linkname_copy;    /* non-const copy of linkname */
2043         struct archive_string error_string;
2044         int error_number;
2045
2046         /* We identify hard/symlinks according to the link names. */
2047         /* Since link(2) and symlink(2) don't handle modes, we're done here. */
2048         linkname = archive_entry_hardlink(a->entry);
2049         if (linkname != NULL) {
2050 #if !HAVE_LINK
2051                 return (EPERM);
2052 #else
2053                 archive_string_init(&error_string);
2054                 linkname_copy = strdup(linkname);
2055                 if (linkname_copy == NULL) {
2056                     return (EPERM);
2057                 }
2058                 /*
2059                  * TODO: consider using the cleaned-up path as the link
2060                  * target?
2061                  */
2062                 r = cleanup_pathname_fsobj(linkname_copy, &error_number,
2063                     &error_string, a->flags);
2064                 if (r != ARCHIVE_OK) {
2065                         archive_set_error(&a->archive, error_number, "%s",
2066                             error_string.s);
2067                         free(linkname_copy);
2068                         /*
2069                          * EPERM is more appropriate than error_number for our
2070                          * callers
2071                          */
2072                         return (EPERM);
2073                 }
2074                 r = check_symlinks_fsobj(linkname_copy, &error_number,
2075                     &error_string, a->flags);
2076                 if (r != ARCHIVE_OK) {
2077                         archive_set_error(&a->archive, error_number, "%s",
2078                             error_string.s);
2079                         free(linkname_copy);
2080                         /*
2081                          * EPERM is more appropriate than error_number for our
2082                          * callers
2083                          */
2084                         return (EPERM);
2085                 }
2086                 free(linkname_copy);
2087                 r = link(linkname, a->name) ? errno : 0;
2088                 /*
2089                  * New cpio and pax formats allow hardlink entries
2090                  * to carry data, so we may have to open the file
2091                  * for hardlink entries.
2092                  *
2093                  * If the hardlink was successfully created and
2094                  * the archive doesn't have carry data for it,
2095                  * consider it to be non-authoritative for meta data.
2096                  * This is consistent with GNU tar and BSD pax.
2097                  * If the hardlink does carry data, let the last
2098                  * archive entry decide ownership.
2099                  */
2100                 if (r == 0 && a->filesize <= 0) {
2101                         a->todo = 0;
2102                         a->deferred = 0;
2103                 } else if (r == 0 && a->filesize > 0) {
2104                         a->fd = open(a->name, O_WRONLY | O_TRUNC | O_BINARY
2105                             | O_CLOEXEC | O_NOFOLLOW);
2106                         __archive_ensure_cloexec_flag(a->fd);
2107                         if (a->fd < 0)
2108                                 r = errno;
2109                 }
2110                 return (r);
2111 #endif
2112         }
2113         linkname = archive_entry_symlink(a->entry);
2114         if (linkname != NULL) {
2115 #if HAVE_SYMLINK
2116                 return symlink(linkname, a->name) ? errno : 0;
2117 #else
2118                 return (EPERM);
2119 #endif
2120         }
2121
2122         /*
2123          * The remaining system calls all set permissions, so let's
2124          * try to take advantage of that to avoid an extra chmod()
2125          * call.  (Recall that umask is set to zero right now!)
2126          */
2127
2128         /* Mode we want for the final restored object (w/o file type bits). */
2129         final_mode = a->mode & 07777;
2130         /*
2131          * The mode that will actually be restored in this step.  Note
2132          * that SUID, SGID, etc, require additional work to ensure
2133          * security, so we never restore them at this point.
2134          */
2135         mode = final_mode & 0777 & ~a->user_umask;
2136
2137         switch (a->mode & AE_IFMT) {
2138         default:
2139                 /* POSIX requires that we fall through here. */
2140                 /* FALLTHROUGH */
2141         case AE_IFREG:
2142                 a->fd = open(a->name,
2143                     O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode);
2144                 __archive_ensure_cloexec_flag(a->fd);
2145                 r = (a->fd < 0);
2146                 break;
2147         case AE_IFCHR:
2148 #ifdef HAVE_MKNOD
2149                 /* Note: we use AE_IFCHR for the case label, and
2150                  * S_IFCHR for the mknod() call.  This is correct.  */
2151                 r = mknod(a->name, mode | S_IFCHR,
2152                     archive_entry_rdev(a->entry));
2153                 break;
2154 #else
2155                 /* TODO: Find a better way to warn about our inability
2156                  * to restore a char device node. */
2157                 return (EINVAL);
2158 #endif /* HAVE_MKNOD */
2159         case AE_IFBLK:
2160 #ifdef HAVE_MKNOD
2161                 r = mknod(a->name, mode | S_IFBLK,
2162                     archive_entry_rdev(a->entry));
2163                 break;
2164 #else
2165                 /* TODO: Find a better way to warn about our inability
2166                  * to restore a block device node. */
2167                 return (EINVAL);
2168 #endif /* HAVE_MKNOD */
2169         case AE_IFDIR:
2170                 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
2171                 r = mkdir(a->name, mode);
2172                 if (r == 0) {
2173                         /* Defer setting dir times. */
2174                         a->deferred |= (a->todo & TODO_TIMES);
2175                         a->todo &= ~TODO_TIMES;
2176                         /* Never use an immediate chmod(). */
2177                         /* We can't avoid the chmod() entirely if EXTRACT_PERM
2178                          * because of SysV SGID inheritance. */
2179                         if ((mode != final_mode)
2180                             || (a->flags & ARCHIVE_EXTRACT_PERM))
2181                                 a->deferred |= (a->todo & TODO_MODE);
2182                         a->todo &= ~TODO_MODE;
2183                 }
2184                 break;
2185         case AE_IFIFO:
2186 #ifdef HAVE_MKFIFO
2187                 r = mkfifo(a->name, mode);
2188                 break;
2189 #else
2190                 /* TODO: Find a better way to warn about our inability
2191                  * to restore a fifo. */
2192                 return (EINVAL);
2193 #endif /* HAVE_MKFIFO */
2194         }
2195
2196         /* All the system calls above set errno on failure. */
2197         if (r)
2198                 return (errno);
2199
2200         /* If we managed to set the final mode, we've avoided a chmod(). */
2201         if (mode == final_mode)
2202                 a->todo &= ~TODO_MODE;
2203         return (0);
2204 }
2205
2206 /*
2207  * Cleanup function for archive_extract.  Mostly, this involves processing
2208  * the fixup list, which is used to address a number of problems:
2209  *   * Dir permissions might prevent us from restoring a file in that
2210  *     dir, so we restore the dir with minimum 0700 permissions first,
2211  *     then correct the mode at the end.
2212  *   * Similarly, the act of restoring a file touches the directory
2213  *     and changes the timestamp on the dir, so we have to touch-up dir
2214  *     timestamps at the end as well.
2215  *   * Some file flags can interfere with the restore by, for example,
2216  *     preventing the creation of hardlinks to those files.
2217  *   * Mac OS extended metadata includes ACLs, so must be deferred on dirs.
2218  *
2219  * Note that tar/cpio do not require that archives be in a particular
2220  * order; there is no way to know when the last file has been restored
2221  * within a directory, so there's no way to optimize the memory usage
2222  * here by fixing up the directory any earlier than the
2223  * end-of-archive.
2224  *
2225  * XXX TODO: Directory ACLs should be restored here, for the same
2226  * reason we set directory perms here. XXX
2227  */
2228 static int
2229 _archive_write_disk_close(struct archive *_a)
2230 {
2231         struct archive_write_disk *a = (struct archive_write_disk *)_a;
2232         struct fixup_entry *next, *p;
2233         int ret;
2234
2235         archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
2236             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
2237             "archive_write_disk_close");
2238         ret = _archive_write_disk_finish_entry(&a->archive);
2239
2240         /* Sort dir list so directories are fixed up in depth-first order. */
2241         p = sort_dir_list(a->fixup_list);
2242
2243         while (p != NULL) {
2244                 a->pst = NULL; /* Mark stat cache as out-of-date. */
2245                 if (p->fixup & TODO_TIMES) {
2246                         set_times(a, -1, p->mode, p->name,
2247                             p->atime, p->atime_nanos,
2248                             p->birthtime, p->birthtime_nanos,
2249                             p->mtime, p->mtime_nanos,
2250                             p->ctime, p->ctime_nanos);
2251                 }
2252                 if (p->fixup & TODO_MODE_BASE)
2253                         chmod(p->name, p->mode);
2254                 if (p->fixup & TODO_ACLS)
2255                         archive_write_disk_set_acls(&a->archive,
2256                                                     -1, p->name, &p->acl);
2257                 if (p->fixup & TODO_FFLAGS)
2258                         set_fflags_platform(a, -1, p->name,
2259                             p->mode, p->fflags_set, 0);
2260                 if (p->fixup & TODO_MAC_METADATA)
2261                         set_mac_metadata(a, p->name, p->mac_metadata,
2262                                          p->mac_metadata_size);
2263                 next = p->next;
2264                 archive_acl_clear(&p->acl);
2265                 free(p->mac_metadata);
2266                 free(p->name);
2267                 free(p);
2268                 p = next;
2269         }
2270         a->fixup_list = NULL;
2271         return (ret);
2272 }
2273
2274 static int
2275 _archive_write_disk_free(struct archive *_a)
2276 {
2277         struct archive_write_disk *a;
2278         int ret;
2279         if (_a == NULL)
2280                 return (ARCHIVE_OK);
2281         archive_check_magic(_a, ARCHIVE_WRITE_DISK_MAGIC,
2282             ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_write_disk_free");
2283         a = (struct archive_write_disk *)_a;
2284         ret = _archive_write_disk_close(&a->archive);
2285         archive_write_disk_set_group_lookup(&a->archive, NULL, NULL, NULL);
2286         archive_write_disk_set_user_lookup(&a->archive, NULL, NULL, NULL);
2287         if (a->entry)
2288                 archive_entry_free(a->entry);
2289         archive_string_free(&a->_name_data);
2290         archive_string_free(&a->archive.error_string);
2291         archive_string_free(&a->path_safe);
2292         a->archive.magic = 0;
2293         __archive_clean(&a->archive);
2294         free(a->decmpfs_header_p);
2295         free(a->resource_fork);
2296         free(a->compressed_buffer);
2297         free(a->uncompressed_buffer);
2298 #if defined(__APPLE__) && defined(UF_COMPRESSED) && defined(HAVE_SYS_XATTR_H)\
2299         && defined(HAVE_ZLIB_H)
2300         if (a->stream_valid) {
2301                 switch (deflateEnd(&a->stream)) {
2302                 case Z_OK:
2303                         break;
2304                 default:
2305                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2306                             "Failed to clean up compressor");
2307                         ret = ARCHIVE_FATAL;
2308                         break;
2309                 }
2310         }
2311 #endif
2312         free(a);
2313         return (ret);
2314 }
2315
2316 /*
2317  * Simple O(n log n) merge sort to order the fixup list.  In
2318  * particular, we want to restore dir timestamps depth-first.
2319  */
2320 static struct fixup_entry *
2321 sort_dir_list(struct fixup_entry *p)
2322 {
2323         struct fixup_entry *a, *b, *t;
2324
2325         if (p == NULL)
2326                 return (NULL);
2327         /* A one-item list is already sorted. */
2328         if (p->next == NULL)
2329                 return (p);
2330
2331         /* Step 1: split the list. */
2332         t = p;
2333         a = p->next->next;
2334         while (a != NULL) {
2335                 /* Step a twice, t once. */
2336                 a = a->next;
2337                 if (a != NULL)
2338                         a = a->next;
2339                 t = t->next;
2340         }
2341         /* Now, t is at the mid-point, so break the list here. */
2342         b = t->next;
2343         t->next = NULL;
2344         a = p;
2345
2346         /* Step 2: Recursively sort the two sub-lists. */
2347         a = sort_dir_list(a);
2348         b = sort_dir_list(b);
2349
2350         /* Step 3: Merge the returned lists. */
2351         /* Pick the first element for the merged list. */
2352         if (strcmp(a->name, b->name) > 0) {
2353                 t = p = a;
2354                 a = a->next;
2355         } else {
2356                 t = p = b;
2357                 b = b->next;
2358         }
2359
2360         /* Always put the later element on the list first. */
2361         while (a != NULL && b != NULL) {
2362                 if (strcmp(a->name, b->name) > 0) {
2363                         t->next = a;
2364                         a = a->next;
2365                 } else {
2366                         t->next = b;
2367                         b = b->next;
2368                 }
2369                 t = t->next;
2370         }
2371
2372         /* Only one list is non-empty, so just splice it on. */
2373         if (a != NULL)
2374                 t->next = a;
2375         if (b != NULL)
2376                 t->next = b;
2377
2378         return (p);
2379 }
2380
2381 /*
2382  * Returns a new, initialized fixup entry.
2383  *
2384  * TODO: Reduce the memory requirements for this list by using a tree
2385  * structure rather than a simple list of names.
2386  */
2387 static struct fixup_entry *
2388 new_fixup(struct archive_write_disk *a, const char *pathname)
2389 {
2390         struct fixup_entry *fe;
2391
2392         fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry));
2393         if (fe == NULL) {
2394                 archive_set_error(&a->archive, ENOMEM,
2395                     "Can't allocate memory for a fixup");
2396                 return (NULL);
2397         }
2398         fe->next = a->fixup_list;
2399         a->fixup_list = fe;
2400         fe->fixup = 0;
2401         fe->name = strdup(pathname);
2402         return (fe);
2403 }
2404
2405 /*
2406  * Returns a fixup structure for the current entry.
2407  */
2408 static struct fixup_entry *
2409 current_fixup(struct archive_write_disk *a, const char *pathname)
2410 {
2411         if (a->current_fixup == NULL)
2412                 a->current_fixup = new_fixup(a, pathname);
2413         return (a->current_fixup);
2414 }
2415
2416 /* Error helper for new *_fsobj functions */
2417 static void
2418 fsobj_error(int *a_eno, struct archive_string *a_estr,
2419     int err, const char *errstr, const char *path)
2420 {
2421         if (a_eno)
2422                 *a_eno = err;
2423         if (a_estr)
2424                 archive_string_sprintf(a_estr, errstr, path);
2425 }
2426
2427 /*
2428  * TODO: Someday, integrate this with the deep dir support; they both
2429  * scan the path and both can be optimized by comparing against other
2430  * recent paths.
2431  */
2432 /* TODO: Extend this to support symlinks on Windows Vista and later. */
2433
2434 /*
2435  * Checks the given path to see if any elements along it are symlinks.  Returns
2436  * ARCHIVE_OK if there are none, otherwise puts an error in errmsg.
2437  */
2438 static int
2439 check_symlinks_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2440     int flags)
2441 {
2442 #if !defined(HAVE_LSTAT)
2443         /* Platform doesn't have lstat, so we can't look for symlinks. */
2444         (void)path; /* UNUSED */
2445         (void)error_number; /* UNUSED */
2446         (void)error_string; /* UNUSED */
2447         (void)flags; /* UNUSED */
2448         return (ARCHIVE_OK);
2449 #else
2450         int res = ARCHIVE_OK;
2451         char *tail;
2452         char *head;
2453         int last;
2454         char c;
2455         int r;
2456         struct stat st;
2457         int restore_pwd;
2458
2459         /* Nothing to do here if name is empty */
2460         if(path[0] == '\0')
2461             return (ARCHIVE_OK);
2462
2463         /*
2464          * Guard against symlink tricks.  Reject any archive entry whose
2465          * destination would be altered by a symlink.
2466          *
2467          * Walk the filename in chunks separated by '/'.  For each segment:
2468          *  - if it doesn't exist, continue
2469          *  - if it's symlink, abort or remove it
2470          *  - if it's a directory and it's not the last chunk, cd into it
2471          * As we go:
2472          *  head points to the current (relative) path
2473          *  tail points to the temporary \0 terminating the segment we're
2474          *      currently examining
2475          *  c holds what used to be in *tail
2476          *  last is 1 if this is the last tail
2477          */
2478         restore_pwd = open(".", O_RDONLY | O_BINARY | O_CLOEXEC);
2479         __archive_ensure_cloexec_flag(restore_pwd);
2480         if (restore_pwd < 0)
2481                 return (ARCHIVE_FATAL);
2482         head = path;
2483         tail = path;
2484         last = 0;
2485         /* TODO: reintroduce a safe cache here? */
2486         /* Skip the root directory if the path is absolute. */
2487         if(tail == path && tail[0] == '/')
2488                 ++tail;
2489         /* Keep going until we've checked the entire name.
2490          * head, tail, path all alias the same string, which is
2491          * temporarily zeroed at tail, so be careful restoring the
2492          * stashed (c=tail[0]) for error messages.
2493          * Exiting the loop with break is okay; continue is not.
2494          */
2495         while (!last) {
2496                 /*
2497                  * Skip the separator we just consumed, plus any adjacent ones
2498                  */
2499                 while (*tail == '/')
2500                     ++tail;
2501                 /* Skip the next path element. */
2502                 while (*tail != '\0' && *tail != '/')
2503                         ++tail;
2504                 /* is this the last path component? */
2505                 last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0');
2506                 /* temporarily truncate the string here */
2507                 c = tail[0];
2508                 tail[0] = '\0';
2509                 /* Check that we haven't hit a symlink. */
2510                 r = lstat(head, &st);
2511                 if (r != 0) {
2512                         tail[0] = c;
2513                         /* We've hit a dir that doesn't exist; stop now. */
2514                         if (errno == ENOENT) {
2515                                 break;
2516                         } else {
2517                                 /*
2518                                  * Treat any other error as fatal - best to be
2519                                  * paranoid here.
2520                                  * Note: This effectively disables deep
2521                                  * directory support when security checks are
2522                                  * enabled. Otherwise, very long pathnames that
2523                                  * trigger an error here could evade the
2524                                  * sandbox.
2525                                  * TODO: We could do better, but it would
2526                                  * probably require merging the symlink checks
2527                                  * with the deep-directory editing.
2528                                  */
2529                                 fsobj_error(a_eno, a_estr, errno,
2530                                     "Could not stat %s", path);
2531                                 res = ARCHIVE_FAILED;
2532                                 break;
2533                         }
2534                 } else if (S_ISDIR(st.st_mode)) {
2535                         if (!last) {
2536                                 if (chdir(head) != 0) {
2537                                         tail[0] = c;
2538                                         fsobj_error(a_eno, a_estr, errno,
2539                                             "Could not chdir %s", path);
2540                                         res = (ARCHIVE_FATAL);
2541                                         break;
2542                                 }
2543                                 /* Our view is now from inside this dir: */
2544                                 head = tail + 1;
2545                         }
2546                 } else if (S_ISLNK(st.st_mode)) {
2547                         if (last) {
2548                                 /*
2549                                  * Last element is symlink; remove it
2550                                  * so we can overwrite it with the
2551                                  * item being extracted.
2552                                  */
2553                                 if (unlink(head)) {
2554                                         tail[0] = c;
2555                                         fsobj_error(a_eno, a_estr, errno,
2556                                             "Could not remove symlink %s",
2557                                             path);
2558                                         res = ARCHIVE_FAILED;
2559                                         break;
2560                                 }
2561                                 /*
2562                                  * Even if we did remove it, a warning
2563                                  * is in order.  The warning is silly,
2564                                  * though, if we're just replacing one
2565                                  * symlink with another symlink.
2566                                  */
2567                                 tail[0] = c;
2568                                 /*
2569                                  * FIXME:  not sure how important this is to
2570                                  * restore
2571                                  */
2572                                 /*
2573                                 if (!S_ISLNK(path)) {
2574                                         fsobj_error(a_eno, a_estr, 0,
2575                                             "Removing symlink %s", path);
2576                                 }
2577                                 */
2578                                 /* Symlink gone.  No more problem! */
2579                                 res = ARCHIVE_OK;
2580                                 break;
2581                         } else if (flags & ARCHIVE_EXTRACT_UNLINK) {
2582                                 /* User asked us to remove problems. */
2583                                 if (unlink(head) != 0) {
2584                                         tail[0] = c;
2585                                         fsobj_error(a_eno, a_estr, 0,
2586                                             "Cannot remove intervening "
2587                                             "symlink %s", path);
2588                                         res = ARCHIVE_FAILED;
2589                                         break;
2590                                 }
2591                                 tail[0] = c;
2592                         } else if ((flags &
2593                             ARCHIVE_EXTRACT_SECURE_SYMLINKS) == 0) {
2594                                 /*
2595                                  * We are not the last element and we want to
2596                                  * follow symlinks if they are a directory.
2597                                  * 
2598                                  * This is needed to extract hardlinks over
2599                                  * symlinks.
2600                                  */
2601                                 r = stat(head, &st);
2602                                 if (r != 0) {
2603                                         tail[0] = c;
2604                                         if (errno == ENOENT) {
2605                                                 break;
2606                                         } else {
2607                                                 fsobj_error(a_eno, a_estr,
2608                                                     errno,
2609                                                     "Could not stat %s", path);
2610                                                 res = (ARCHIVE_FAILED);
2611                                                 break;
2612                                         }
2613                                 } else if (S_ISDIR(st.st_mode)) {
2614                                         if (chdir(head) != 0) {
2615                                                 tail[0] = c;
2616                                                 fsobj_error(a_eno, a_estr,
2617                                                     errno,
2618                                                     "Could not chdir %s", path);
2619                                                 res = (ARCHIVE_FATAL);
2620                                                 break;
2621                                         }
2622                                         /*
2623                                          * Our view is now from inside
2624                                          * this dir:
2625                                          */
2626                                         head = tail + 1;
2627                                 } else {
2628                                         tail[0] = c;
2629                                         fsobj_error(a_eno, a_estr, 0,
2630                                             "Cannot extract through "
2631                                             "symlink %s", path);
2632                                         res = ARCHIVE_FAILED;
2633                                         break;
2634                                 }
2635                         } else {
2636                                 tail[0] = c;
2637                                 fsobj_error(a_eno, a_estr, 0,
2638                                     "Cannot extract through symlink %s", path);
2639                                 res = ARCHIVE_FAILED;
2640                                 break;
2641                         }
2642                 }
2643                 /* be sure to always maintain this */
2644                 tail[0] = c;
2645                 if (tail[0] != '\0')
2646                         tail++; /* Advance to the next segment. */
2647         }
2648         /* Catches loop exits via break */
2649         tail[0] = c;
2650 #ifdef HAVE_FCHDIR
2651         /* If we changed directory above, restore it here. */
2652         if (restore_pwd >= 0) {
2653                 r = fchdir(restore_pwd);
2654                 if (r != 0) {
2655                         fsobj_error(a_eno, a_estr, errno,
2656                             "chdir() failure", "");
2657                 }
2658                 close(restore_pwd);
2659                 restore_pwd = -1;
2660                 if (r != 0) {
2661                         res = (ARCHIVE_FATAL);
2662                 }
2663         }
2664 #endif
2665         /* TODO: reintroduce a safe cache here? */
2666         return res;
2667 #endif
2668 }
2669
2670 /*
2671  * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise
2672  * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED}
2673  */
2674 static int
2675 check_symlinks(struct archive_write_disk *a)
2676 {
2677         struct archive_string error_string;
2678         int error_number;
2679         int rc;
2680         archive_string_init(&error_string);
2681         rc = check_symlinks_fsobj(a->name, &error_number, &error_string,
2682             a->flags);
2683         if (rc != ARCHIVE_OK) {
2684                 archive_set_error(&a->archive, error_number, "%s",
2685                     error_string.s);
2686         }
2687         archive_string_free(&error_string);
2688         a->pst = NULL;  /* to be safe */
2689         return rc;
2690 }
2691
2692
2693 #if defined(__CYGWIN__)
2694 /*
2695  * 1. Convert a path separator from '\' to '/' .
2696  *    We shouldn't check multibyte character directly because some
2697  *    character-set have been using the '\' character for a part of
2698  *    its multibyte character code.
2699  * 2. Replace unusable characters in Windows with underscore('_').
2700  * See also : http://msdn.microsoft.com/en-us/library/aa365247.aspx
2701  */
2702 static void
2703 cleanup_pathname_win(char *path)
2704 {
2705         wchar_t wc;
2706         char *p;
2707         size_t alen, l;
2708         int mb, complete, utf8;
2709
2710         alen = 0;
2711         mb = 0;
2712         complete = 1;
2713         utf8 = (strcmp(nl_langinfo(CODESET), "UTF-8") == 0)? 1: 0;
2714         for (p = path; *p != '\0'; p++) {
2715                 ++alen;
2716                 if (*p == '\\') {
2717                         /* If previous byte is smaller than 128,
2718                          * this is not second byte of multibyte characters,
2719                          * so we can replace '\' with '/'. */
2720                         if (utf8 || !mb)
2721                                 *p = '/';
2722                         else
2723                                 complete = 0;/* uncompleted. */
2724                 } else if (*(unsigned char *)p > 127)
2725                         mb = 1;
2726                 else
2727                         mb = 0;
2728                 /* Rewrite the path name if its next character is unusable. */
2729                 if (*p == ':' || *p == '*' || *p == '?' || *p == '"' ||
2730                     *p == '<' || *p == '>' || *p == '|')
2731                         *p = '_';
2732         }
2733         if (complete)
2734                 return;
2735
2736         /*
2737          * Convert path separator in wide-character.
2738          */
2739         p = path;
2740         while (*p != '\0' && alen) {
2741                 l = mbtowc(&wc, p, alen);
2742                 if (l == (size_t)-1) {
2743                         while (*p != '\0') {
2744                                 if (*p == '\\')
2745                                         *p = '/';
2746                                 ++p;
2747                         }
2748                         break;
2749                 }
2750                 if (l == 1 && wc == L'\\')
2751                         *p = '/';
2752                 p += l;
2753                 alen -= l;
2754         }
2755 }
2756 #endif
2757
2758 /*
2759  * Canonicalize the pathname.  In particular, this strips duplicate
2760  * '/' characters, '.' elements, and trailing '/'.  It also raises an
2761  * error for an empty path, a trailing '..', (if _SECURE_NODOTDOT is
2762  * set) any '..' in the path or (if ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS
2763  * is set) if the path is absolute.
2764  */
2765 static int
2766 cleanup_pathname_fsobj(char *path, int *a_eno, struct archive_string *a_estr,
2767     int flags)
2768 {
2769         char *dest, *src;
2770         char separator = '\0';
2771
2772         dest = src = path;
2773         if (*src == '\0') {
2774                 fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
2775                     "Invalid empty ", "pathname");
2776                 return (ARCHIVE_FAILED);
2777         }
2778
2779 #if defined(__CYGWIN__)
2780         cleanup_pathname_win(path);
2781 #endif
2782         /* Skip leading '/'. */
2783         if (*src == '/') {
2784                 if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) {
2785                         fsobj_error(a_eno, a_estr, ARCHIVE_ERRNO_MISC,
2786                             "Path is ", "absolute");
2787                         return (ARCHIVE_FAILED);
2788                 }
2789
2790                 separator = *src++;
2791         }
2792
2793         /* Scan the pathname one element at a time. */
2794         for (;;) {
2795                 /* src points to first char after '/' */
2796                 if (src[0] == '\0') {
2797                         break;
2798                 } else if (src[0] == '/') {
2799                         /* Found '//', ignore second one. */
2800                         src++;
2801                         continue;
2802                 } else if (src[0] == '.') {
2803                         if (src[1] == '\0') {
2804                                 /* Ignore trailing '.' */
2805                                 break;
2806                         } else if (src[1] == '/') {
2807                                 /* Skip './'. */
2808                                 src += 2;
2809                                 continue;
2810                         } else if (src[1] == '.') {
2811                                 if (src[2] == '/' || src[2] == '\0') {
2812                                         /* Conditionally warn about '..' */
2813                                         if (flags
2814                                             & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
2815                                                 fsobj_error(a_eno, a_estr,
2816                                                     ARCHIVE_ERRNO_MISC,
2817                                                     "Path contains ", "'..'");
2818                                                 return (ARCHIVE_FAILED);
2819                                         }
2820                                 }
2821                                 /*
2822                                  * Note: Under no circumstances do we
2823                                  * remove '..' elements.  In
2824                                  * particular, restoring
2825                                  * '/foo/../bar/' should create the
2826                                  * 'foo' dir as a side-effect.
2827                                  */
2828                         }
2829                 }
2830
2831                 /* Copy current element, including leading '/'. */
2832                 if (separator)
2833                         *dest++ = '/';
2834                 while (*src != '\0' && *src != '/') {
2835                         *dest++ = *src++;
2836                 }
2837
2838                 if (*src == '\0')
2839                         break;
2840
2841                 /* Skip '/' separator. */
2842                 separator = *src++;
2843         }
2844         /*
2845          * We've just copied zero or more path elements, not including the
2846          * final '/'.
2847          */
2848         if (dest == path) {
2849                 /*
2850                  * Nothing got copied.  The path must have been something
2851                  * like '.' or '/' or './' or '/././././/./'.
2852                  */
2853                 if (separator)
2854                         *dest++ = '/';
2855                 else
2856                         *dest++ = '.';
2857         }
2858         /* Terminate the result. */
2859         *dest = '\0';
2860         return (ARCHIVE_OK);
2861 }
2862
2863 static int
2864 cleanup_pathname(struct archive_write_disk *a)
2865 {
2866         struct archive_string error_string;
2867         int error_number;
2868         int rc;
2869         archive_string_init(&error_string);
2870         rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string,
2871             a->flags);
2872         if (rc != ARCHIVE_OK) {
2873                 archive_set_error(&a->archive, error_number, "%s",
2874                     error_string.s);
2875         }
2876         archive_string_free(&error_string);
2877         return rc;
2878 }
2879
2880 /*
2881  * Create the parent directory of the specified path, assuming path
2882  * is already in mutable storage.
2883  */
2884 static int
2885 create_parent_dir(struct archive_write_disk *a, char *path)
2886 {
2887         char *slash;
2888         int r;
2889
2890         /* Remove tail element to obtain parent name. */
2891         slash = strrchr(path, '/');
2892         if (slash == NULL)
2893                 return (ARCHIVE_OK);
2894         *slash = '\0';
2895         r = create_dir(a, path);
2896         *slash = '/';
2897         return (r);
2898 }
2899
2900 /*
2901  * Create the specified dir, recursing to create parents as necessary.
2902  *
2903  * Returns ARCHIVE_OK if the path exists when we're done here.
2904  * Otherwise, returns ARCHIVE_FAILED.
2905  * Assumes path is in mutable storage; path is unchanged on exit.
2906  */
2907 static int
2908 create_dir(struct archive_write_disk *a, char *path)
2909 {
2910         struct stat st;
2911         struct fixup_entry *le;
2912         char *slash, *base;
2913         mode_t mode_final, mode;
2914         int r;
2915
2916         /* Check for special names and just skip them. */
2917         slash = strrchr(path, '/');
2918         if (slash == NULL)
2919                 base = path;
2920         else
2921                 base = slash + 1;
2922
2923         if (base[0] == '\0' ||
2924             (base[0] == '.' && base[1] == '\0') ||
2925             (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
2926                 /* Don't bother trying to create null path, '.', or '..'. */
2927                 if (slash != NULL) {
2928                         *slash = '\0';
2929                         r = create_dir(a, path);
2930                         *slash = '/';
2931                         return (r);
2932                 }
2933                 return (ARCHIVE_OK);
2934         }
2935
2936         /*
2937          * Yes, this should be stat() and not lstat().  Using lstat()
2938          * here loses the ability to extract through symlinks.  Also note
2939          * that this should not use the a->st cache.
2940          */
2941         if (stat(path, &st) == 0) {
2942                 if (S_ISDIR(st.st_mode))
2943                         return (ARCHIVE_OK);
2944                 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
2945                         archive_set_error(&a->archive, EEXIST,
2946                             "Can't create directory '%s'", path);
2947                         return (ARCHIVE_FAILED);
2948                 }
2949                 if (unlink(path) != 0) {
2950                         archive_set_error(&a->archive, errno,
2951                             "Can't create directory '%s': "
2952                             "Conflicting file cannot be removed",
2953                             path);
2954                         return (ARCHIVE_FAILED);
2955                 }
2956         } else if (errno != ENOENT && errno != ENOTDIR) {
2957                 /* Stat failed? */
2958                 archive_set_error(&a->archive, errno,
2959                     "Can't test directory '%s'", path);
2960                 return (ARCHIVE_FAILED);
2961         } else if (slash != NULL) {
2962                 *slash = '\0';
2963                 r = create_dir(a, path);
2964                 *slash = '/';
2965                 if (r != ARCHIVE_OK)
2966                         return (r);
2967         }
2968
2969         /*
2970          * Mode we want for the final restored directory.  Per POSIX,
2971          * implicitly-created dirs must be created obeying the umask.
2972          * There's no mention whether this is different for privileged
2973          * restores (which the rest of this code handles by pretending
2974          * umask=0).  I've chosen here to always obey the user's umask for
2975          * implicit dirs, even if _EXTRACT_PERM was specified.
2976          */
2977         mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
2978         /* Mode we want on disk during the restore process. */
2979         mode = mode_final;
2980         mode |= MINIMUM_DIR_MODE;
2981         mode &= MAXIMUM_DIR_MODE;
2982         if (mkdir(path, mode) == 0) {
2983                 if (mode != mode_final) {
2984                         le = new_fixup(a, path);
2985                         if (le == NULL)
2986                                 return (ARCHIVE_FATAL);
2987                         le->fixup |=TODO_MODE_BASE;
2988                         le->mode = mode_final;
2989                 }
2990                 return (ARCHIVE_OK);
2991         }
2992
2993         /*
2994          * Without the following check, a/b/../b/c/d fails at the
2995          * second visit to 'b', so 'd' can't be created.  Note that we
2996          * don't add it to the fixup list here, as it's already been
2997          * added.
2998          */
2999         if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
3000                 return (ARCHIVE_OK);
3001
3002         archive_set_error(&a->archive, errno, "Failed to create dir '%s'",
3003             path);
3004         return (ARCHIVE_FAILED);
3005 }
3006
3007 /*
3008  * Note: Although we can skip setting the user id if the desired user
3009  * id matches the current user, we cannot skip setting the group, as
3010  * many systems set the gid based on the containing directory.  So
3011  * we have to perform a chown syscall if we want to set the SGID
3012  * bit.  (The alternative is to stat() and then possibly chown(); it's
3013  * more efficient to skip the stat() and just always chown().)  Note
3014  * that a successful chown() here clears the TODO_SGID_CHECK bit, which
3015  * allows set_mode to skip the stat() check for the GID.
3016  */
3017 static int
3018 set_ownership(struct archive_write_disk *a)
3019 {
3020 #ifndef __CYGWIN__
3021 /* unfortunately, on win32 there is no 'root' user with uid 0,
3022    so we just have to try the chown and see if it works */
3023
3024         /* If we know we can't change it, don't bother trying. */
3025         if (a->user_uid != 0  &&  a->user_uid != a->uid) {
3026                 archive_set_error(&a->archive, errno,
3027                     "Can't set UID=%jd", (intmax_t)a->uid);
3028                 return (ARCHIVE_WARN);
3029         }
3030 #endif
3031
3032 #ifdef HAVE_FCHOWN
3033         /* If we have an fd, we can avoid a race. */
3034         if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
3035                 /* We've set owner and know uid/gid are correct. */
3036                 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3037                 return (ARCHIVE_OK);
3038         }
3039 #endif
3040
3041         /* We prefer lchown() but will use chown() if that's all we have. */
3042         /* Of course, if we have neither, this will always fail. */
3043 #ifdef HAVE_LCHOWN
3044         if (lchown(a->name, a->uid, a->gid) == 0) {
3045                 /* We've set owner and know uid/gid are correct. */
3046                 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3047                 return (ARCHIVE_OK);
3048         }
3049 #elif HAVE_CHOWN
3050         if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
3051                 /* We've set owner and know uid/gid are correct. */
3052                 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
3053                 return (ARCHIVE_OK);
3054         }
3055 #endif
3056
3057         archive_set_error(&a->archive, errno,
3058             "Can't set user=%jd/group=%jd for %s",
3059             (intmax_t)a->uid, (intmax_t)a->gid, a->name);
3060         return (ARCHIVE_WARN);
3061 }
3062
3063 /*
3064  * Note: Returns 0 on success, non-zero on failure.
3065  */
3066 static int
3067 set_time(int fd, int mode, const char *name,
3068     time_t atime, long atime_nsec,
3069     time_t mtime, long mtime_nsec)
3070 {
3071         /* Select the best implementation for this platform. */
3072 #if defined(HAVE_UTIMENSAT) && defined(HAVE_FUTIMENS)
3073         /*
3074          * utimensat() and futimens() are defined in
3075          * POSIX.1-2008. They support ns resolution and setting times
3076          * on fds and symlinks.
3077          */
3078         struct timespec ts[2];
3079         (void)mode; /* UNUSED */
3080         ts[0].tv_sec = atime;
3081         ts[0].tv_nsec = atime_nsec;
3082         ts[1].tv_sec = mtime;
3083         ts[1].tv_nsec = mtime_nsec;
3084         if (fd >= 0)
3085                 return futimens(fd, ts);
3086         return utimensat(AT_FDCWD, name, ts, AT_SYMLINK_NOFOLLOW);
3087
3088 #elif HAVE_UTIMES
3089         /*
3090          * The utimes()-family functions support Âµs-resolution and
3091          * setting times fds and symlinks.  utimes() is documented as
3092          * LEGACY by POSIX, futimes() and lutimes() are not described
3093          * in POSIX.
3094          */
3095         struct timeval times[2];
3096
3097         times[0].tv_sec = atime;
3098         times[0].tv_usec = atime_nsec / 1000;
3099         times[1].tv_sec = mtime;
3100         times[1].tv_usec = mtime_nsec / 1000;
3101
3102 #ifdef HAVE_FUTIMES
3103         if (fd >= 0)
3104                 return (futimes(fd, times));
3105 #else
3106         (void)fd; /* UNUSED */
3107 #endif
3108 #ifdef HAVE_LUTIMES
3109         (void)mode; /* UNUSED */
3110         return (lutimes(name, times));
3111 #else
3112         if (S_ISLNK(mode))
3113                 return (0);
3114         return (utimes(name, times));
3115 #endif
3116
3117 #elif defined(HAVE_UTIME)
3118         /*
3119          * utime() is POSIX-standard but only supports 1s resolution and
3120          * does not support fds or symlinks.
3121          */
3122         struct utimbuf times;
3123         (void)fd; /* UNUSED */
3124         (void)name; /* UNUSED */
3125         (void)atime_nsec; /* UNUSED */
3126         (void)mtime_nsec; /* UNUSED */
3127         times.actime = atime;
3128         times.modtime = mtime;
3129         if (S_ISLNK(mode))
3130                 return (ARCHIVE_OK);
3131         return (utime(name, &times));
3132
3133 #else
3134         /*
3135          * We don't know how to set the time on this platform.
3136          */
3137         (void)fd; /* UNUSED */
3138         (void)mode; /* UNUSED */
3139         (void)name; /* UNUSED */
3140         (void)atime_nsec; /* UNUSED */
3141         (void)mtime_nsec; /* UNUSED */
3142         return (ARCHIVE_WARN);
3143 #endif
3144 }
3145
3146 #ifdef F_SETTIMES
3147 static int
3148 set_time_tru64(int fd, int mode, const char *name,
3149     time_t atime, long atime_nsec,
3150     time_t mtime, long mtime_nsec,
3151     time_t ctime, long ctime_nsec)
3152 {
3153         struct attr_timbuf tstamp;
3154         tstamp.atime.tv_sec = atime;
3155         tstamp.mtime.tv_sec = mtime;
3156         tstamp.ctime.tv_sec = ctime;
3157 #if defined (__hpux) && defined (__ia64)
3158         tstamp.atime.tv_nsec = atime_nsec;
3159         tstamp.mtime.tv_nsec = mtime_nsec;
3160         tstamp.ctime.tv_nsec = ctime_nsec;
3161 #else
3162         tstamp.atime.tv_usec = atime_nsec / 1000;
3163         tstamp.mtime.tv_usec = mtime_nsec / 1000;
3164         tstamp.ctime.tv_usec = ctime_nsec / 1000;
3165 #endif
3166         return (fcntl(fd,F_SETTIMES,&tstamp));
3167 }
3168 #endif /* F_SETTIMES */
3169
3170 static int
3171 set_times(struct archive_write_disk *a,
3172     int fd, int mode, const char *name,
3173     time_t atime, long atime_nanos,
3174     time_t birthtime, long birthtime_nanos,
3175     time_t mtime, long mtime_nanos,
3176     time_t cctime, long ctime_nanos)
3177 {
3178         /* Note: set_time doesn't use libarchive return conventions!
3179          * It uses syscall conventions.  So 0 here instead of ARCHIVE_OK. */
3180         int r1 = 0, r2 = 0;
3181
3182 #ifdef F_SETTIMES
3183          /*
3184          * on Tru64 try own fcntl first which can restore even the
3185          * ctime, fall back to default code path below if it fails
3186          * or if we are not running as root
3187          */
3188         if (a->user_uid == 0 &&
3189             set_time_tru64(fd, mode, name,
3190                            atime, atime_nanos, mtime,
3191                            mtime_nanos, cctime, ctime_nanos) == 0) {
3192                 return (ARCHIVE_OK);
3193         }
3194 #else /* Tru64 */
3195         (void)cctime; /* UNUSED */
3196         (void)ctime_nanos; /* UNUSED */
3197 #endif /* Tru64 */
3198
3199 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
3200         /*
3201          * If you have struct stat.st_birthtime, we assume BSD
3202          * birthtime semantics, in which {f,l,}utimes() updates
3203          * birthtime to earliest mtime.  So we set the time twice,
3204          * first using the birthtime, then using the mtime.  If
3205          * birthtime == mtime, this isn't necessary, so we skip it.
3206          * If birthtime > mtime, then this won't work, so we skip it.
3207          */
3208         if (birthtime < mtime
3209             || (birthtime == mtime && birthtime_nanos < mtime_nanos))
3210                 r1 = set_time(fd, mode, name,
3211                               atime, atime_nanos,
3212                               birthtime, birthtime_nanos);
3213 #else
3214         (void)birthtime; /* UNUSED */
3215         (void)birthtime_nanos; /* UNUSED */
3216 #endif
3217         r2 = set_time(fd, mode, name,
3218                       atime, atime_nanos,
3219                       mtime, mtime_nanos);
3220         if (r1 != 0 || r2 != 0) {
3221                 archive_set_error(&a->archive, errno,
3222                                   "Can't restore time");
3223                 return (ARCHIVE_WARN);
3224         }
3225         return (ARCHIVE_OK);
3226 }
3227
3228 static int
3229 set_times_from_entry(struct archive_write_disk *a)
3230 {
3231         time_t atime, birthtime, mtime, cctime;
3232         long atime_nsec, birthtime_nsec, mtime_nsec, ctime_nsec;
3233
3234         /* Suitable defaults. */
3235         atime = birthtime = mtime = cctime = a->start_time;
3236         atime_nsec = birthtime_nsec = mtime_nsec = ctime_nsec = 0;
3237
3238         /* If no time was provided, we're done. */
3239         if (!archive_entry_atime_is_set(a->entry)
3240 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
3241             && !archive_entry_birthtime_is_set(a->entry)
3242 #endif
3243             && !archive_entry_mtime_is_set(a->entry))
3244                 return (ARCHIVE_OK);
3245
3246         if (archive_entry_atime_is_set(a->entry)) {
3247                 atime = archive_entry_atime(a->entry);
3248                 atime_nsec = archive_entry_atime_nsec(a->entry);
3249         }
3250         if (archive_entry_birthtime_is_set(a->entry)) {
3251                 birthtime = archive_entry_birthtime(a->entry);
3252                 birthtime_nsec = archive_entry_birthtime_nsec(a->entry);
3253         }
3254         if (archive_entry_mtime_is_set(a->entry)) {
3255                 mtime = archive_entry_mtime(a->entry);
3256                 mtime_nsec = archive_entry_mtime_nsec(a->entry);
3257         }
3258         if (archive_entry_ctime_is_set(a->entry)) {
3259                 cctime = archive_entry_ctime(a->entry);
3260                 ctime_nsec = archive_entry_ctime_nsec(a->entry);
3261         }
3262
3263         return set_times(a, a->fd, a->mode, a->name,
3264                          atime, atime_nsec,
3265                          birthtime, birthtime_nsec,
3266                          mtime, mtime_nsec,
3267                          cctime, ctime_nsec);
3268 }
3269
3270 static int
3271 set_mode(struct archive_write_disk *a, int mode)
3272 {
3273         int r = ARCHIVE_OK;
3274         mode &= 07777; /* Strip off file type bits. */
3275
3276         if (a->todo & TODO_SGID_CHECK) {
3277                 /*
3278                  * If we don't know the GID is right, we must stat()
3279                  * to verify it.  We can't just check the GID of this
3280                  * process, since systems sometimes set GID from
3281                  * the enclosing dir or based on ACLs.
3282                  */
3283                 if ((r = lazy_stat(a)) != ARCHIVE_OK)
3284                         return (r);
3285                 if (a->pst->st_gid != a->gid) {
3286                         mode &= ~ S_ISGID;
3287                         if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3288                                 /*
3289                                  * This is only an error if you
3290                                  * requested owner restore.  If you
3291                                  * didn't, we'll try to restore
3292                                  * sgid/suid, but won't consider it a
3293                                  * problem if we can't.
3294                                  */
3295                                 archive_set_error(&a->archive, -1,
3296                                     "Can't restore SGID bit");
3297                                 r = ARCHIVE_WARN;
3298                         }
3299                 }
3300                 /* While we're here, double-check the UID. */
3301                 if (a->pst->st_uid != a->uid
3302                     && (a->todo & TODO_SUID)) {
3303                         mode &= ~ S_ISUID;
3304                         if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3305                                 archive_set_error(&a->archive, -1,
3306                                     "Can't restore SUID bit");
3307                                 r = ARCHIVE_WARN;
3308                         }
3309                 }
3310                 a->todo &= ~TODO_SGID_CHECK;
3311                 a->todo &= ~TODO_SUID_CHECK;
3312         } else if (a->todo & TODO_SUID_CHECK) {
3313                 /*
3314                  * If we don't know the UID is right, we can just check
3315                  * the user, since all systems set the file UID from
3316                  * the process UID.
3317                  */
3318                 if (a->user_uid != a->uid) {
3319                         mode &= ~ S_ISUID;
3320                         if (a->flags & ARCHIVE_EXTRACT_OWNER) {
3321                                 archive_set_error(&a->archive, -1,
3322                                     "Can't make file SUID");
3323                                 r = ARCHIVE_WARN;
3324                         }
3325                 }
3326                 a->todo &= ~TODO_SUID_CHECK;
3327         }
3328
3329         if (S_ISLNK(a->mode)) {
3330 #ifdef HAVE_LCHMOD
3331                 /*
3332                  * If this is a symlink, use lchmod().  If the
3333                  * platform doesn't support lchmod(), just skip it.  A
3334                  * platform that doesn't provide a way to set
3335                  * permissions on symlinks probably ignores
3336                  * permissions on symlinks, so a failure here has no
3337                  * impact.
3338                  */
3339                 if (lchmod(a->name, mode) != 0) {
3340                         switch (errno) {
3341                         case ENOTSUP:
3342                         case ENOSYS:
3343 #if ENOTSUP != EOPNOTSUPP
3344                         case EOPNOTSUPP:
3345 #endif
3346                                 /*
3347                                  * if lchmod is defined but the platform
3348                                  * doesn't support it, silently ignore
3349                                  * error
3350                                  */
3351                                 break;
3352                         default:
3353                                 archive_set_error(&a->archive, errno,
3354                                     "Can't set permissions to 0%o", (int)mode);
3355                                 r = ARCHIVE_WARN;
3356                         }
3357                 }
3358 #endif
3359         } else if (!S_ISDIR(a->mode)) {
3360                 /*
3361                  * If it's not a symlink and not a dir, then use
3362                  * fchmod() or chmod(), depending on whether we have
3363                  * an fd.  Dirs get their perms set during the
3364                  * post-extract fixup, which is handled elsewhere.
3365                  */
3366 #ifdef HAVE_FCHMOD
3367                 if (a->fd >= 0) {
3368                         if (fchmod(a->fd, mode) != 0) {
3369                                 archive_set_error(&a->archive, errno,
3370                                     "Can't set permissions to 0%o", (int)mode);
3371                                 r = ARCHIVE_WARN;
3372                         }
3373                 } else
3374 #endif
3375                         /* If this platform lacks fchmod(), then
3376                          * we'll just use chmod(). */
3377                         if (chmod(a->name, mode) != 0) {
3378                                 archive_set_error(&a->archive, errno,
3379                                     "Can't set permissions to 0%o", (int)mode);
3380                                 r = ARCHIVE_WARN;
3381                         }
3382         }
3383         return (r);
3384 }
3385
3386 static int
3387 set_fflags(struct archive_write_disk *a)
3388 {
3389         struct fixup_entry *le;
3390         unsigned long   set, clear;
3391         int             r;
3392         int             critical_flags;
3393         mode_t          mode = archive_entry_mode(a->entry);
3394
3395         /*
3396          * Make 'critical_flags' hold all file flags that can't be
3397          * immediately restored.  For example, on BSD systems,
3398          * SF_IMMUTABLE prevents hardlinks from being created, so
3399          * should not be set until after any hardlinks are created.  To
3400          * preserve some semblance of portability, this uses #ifdef
3401          * extensively.  Ugly, but it works.
3402          *
3403          * Yes, Virginia, this does create a security race.  It's mitigated
3404          * somewhat by the practice of creating dirs 0700 until the extract
3405          * is done, but it would be nice if we could do more than that.
3406          * People restoring critical file systems should be wary of
3407          * other programs that might try to muck with files as they're
3408          * being restored.
3409          */
3410         /* Hopefully, the compiler will optimize this mess into a constant. */
3411         critical_flags = 0;
3412 #ifdef SF_IMMUTABLE
3413         critical_flags |= SF_IMMUTABLE;
3414 #endif
3415 #ifdef UF_IMMUTABLE
3416         critical_flags |= UF_IMMUTABLE;
3417 #endif
3418 #ifdef SF_APPEND
3419         critical_flags |= SF_APPEND;
3420 #endif
3421 #ifdef UF_APPEND
3422         critical_flags |= UF_APPEND;
3423 #endif
3424 #ifdef EXT2_APPEND_FL
3425         critical_flags |= EXT2_APPEND_FL;
3426 #endif
3427 #ifdef EXT2_IMMUTABLE_FL
3428         critical_flags |= EXT2_IMMUTABLE_FL;
3429 #endif
3430
3431         if (a->todo & TODO_FFLAGS) {
3432                 archive_entry_fflags(a->entry, &set, &clear);
3433
3434                 /*
3435                  * The first test encourages the compiler to eliminate
3436                  * all of this if it's not necessary.
3437                  */
3438                 if ((critical_flags != 0)  &&  (set & critical_flags)) {
3439                         le = current_fixup(a, a->name);
3440                         if (le == NULL)
3441                                 return (ARCHIVE_FATAL);
3442                         le->fixup |= TODO_FFLAGS;
3443                         le->fflags_set = set;
3444                         /* Store the mode if it's not already there. */
3445                         if ((le->fixup & TODO_MODE) == 0)
3446                                 le->mode = mode;
3447                 } else {
3448                         r = set_fflags_platform(a, a->fd,
3449                             a->name, mode, set, clear);
3450                         if (r != ARCHIVE_OK)
3451                                 return (r);
3452                 }
3453         }
3454         return (ARCHIVE_OK);
3455 }
3456
3457 static int
3458 clear_nochange_fflags(struct archive_write_disk *a)
3459 {
3460         int             nochange_flags;
3461         mode_t          mode = archive_entry_mode(a->entry);
3462
3463         /* Hopefully, the compiler will optimize this mess into a constant. */
3464         nochange_flags = 0;
3465 #ifdef SF_IMMUTABLE
3466         nochange_flags |= SF_IMMUTABLE;
3467 #endif
3468 #ifdef UF_IMMUTABLE
3469         nochange_flags |= UF_IMMUTABLE;
3470 #endif
3471 #ifdef SF_APPEND
3472         nochange_flags |= SF_APPEND;
3473 #endif
3474 #ifdef UF_APPEND
3475         nochange_flags |= UF_APPEND;
3476 #endif
3477 #ifdef EXT2_APPEND_FL
3478         nochange_flags |= EXT2_APPEND_FL;
3479 #endif
3480 #ifdef EXT2_IMMUTABLE_FL
3481         nochange_flags |= EXT2_IMMUTABLE_FL;
3482 #endif
3483
3484         return (set_fflags_platform(a, a->fd, a->name, mode, 0,
3485             nochange_flags));
3486 }
3487
3488
3489 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
3490 /*
3491  * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
3492  */
3493 static int
3494 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3495     mode_t mode, unsigned long set, unsigned long clear)
3496 {
3497         int r;
3498
3499         (void)mode; /* UNUSED */
3500         if (set == 0  && clear == 0)
3501                 return (ARCHIVE_OK);
3502
3503         /*
3504          * XXX Is the stat here really necessary?  Or can I just use
3505          * the 'set' flags directly?  In particular, I'm not sure
3506          * about the correct approach if we're overwriting an existing
3507          * file that already has flags on it. XXX
3508          */
3509         if ((r = lazy_stat(a)) != ARCHIVE_OK)
3510                 return (r);
3511
3512         a->st.st_flags &= ~clear;
3513         a->st.st_flags |= set;
3514 #ifdef HAVE_FCHFLAGS
3515         /* If platform has fchflags() and we were given an fd, use it. */
3516         if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
3517                 return (ARCHIVE_OK);
3518 #endif
3519         /*
3520          * If we can't use the fd to set the flags, we'll use the
3521          * pathname to set flags.  We prefer lchflags() but will use
3522          * chflags() if we must.
3523          */
3524 #ifdef HAVE_LCHFLAGS
3525         if (lchflags(name, a->st.st_flags) == 0)
3526                 return (ARCHIVE_OK);
3527 #elif defined(HAVE_CHFLAGS)
3528         if (S_ISLNK(a->st.st_mode)) {
3529                 archive_set_error(&a->archive, errno,
3530                     "Can't set file flags on symlink.");
3531                 return (ARCHIVE_WARN);
3532         }
3533         if (chflags(name, a->st.st_flags) == 0)
3534                 return (ARCHIVE_OK);
3535 #endif
3536         archive_set_error(&a->archive, errno,
3537             "Failed to set file flags");
3538         return (ARCHIVE_WARN);
3539 }
3540
3541 #elif defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS) && defined(HAVE_WORKING_EXT2_IOC_GETFLAGS)
3542 /*
3543  * Linux uses ioctl() to read and write file flags.
3544  */
3545 static int
3546 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3547     mode_t mode, unsigned long set, unsigned long clear)
3548 {
3549         int              ret;
3550         int              myfd = fd;
3551         int newflags, oldflags;
3552         int sf_mask = 0;
3553
3554         if (set == 0  && clear == 0)
3555                 return (ARCHIVE_OK);
3556         /* Only regular files and dirs can have flags. */
3557         if (!S_ISREG(mode) && !S_ISDIR(mode))
3558                 return (ARCHIVE_OK);
3559
3560         /* If we weren't given an fd, open it ourselves. */
3561         if (myfd < 0) {
3562                 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY | O_CLOEXEC);
3563                 __archive_ensure_cloexec_flag(myfd);
3564         }
3565         if (myfd < 0)
3566                 return (ARCHIVE_OK);
3567
3568         /*
3569          * Linux has no define for the flags that are only settable by
3570          * the root user.  This code may seem a little complex, but
3571          * there seem to be some Linux systems that lack these
3572          * defines. (?)  The code below degrades reasonably gracefully
3573          * if sf_mask is incomplete.
3574          */
3575 #ifdef EXT2_IMMUTABLE_FL
3576         sf_mask |= EXT2_IMMUTABLE_FL;
3577 #endif
3578 #ifdef EXT2_APPEND_FL
3579         sf_mask |= EXT2_APPEND_FL;
3580 #endif
3581         /*
3582          * XXX As above, this would be way simpler if we didn't have
3583          * to read the current flags from disk. XXX
3584          */
3585         ret = ARCHIVE_OK;
3586
3587         /* Read the current file flags. */
3588         if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) < 0)
3589                 goto fail;
3590
3591         /* Try setting the flags as given. */
3592         newflags = (oldflags & ~clear) | set;
3593         if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
3594                 goto cleanup;
3595         if (errno != EPERM)
3596                 goto fail;
3597
3598         /* If we couldn't set all the flags, try again with a subset. */
3599         newflags &= ~sf_mask;
3600         oldflags &= sf_mask;
3601         newflags |= oldflags;
3602         if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
3603                 goto cleanup;
3604
3605         /* We couldn't set the flags, so report the failure. */
3606 fail:
3607         archive_set_error(&a->archive, errno,
3608             "Failed to set file flags");
3609         ret = ARCHIVE_WARN;
3610 cleanup:
3611         if (fd < 0)
3612                 close(myfd);
3613         return (ret);
3614 }
3615
3616 #else
3617
3618 /*
3619  * Of course, some systems have neither BSD chflags() nor Linux' flags
3620  * support through ioctl().
3621  */
3622 static int
3623 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
3624     mode_t mode, unsigned long set, unsigned long clear)
3625 {
3626         (void)a; /* UNUSED */
3627         (void)fd; /* UNUSED */
3628         (void)name; /* UNUSED */
3629         (void)mode; /* UNUSED */
3630         (void)set; /* UNUSED */
3631         (void)clear; /* UNUSED */
3632         return (ARCHIVE_OK);
3633 }
3634
3635 #endif /* __linux */
3636
3637 #ifndef HAVE_COPYFILE_H
3638 /* Default is to simply drop Mac extended metadata. */
3639 static int
3640 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
3641                  const void *metadata, size_t metadata_size)
3642 {
3643         (void)a; /* UNUSED */
3644         (void)pathname; /* UNUSED */
3645         (void)metadata; /* UNUSED */
3646         (void)metadata_size; /* UNUSED */
3647         return (ARCHIVE_OK);
3648 }
3649
3650 static int
3651 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
3652 {
3653         (void)a; /* UNUSED */
3654         (void)pathname; /* UNUSED */
3655         return (ARCHIVE_OK);
3656 }
3657 #else
3658
3659 /*
3660  * On Mac OS, we use copyfile() to unpack the metadata and
3661  * apply it to the target file.
3662  */
3663
3664 #if defined(HAVE_SYS_XATTR_H)
3665 static int
3666 copy_xattrs(struct archive_write_disk *a, int tmpfd, int dffd)
3667 {
3668         ssize_t xattr_size;
3669         char *xattr_names = NULL, *xattr_val = NULL;
3670         int ret = ARCHIVE_OK, xattr_i;
3671
3672         xattr_size = flistxattr(tmpfd, NULL, 0, 0);
3673         if (xattr_size == -1) {
3674                 archive_set_error(&a->archive, errno,
3675                     "Failed to read metadata(xattr)");
3676                 ret = ARCHIVE_WARN;
3677                 goto exit_xattr;
3678         }
3679         xattr_names = malloc(xattr_size);
3680         if (xattr_names == NULL) {
3681                 archive_set_error(&a->archive, ENOMEM,
3682                     "Can't allocate memory for metadata(xattr)");
3683                 ret = ARCHIVE_FATAL;
3684                 goto exit_xattr;
3685         }
3686         xattr_size = flistxattr(tmpfd, xattr_names, xattr_size, 0);
3687         if (xattr_size == -1) {
3688                 archive_set_error(&a->archive, errno,
3689                     "Failed to read metadata(xattr)");
3690                 ret = ARCHIVE_WARN;
3691                 goto exit_xattr;
3692         }
3693         for (xattr_i = 0; xattr_i < xattr_size;
3694             xattr_i += strlen(xattr_names + xattr_i) + 1) {
3695                 char *xattr_val_saved;
3696                 ssize_t s;
3697                 int f;
3698
3699                 s = fgetxattr(tmpfd, xattr_names + xattr_i, NULL, 0, 0, 0);
3700                 if (s == -1) {
3701                         archive_set_error(&a->archive, errno,
3702                             "Failed to get metadata(xattr)");
3703                         ret = ARCHIVE_WARN;
3704                         goto exit_xattr;
3705                 }
3706                 xattr_val_saved = xattr_val;
3707                 xattr_val = realloc(xattr_val, s);
3708                 if (xattr_val == NULL) {
3709                         archive_set_error(&a->archive, ENOMEM,
3710                             "Failed to get metadata(xattr)");
3711                         ret = ARCHIVE_WARN;
3712                         free(xattr_val_saved);
3713                         goto exit_xattr;
3714                 }
3715                 s = fgetxattr(tmpfd, xattr_names + xattr_i, xattr_val, s, 0, 0);
3716                 if (s == -1) {
3717                         archive_set_error(&a->archive, errno,
3718                             "Failed to get metadata(xattr)");
3719                         ret = ARCHIVE_WARN;
3720                         goto exit_xattr;
3721                 }
3722                 f = fsetxattr(dffd, xattr_names + xattr_i, xattr_val, s, 0, 0);
3723                 if (f == -1) {
3724                         archive_set_error(&a->archive, errno,
3725                             "Failed to get metadata(xattr)");
3726                         ret = ARCHIVE_WARN;
3727                         goto exit_xattr;
3728                 }
3729         }
3730 exit_xattr:
3731         free(xattr_names);
3732         free(xattr_val);
3733         return (ret);
3734 }
3735 #endif
3736
3737 static int
3738 copy_acls(struct archive_write_disk *a, int tmpfd, int dffd)
3739 {
3740 #ifndef HAVE_SYS_ACL_H
3741         return 0;
3742 #else
3743         acl_t acl, dfacl = NULL;
3744         int acl_r, ret = ARCHIVE_OK;
3745
3746         acl = acl_get_fd(tmpfd);
3747         if (acl == NULL) {
3748                 if (errno == ENOENT)
3749                         /* There are not any ACLs. */
3750                         return (ret);
3751                 archive_set_error(&a->archive, errno,
3752                     "Failed to get metadata(acl)");
3753                 ret = ARCHIVE_WARN;
3754                 goto exit_acl;
3755         }
3756         dfacl = acl_dup(acl);
3757         acl_r = acl_set_fd(dffd, dfacl);
3758         if (acl_r == -1) {
3759                 archive_set_error(&a->archive, errno,
3760                     "Failed to get metadata(acl)");
3761                 ret = ARCHIVE_WARN;
3762                 goto exit_acl;
3763         }
3764 exit_acl:
3765         if (acl)
3766                 acl_free(acl);
3767         if (dfacl)
3768                 acl_free(dfacl);
3769         return (ret);
3770 #endif
3771 }
3772
3773 static int
3774 create_tempdatafork(struct archive_write_disk *a, const char *pathname)
3775 {
3776         struct archive_string tmpdatafork;
3777         int tmpfd;
3778
3779         archive_string_init(&tmpdatafork);
3780         archive_strcpy(&tmpdatafork, "tar.md.XXXXXX");
3781         tmpfd = mkstemp(tmpdatafork.s);
3782         if (tmpfd < 0) {
3783                 archive_set_error(&a->archive, errno,
3784                     "Failed to mkstemp");
3785                 archive_string_free(&tmpdatafork);
3786                 return (-1);
3787         }
3788         if (copyfile(pathname, tmpdatafork.s, 0,
3789             COPYFILE_UNPACK | COPYFILE_NOFOLLOW
3790             | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
3791                 archive_set_error(&a->archive, errno,
3792                     "Failed to restore metadata");
3793                 close(tmpfd);
3794                 tmpfd = -1;
3795         }
3796         unlink(tmpdatafork.s);
3797         archive_string_free(&tmpdatafork);
3798         return (tmpfd);
3799 }
3800
3801 static int
3802 copy_metadata(struct archive_write_disk *a, const char *metadata,
3803     const char *datafork, int datafork_compressed)
3804 {
3805         int ret = ARCHIVE_OK;
3806
3807         if (datafork_compressed) {
3808                 int dffd, tmpfd;
3809
3810                 tmpfd = create_tempdatafork(a, metadata);
3811                 if (tmpfd == -1)
3812                         return (ARCHIVE_WARN);
3813
3814                 /*
3815                  * Do not open the data fork compressed by HFS+ compression
3816                  * with at least a writing mode(O_RDWR or O_WRONLY). it
3817                  * makes the data fork uncompressed.
3818                  */
3819                 dffd = open(datafork, 0);
3820                 if (dffd == -1) {
3821                         archive_set_error(&a->archive, errno,
3822                             "Failed to open the data fork for metadata");
3823                         close(tmpfd);
3824                         return (ARCHIVE_WARN);
3825                 }
3826
3827 #if defined(HAVE_SYS_XATTR_H)
3828                 ret = copy_xattrs(a, tmpfd, dffd);
3829                 if (ret == ARCHIVE_OK)
3830 #endif
3831                         ret = copy_acls(a, tmpfd, dffd);
3832                 close(tmpfd);
3833                 close(dffd);
3834         } else {
3835                 if (copyfile(metadata, datafork, 0,
3836                     COPYFILE_UNPACK | COPYFILE_NOFOLLOW
3837                     | COPYFILE_ACL | COPYFILE_XATTR) < 0) {
3838                         archive_set_error(&a->archive, errno,
3839                             "Failed to restore metadata");
3840                         ret = ARCHIVE_WARN;
3841                 }
3842         }
3843         return (ret);
3844 }
3845
3846 static int
3847 set_mac_metadata(struct archive_write_disk *a, const char *pathname,
3848                  const void *metadata, size_t metadata_size)
3849 {
3850         struct archive_string tmp;
3851         ssize_t written;
3852         int fd;
3853         int ret = ARCHIVE_OK;
3854
3855         /* This would be simpler if copyfile() could just accept the
3856          * metadata as a block of memory; then we could sidestep this
3857          * silly dance of writing the data to disk just so that
3858          * copyfile() can read it back in again. */
3859         archive_string_init(&tmp);
3860         archive_strcpy(&tmp, pathname);
3861         archive_strcat(&tmp, ".XXXXXX");
3862         fd = mkstemp(tmp.s);
3863
3864         if (fd < 0) {
3865                 archive_set_error(&a->archive, errno,
3866                                   "Failed to restore metadata");
3867                 archive_string_free(&tmp);
3868                 return (ARCHIVE_WARN);
3869         }
3870         written = write(fd, metadata, metadata_size);
3871         close(fd);
3872         if ((size_t)written != metadata_size) {
3873                 archive_set_error(&a->archive, errno,
3874                                   "Failed to restore metadata");
3875                 ret = ARCHIVE_WARN;
3876         } else {
3877                 int compressed;
3878
3879 #if defined(UF_COMPRESSED)
3880                 if ((a->todo & TODO_HFS_COMPRESSION) != 0 &&
3881                     (ret = lazy_stat(a)) == ARCHIVE_OK)
3882                         compressed = a->st.st_flags & UF_COMPRESSED;
3883                 else
3884 #endif
3885                         compressed = 0;
3886                 ret = copy_metadata(a, tmp.s, pathname, compressed);
3887         }
3888         unlink(tmp.s);
3889         archive_string_free(&tmp);
3890         return (ret);
3891 }
3892
3893 static int
3894 fixup_appledouble(struct archive_write_disk *a, const char *pathname)
3895 {
3896         char buff[8];
3897         struct stat st;
3898         const char *p;
3899         struct archive_string datafork;
3900         int fd = -1, ret = ARCHIVE_OK;
3901
3902         archive_string_init(&datafork);
3903         /* Check if the current file name is a type of the resource
3904          * fork file. */
3905         p = strrchr(pathname, '/');
3906         if (p == NULL)
3907                 p = pathname;
3908         else
3909                 p++;
3910         if (p[0] != '.' || p[1] != '_')
3911                 goto skip_appledouble;
3912
3913         /*
3914          * Check if the data fork file exists.
3915          *
3916          * TODO: Check if this write disk object has handled it.
3917          */
3918         archive_strncpy(&datafork, pathname, p - pathname);
3919         archive_strcat(&datafork, p + 2);
3920         if (lstat(datafork.s, &st) == -1 ||
3921             (st.st_mode & AE_IFMT) != AE_IFREG)
3922                 goto skip_appledouble;
3923
3924         /*
3925          * Check if the file is in the AppleDouble form.
3926          */
3927         fd = open(pathname, O_RDONLY | O_BINARY | O_CLOEXEC);
3928         __archive_ensure_cloexec_flag(fd);
3929         if (fd == -1) {
3930                 archive_set_error(&a->archive, errno,
3931                     "Failed to open a restoring file");
3932                 ret = ARCHIVE_WARN;
3933                 goto skip_appledouble;
3934         }
3935         if (read(fd, buff, 8) == -1) {
3936                 archive_set_error(&a->archive, errno,
3937                     "Failed to read a restoring file");
3938                 close(fd);
3939                 ret = ARCHIVE_WARN;
3940                 goto skip_appledouble;
3941         }
3942         close(fd);
3943         /* Check AppleDouble Magic Code. */
3944         if (archive_be32dec(buff) != 0x00051607)
3945                 goto skip_appledouble;
3946         /* Check AppleDouble Version. */
3947         if (archive_be32dec(buff+4) != 0x00020000)
3948                 goto skip_appledouble;
3949
3950         ret = copy_metadata(a, pathname, datafork.s,
3951 #if defined(UF_COMPRESSED)
3952             st.st_flags & UF_COMPRESSED);
3953 #else
3954             0);
3955 #endif
3956         if (ret == ARCHIVE_OK) {
3957                 unlink(pathname);
3958                 ret = ARCHIVE_EOF;
3959         }
3960 skip_appledouble:
3961         archive_string_free(&datafork);
3962         return (ret);
3963 }
3964 #endif
3965
3966 #if HAVE_LSETXATTR || HAVE_LSETEA
3967 /*
3968  * Restore extended attributes -  Linux and AIX implementations:
3969  * AIX' ea interface is syntaxwise identical to the Linux xattr interface.
3970  */
3971 static int
3972 set_xattrs(struct archive_write_disk *a)
3973 {
3974         struct archive_entry *entry = a->entry;
3975         static int warning_done = 0;
3976         int ret = ARCHIVE_OK;
3977         int i = archive_entry_xattr_reset(entry);
3978
3979         while (i--) {
3980                 const char *name;
3981                 const void *value;
3982                 size_t size;
3983                 archive_entry_xattr_next(entry, &name, &value, &size);
3984                 if (name != NULL &&
3985                                 strncmp(name, "xfsroot.", 8) != 0 &&
3986                                 strncmp(name, "system.", 7) != 0) {
3987                         int e;
3988 #if HAVE_FSETXATTR
3989                         if (a->fd >= 0)
3990                                 e = fsetxattr(a->fd, name, value, size, 0);
3991                         else
3992 #elif HAVE_FSETEA
3993                         if (a->fd >= 0)
3994                                 e = fsetea(a->fd, name, value, size, 0);
3995                         else
3996 #endif
3997                         {
3998 #if HAVE_LSETXATTR
3999                                 e = lsetxattr(archive_entry_pathname(entry),
4000                                     name, value, size, 0);
4001 #elif HAVE_LSETEA
4002                                 e = lsetea(archive_entry_pathname(entry),
4003                                     name, value, size, 0);
4004 #endif
4005                         }
4006                         if (e == -1) {
4007                                 if (errno == ENOTSUP || errno == ENOSYS) {
4008                                         if (!warning_done) {
4009                                                 warning_done = 1;
4010                                                 archive_set_error(&a->archive,
4011                                                     errno,
4012                                                     "Cannot restore extended "
4013                                                     "attributes on this file "
4014                                                     "system");
4015                                         }
4016                                 } else
4017                                         archive_set_error(&a->archive, errno,
4018                                             "Failed to set extended attribute");
4019                                 ret = ARCHIVE_WARN;
4020                         }
4021                 } else {
4022                         archive_set_error(&a->archive,
4023                             ARCHIVE_ERRNO_FILE_FORMAT,
4024                             "Invalid extended attribute encountered");
4025                         ret = ARCHIVE_WARN;
4026                 }
4027         }
4028         return (ret);
4029 }
4030 #elif HAVE_EXTATTR_SET_FILE && HAVE_DECL_EXTATTR_NAMESPACE_USER
4031 /*
4032  * Restore extended attributes -  FreeBSD implementation
4033  */
4034 static int
4035 set_xattrs(struct archive_write_disk *a)
4036 {
4037         struct archive_entry *entry = a->entry;
4038         static int warning_done = 0;
4039         int ret = ARCHIVE_OK;
4040         int i = archive_entry_xattr_reset(entry);
4041
4042         while (i--) {
4043                 const char *name;
4044                 const void *value;
4045                 size_t size;
4046                 archive_entry_xattr_next(entry, &name, &value, &size);
4047                 if (name != NULL) {
4048                         ssize_t e;
4049                         int namespace;
4050
4051                         if (strncmp(name, "user.", 5) == 0) {
4052                                 /* "user." attributes go to user namespace */
4053                                 name += 5;
4054                                 namespace = EXTATTR_NAMESPACE_USER;
4055                         } else {
4056                                 /* Warn about other extended attributes. */
4057                                 archive_set_error(&a->archive,
4058                                     ARCHIVE_ERRNO_FILE_FORMAT,
4059                                     "Can't restore extended attribute ``%s''",
4060                                     name);
4061                                 ret = ARCHIVE_WARN;
4062                                 continue;
4063                         }
4064                         errno = 0;
4065 #if HAVE_EXTATTR_SET_FD
4066                         if (a->fd >= 0)
4067                                 e = extattr_set_fd(a->fd, namespace, name,
4068                                     value, size);
4069                         else
4070 #endif
4071                         /* TODO: should we use extattr_set_link() instead? */
4072                         {
4073                                 e = extattr_set_file(
4074                                     archive_entry_pathname(entry), namespace,
4075                                     name, value, size);
4076                         }
4077                         if (e != (ssize_t)size) {
4078                                 if (errno == ENOTSUP || errno == ENOSYS) {
4079                                         if (!warning_done) {
4080                                                 warning_done = 1;
4081                                                 archive_set_error(&a->archive,
4082                                                     errno,
4083                                                     "Cannot restore extended "
4084                                                     "attributes on this file "
4085                                                     "system");
4086                                         }
4087                                 } else {
4088                                         archive_set_error(&a->archive, errno,
4089                                             "Failed to set extended attribute");
4090                                 }
4091
4092                                 ret = ARCHIVE_WARN;
4093                         }
4094                 }
4095         }
4096         return (ret);
4097 }
4098 #else
4099 /*
4100  * Restore extended attributes - stub implementation for unsupported systems
4101  */
4102 static int
4103 set_xattrs(struct archive_write_disk *a)
4104 {
4105         static int warning_done = 0;
4106
4107         /* If there aren't any extended attributes, then it's okay not
4108          * to extract them, otherwise, issue a single warning. */
4109         if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
4110                 warning_done = 1;
4111                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4112                     "Cannot restore extended attributes on this system");
4113                 return (ARCHIVE_WARN);
4114         }
4115         /* Warning was already emitted; suppress further warnings. */
4116         return (ARCHIVE_OK);
4117 }
4118 #endif
4119
4120 /*
4121  * Test if file on disk is older than entry.
4122  */
4123 static int
4124 older(struct stat *st, struct archive_entry *entry)
4125 {
4126         /* First, test the seconds and return if we have a definite answer. */
4127         /* Definitely older. */
4128         if (st->st_mtime < archive_entry_mtime(entry))
4129                 return (1);
4130         /* Definitely younger. */
4131         if (st->st_mtime > archive_entry_mtime(entry))
4132                 return (0);
4133         /* If this platform supports fractional seconds, try those. */
4134 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
4135         /* Definitely older. */
4136         if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
4137                 return (1);
4138 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
4139         /* Definitely older. */
4140         if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
4141                 return (1);
4142 #elif HAVE_STRUCT_STAT_ST_MTIME_N
4143         /* older. */
4144         if (st->st_mtime_n < archive_entry_mtime_nsec(entry))
4145                 return (1);
4146 #elif HAVE_STRUCT_STAT_ST_UMTIME
4147         /* older. */
4148         if (st->st_umtime * 1000 < archive_entry_mtime_nsec(entry))
4149                 return (1);
4150 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
4151         /* older. */
4152         if (st->st_mtime_usec * 1000 < archive_entry_mtime_nsec(entry))
4153                 return (1);
4154 #else
4155         /* This system doesn't have high-res timestamps. */
4156 #endif
4157         /* Same age or newer, so not older. */
4158         return (0);
4159 }
4160
4161 #endif /* !_WIN32 || __CYGWIN__ */
4162