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