]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libarchive/archive_write_disk.c
Merge-from-Googlecode r419
[FreeBSD/FreeBSD.git] / lib / libarchive / archive_write_disk.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "archive_platform.h"
28 __FBSDID("$FreeBSD$");
29
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33 #ifdef HAVE_SYS_ACL_H
34 #include <sys/acl.h>
35 #endif
36 #ifdef HAVE_ATTR_XATTR_H
37 #include <attr/xattr.h>
38 #endif
39 #ifdef HAVE_SYS_IOCTL_H
40 #include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_SYS_STAT_H
43 #include <sys/stat.h>
44 #endif
45 #ifdef HAVE_SYS_TIME_H
46 #include <sys/time.h>
47 #endif
48 #ifdef HAVE_SYS_UTIME_H
49 #include <sys/utime.h>
50 #endif
51
52 #ifdef HAVE_EXT2FS_EXT2_FS_H
53 #include <ext2fs/ext2_fs.h>     /* for Linux file flags */
54 #endif
55 #ifdef HAVE_ERRNO_H
56 #include <errno.h>
57 #endif
58 #ifdef HAVE_FCNTL_H
59 #include <fcntl.h>
60 #endif
61 #ifdef HAVE_GRP_H
62 #include <grp.h>
63 #endif
64 #ifdef HAVE_LINUX_FS_H
65 #include <linux/fs.h>   /* for Linux file flags */
66 #endif
67 #ifdef HAVE_LIMITS_H
68 #include <limits.h>
69 #endif
70 #ifdef HAVE_PWD_H
71 #include <pwd.h>
72 #endif
73 #include <stdio.h>
74 #ifdef HAVE_STDLIB_H
75 #include <stdlib.h>
76 #endif
77 #ifdef HAVE_STRING_H
78 #include <string.h>
79 #endif
80 #ifdef HAVE_UNISTD_H
81 #include <unistd.h>
82 #endif
83 #ifdef HAVE_UTIME_H
84 #include <utime.h>
85 #endif
86
87 #include "archive.h"
88 #include "archive_string.h"
89 #include "archive_entry.h"
90 #include "archive_private.h"
91
92 #ifndef O_BINARY
93 #define O_BINARY 0
94 #endif
95
96 struct fixup_entry {
97         struct fixup_entry      *next;
98         mode_t                   mode;
99         int64_t                  atime;
100         int64_t                  birthtime;
101         int64_t                  mtime;
102         unsigned long            atime_nanos;
103         unsigned long            birthtime_nanos;
104         unsigned long            mtime_nanos;
105         unsigned long            fflags_set;
106         int                      fixup; /* bitmask of what needs fixing */
107         char                    *name;
108 };
109
110 /*
111  * We use a bitmask to track which operations remain to be done for
112  * this file.  In particular, this helps us avoid unnecessary
113  * operations when it's possible to take care of one step as a
114  * side-effect of another.  For example, mkdir() can specify the mode
115  * for the newly-created object but symlink() cannot.  This means we
116  * can skip chmod() if mkdir() succeeded, but we must explicitly
117  * chmod() if we're trying to create a directory that already exists
118  * (mkdir() failed) or if we're restoring a symlink.  Similarly, we
119  * need to verify UID/GID before trying to restore SUID/SGID bits;
120  * that verification can occur explicitly through a stat() call or
121  * implicitly because of a successful chown() call.
122  */
123 #define TODO_MODE_FORCE         0x40000000
124 #define TODO_MODE_BASE          0x20000000
125 #define TODO_SUID               0x10000000
126 #define TODO_SUID_CHECK         0x08000000
127 #define TODO_SGID               0x04000000
128 #define TODO_SGID_CHECK         0x02000000
129 #define TODO_MODE               (TODO_MODE_BASE|TODO_SUID|TODO_SGID)
130 #define TODO_TIMES              ARCHIVE_EXTRACT_TIME
131 #define TODO_OWNER              ARCHIVE_EXTRACT_OWNER
132 #define TODO_FFLAGS             ARCHIVE_EXTRACT_FFLAGS
133 #define TODO_ACLS               ARCHIVE_EXTRACT_ACL
134 #define TODO_XATTR              ARCHIVE_EXTRACT_XATTR
135
136 struct archive_write_disk {
137         struct archive  archive;
138
139         mode_t                   user_umask;
140         struct fixup_entry      *fixup_list;
141         struct fixup_entry      *current_fixup;
142         uid_t                    user_uid;
143         dev_t                    skip_file_dev;
144         ino_t                    skip_file_ino;
145         time_t                   start_time;
146
147         gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid);
148         void  (*cleanup_gid)(void *private);
149         void                    *lookup_gid_data;
150         uid_t (*lookup_uid)(void *private, const char *gname, gid_t gid);
151         void  (*cleanup_uid)(void *private);
152         void                    *lookup_uid_data;
153
154         /*
155          * Full path of last file to satisfy symlink checks.
156          */
157         struct archive_string   path_safe;
158
159         /*
160          * Cached stat data from disk for the current entry.
161          * If this is valid, pst points to st.  Otherwise,
162          * pst is null.
163          */
164         struct stat              st;
165         struct stat             *pst;
166
167         /* Information about the object being restored right now. */
168         struct archive_entry    *entry; /* Entry being extracted. */
169         char                    *name; /* Name of entry, possibly edited. */
170         struct archive_string    _name_data; /* backing store for 'name' */
171         /* Tasks remaining for this object. */
172         int                      todo;
173         /* Tasks deferred until end-of-archive. */
174         int                      deferred;
175         /* Options requested by the client. */
176         int                      flags;
177         /* Handle for the file we're restoring. */
178         int                      fd;
179         /* Current offset for writing data to the file. */
180         off_t                    offset;
181         /* Maximum size of file, -1 if unknown. */
182         off_t                    filesize;
183         /* Dir we were in before this restore; only for deep paths. */
184         int                      restore_pwd;
185         /* Mode we should use for this entry; affected by _PERM and umask. */
186         mode_t                   mode;
187         /* UID/GID to use in restoring this entry. */
188         uid_t                    uid;
189         gid_t                    gid;
190         /* Last offset written to disk. */
191         off_t                    last_offset;
192 };
193
194 /*
195  * Default mode for dirs created automatically (will be modified by umask).
196  * Note that POSIX specifies 0777 for implicity-created dirs, "modified
197  * by the process' file creation mask."
198  */
199 #define DEFAULT_DIR_MODE 0777
200 /*
201  * Dir modes are restored in two steps:  During the extraction, the permissions
202  * in the archive are modified to match the following limits.  During
203  * the post-extract fixup pass, the permissions from the archive are
204  * applied.
205  */
206 #define MINIMUM_DIR_MODE 0700
207 #define MAXIMUM_DIR_MODE 0775
208
209 static int      check_symlinks(struct archive_write_disk *);
210 static int      create_filesystem_object(struct archive_write_disk *);
211 static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname);
212 #ifdef HAVE_FCHDIR
213 static void     edit_deep_directories(struct archive_write_disk *ad);
214 #endif
215 static int      cleanup_pathname(struct archive_write_disk *);
216 static int      create_dir(struct archive_write_disk *, char *);
217 static int      create_parent_dir(struct archive_write_disk *, char *);
218 static int      older(struct stat *, struct archive_entry *);
219 static int      restore_entry(struct archive_write_disk *);
220 #ifdef HAVE_POSIX_ACL
221 static int      set_acl(struct archive_write_disk *, int fd, struct archive_entry *,
222                     acl_type_t, int archive_entry_acl_type, const char *tn);
223 #endif
224 static int      set_acls(struct archive_write_disk *);
225 static int      set_xattrs(struct archive_write_disk *);
226 static int      set_fflags(struct archive_write_disk *);
227 static int      set_fflags_platform(struct archive_write_disk *, int fd,
228                     const char *name, mode_t mode,
229                     unsigned long fflags_set, unsigned long fflags_clear);
230 static int      set_ownership(struct archive_write_disk *);
231 static int      set_mode(struct archive_write_disk *, int mode);
232 static int      set_time(int, int, const char *, time_t, long, time_t, long);
233 static int      set_times(struct archive_write_disk *);
234 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
235 static gid_t    trivial_lookup_gid(void *, const char *, gid_t);
236 static uid_t    trivial_lookup_uid(void *, const char *, uid_t);
237 static ssize_t  write_data_block(struct archive_write_disk *,
238                     const char *, size_t, off_t);
239
240 static struct archive_vtable *archive_write_disk_vtable(void);
241
242 static int      _archive_write_close(struct archive *);
243 static int      _archive_write_finish(struct archive *);
244 static int      _archive_write_header(struct archive *, struct archive_entry *);
245 static int      _archive_write_finish_entry(struct archive *);
246 static ssize_t  _archive_write_data(struct archive *, const void *, size_t);
247 static ssize_t  _archive_write_data_block(struct archive *, const void *, size_t, off_t);
248
249 static int
250 _archive_write_disk_lazy_stat(struct archive_write_disk *a)
251 {
252         if (a->pst != NULL) {
253                 /* Already have stat() data available. */
254                 return (ARCHIVE_OK);
255         }
256 #ifdef HAVE_FSTAT
257         if (a->fd >= 0 && fstat(a->fd, &a->st) == 0) {
258                 a->pst = &a->st;
259                 return (ARCHIVE_OK);
260         }
261 #endif
262         /*
263          * XXX At this point, symlinks should not be hit, otherwise
264          * XXX a race occured.  Do we want to check explicitly for that?
265          */
266         if (lstat(a->name, &a->st) == 0) {
267                 a->pst = &a->st;
268                 return (ARCHIVE_OK);
269         }
270         archive_set_error(&a->archive, errno, "Couldn't stat file");
271         return (ARCHIVE_WARN);
272 }
273
274 static struct archive_vtable *
275 archive_write_disk_vtable(void)
276 {
277         static struct archive_vtable av;
278         static int inited = 0;
279
280         if (!inited) {
281                 av.archive_write_close = _archive_write_close;
282                 av.archive_write_finish = _archive_write_finish;
283                 av.archive_write_header = _archive_write_header;
284                 av.archive_write_finish_entry = _archive_write_finish_entry;
285                 av.archive_write_data = _archive_write_data;
286                 av.archive_write_data_block = _archive_write_data_block;
287         }
288         return (&av);
289 }
290
291
292 int
293 archive_write_disk_set_options(struct archive *_a, int flags)
294 {
295         struct archive_write_disk *a = (struct archive_write_disk *)_a;
296
297         a->flags = flags;
298         return (ARCHIVE_OK);
299 }
300
301
302 /*
303  * Extract this entry to disk.
304  *
305  * TODO: Validate hardlinks.  According to the standards, we're
306  * supposed to check each extracted hardlink and squawk if it refers
307  * to a file that we didn't restore.  I'm not entirely convinced this
308  * is a good idea, but more importantly: Is there any way to validate
309  * hardlinks without keeping a complete list of filenames from the
310  * entire archive?? Ugh.
311  *
312  */
313 static int
314 _archive_write_header(struct archive *_a, struct archive_entry *entry)
315 {
316         struct archive_write_disk *a = (struct archive_write_disk *)_a;
317         struct fixup_entry *fe;
318         int ret, r;
319
320         __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
321             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
322             "archive_write_disk_header");
323         archive_clear_error(&a->archive);
324         if (a->archive.state & ARCHIVE_STATE_DATA) {
325                 r = _archive_write_finish_entry(&a->archive);
326                 if (r == ARCHIVE_FATAL)
327                         return (r);
328         }
329
330         /* Set up for this particular entry. */
331         a->pst = NULL;
332         a->current_fixup = NULL;
333         a->deferred = 0;
334         if (a->entry) {
335                 archive_entry_free(a->entry);
336                 a->entry = NULL;
337         }
338         a->entry = archive_entry_clone(entry);
339         a->fd = -1;
340         a->last_offset = 0;
341         a->offset = 0;
342         a->uid = a->user_uid;
343         a->mode = archive_entry_mode(a->entry);
344         if (archive_entry_size_is_set(a->entry))
345                 a->filesize = archive_entry_size(a->entry);
346         else
347                 a->filesize = -1;
348         archive_strcpy(&(a->_name_data), archive_entry_pathname(a->entry));
349         a->name = a->_name_data.s;
350         archive_clear_error(&a->archive);
351
352         /*
353          * Clean up the requested path.  This is necessary for correct
354          * dir restores; the dir restore logic otherwise gets messed
355          * up by nonsense like "dir/.".
356          */
357         ret = cleanup_pathname(a);
358         if (ret != ARCHIVE_OK)
359                 return (ret);
360
361         /*
362          * Set the umask to zero so we get predictable mode settings.
363          * This gets done on every call to _write_header in case the
364          * user edits their umask during the extraction for some
365          * reason. This will be reset before we return.  Note that we
366          * don't need to do this in _finish_entry, as the chmod(), etc,
367          * system calls don't obey umask.
368          */
369         a->user_umask = umask(0);
370         /* From here on, early exit requires "goto done" to clean up. */
371
372         /* Figure out what we need to do for this entry. */
373         a->todo = TODO_MODE_BASE;
374         if (a->flags & ARCHIVE_EXTRACT_PERM) {
375                 a->todo |= TODO_MODE_FORCE; /* Be pushy about permissions. */
376                 /*
377                  * SGID requires an extra "check" step because we
378                  * cannot easily predict the GID that the system will
379                  * assign.  (Different systems assign GIDs to files
380                  * based on a variety of criteria, including process
381                  * credentials and the gid of the enclosing
382                  * directory.)  We can only restore the SGID bit if
383                  * the file has the right GID, and we only know the
384                  * GID if we either set it (see set_ownership) or if
385                  * we've actually called stat() on the file after it
386                  * was restored.  Since there are several places at
387                  * which we might verify the GID, we need a TODO bit
388                  * to keep track.
389                  */
390                 if (a->mode & S_ISGID)
391                         a->todo |= TODO_SGID | TODO_SGID_CHECK;
392                 /*
393                  * Verifying the SUID is simpler, but can still be
394                  * done in multiple ways, hence the separate "check" bit.
395                  */
396                 if (a->mode & S_ISUID)
397                         a->todo |= TODO_SUID | TODO_SUID_CHECK;
398         } else {
399                 /*
400                  * User didn't request full permissions, so don't
401                  * restore SUID, SGID bits and obey umask.
402                  */
403                 a->mode &= ~S_ISUID;
404                 a->mode &= ~S_ISGID;
405                 a->mode &= ~S_ISVTX;
406                 a->mode &= ~a->user_umask;
407         }
408         if (a->flags & ARCHIVE_EXTRACT_OWNER)
409                 a->todo |= TODO_OWNER;
410         if (a->flags & ARCHIVE_EXTRACT_TIME)
411                 a->todo |= TODO_TIMES;
412         if (a->flags & ARCHIVE_EXTRACT_ACL)
413                 a->todo |= TODO_ACLS;
414         if (a->flags & ARCHIVE_EXTRACT_FFLAGS)
415                 a->todo |= TODO_FFLAGS;
416         if (a->flags & ARCHIVE_EXTRACT_SECURE_SYMLINKS) {
417                 ret = check_symlinks(a);
418                 if (ret != ARCHIVE_OK)
419                         goto done;
420         }
421 #ifdef HAVE_FCHDIR
422         /* If path exceeds PATH_MAX, shorten the path. */
423         edit_deep_directories(a);
424 #endif
425
426         ret = restore_entry(a);
427
428 #ifdef HAVE_FCHDIR
429         /* If we changed directory above, restore it here. */
430         if (a->restore_pwd >= 0) {
431                 fchdir(a->restore_pwd);
432                 close(a->restore_pwd);
433                 a->restore_pwd = -1;
434         }
435 #endif
436
437         /*
438          * Fixup uses the unedited pathname from archive_entry_pathname(),
439          * because it is relative to the base dir and the edited path
440          * might be relative to some intermediate dir as a result of the
441          * deep restore logic.
442          */
443         if (a->deferred & TODO_MODE) {
444                 fe = current_fixup(a, archive_entry_pathname(entry));
445                 fe->fixup |= TODO_MODE_BASE;
446                 fe->mode = a->mode;
447         }
448
449         if ((a->deferred & TODO_TIMES)
450                 && (archive_entry_mtime_is_set(entry)
451                     || archive_entry_atime_is_set(entry))) {
452                 fe = current_fixup(a, archive_entry_pathname(entry));
453                 fe->fixup |= TODO_TIMES;
454                 if (archive_entry_atime_is_set(entry)) {
455                         fe->atime = archive_entry_atime(entry);
456                         fe->atime_nanos = archive_entry_atime_nsec(entry);
457                 } else {
458                         /* If atime is unset, use start time. */
459                         fe->atime = a->start_time;
460                         fe->atime_nanos = 0;
461                 }
462                 if (archive_entry_mtime_is_set(entry)) {
463                         fe->mtime = archive_entry_mtime(entry);
464                         fe->mtime_nanos = archive_entry_mtime_nsec(entry);
465                 } else {
466                         /* If mtime is unset, use start time. */
467                         fe->mtime = a->start_time;
468                         fe->mtime_nanos = 0;
469                 }
470                 if (archive_entry_birthtime_is_set(entry)) {
471                         fe->birthtime = archive_entry_birthtime(entry);
472                         fe->birthtime_nanos = archive_entry_birthtime_nsec(entry);
473                 } else {
474                         /* If birthtime is unset, use mtime. */
475                         fe->birthtime = fe->mtime;
476                         fe->birthtime_nanos = fe->mtime_nanos;
477                 }
478         }
479
480         if (a->deferred & TODO_FFLAGS) {
481                 fe = current_fixup(a, archive_entry_pathname(entry));
482                 fe->fixup |= TODO_FFLAGS;
483                 /* TODO: Complete this.. defer fflags from below. */
484         }
485
486         /* We've created the object and are ready to pour data into it. */
487         if (ret >= ARCHIVE_WARN)
488                 a->archive.state = ARCHIVE_STATE_DATA;
489         /*
490          * If it's not open, tell our client not to try writing.
491          * In particular, dirs, links, etc, don't get written to.
492          */
493         if (a->fd < 0) {
494                 archive_entry_set_size(entry, 0);
495                 a->filesize = 0;
496         }
497 done:
498         /* Restore the user's umask before returning. */
499         umask(a->user_umask);
500
501         return (ret);
502 }
503
504 int
505 archive_write_disk_set_skip_file(struct archive *_a, dev_t d, ino_t i)
506 {
507         struct archive_write_disk *a = (struct archive_write_disk *)_a;
508         __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
509             ARCHIVE_STATE_ANY, "archive_write_disk_set_skip_file");
510         a->skip_file_dev = d;
511         a->skip_file_ino = i;
512         return (ARCHIVE_OK);
513 }
514
515 static ssize_t
516 write_data_block(struct archive_write_disk *a,
517     const char *buff, size_t size, off_t offset)
518 {
519         ssize_t bytes_written = 0;
520         ssize_t block_size = 0, bytes_to_write;
521
522         if (a->filesize == 0 || a->fd < 0) {
523                 archive_set_error(&a->archive, 0,
524                     "Attempt to write to an empty file");
525                 return (ARCHIVE_WARN);
526         }
527
528         if (a->flags & ARCHIVE_EXTRACT_SPARSE) {
529 #if HAVE_STRUCT_STAT_ST_BLKSIZE
530                 int r;
531                 if ((r = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
532                         return (r);
533                 block_size = a->pst->st_blksize;
534 #else
535                 /* XXX TODO XXX Is there a more appropriate choice here ? */
536                 /* This needn't match the filesystem allocation size. */
537                 block_size = 16*1024;
538 #endif
539         }
540
541         if (a->filesize >= 0 && (off_t)(offset + size) > a->filesize)
542                 size = (size_t)(a->filesize - offset);
543
544         /* Write the data. */
545         while (size > 0) {
546                 if (block_size == 0) {
547                         bytes_to_write = size;
548                 } else {
549                         /* We're sparsifying the file. */
550                         const char *p, *end;
551                         off_t block_end;
552
553                         /* Skip leading zero bytes. */
554                         for (p = buff, end = buff + size; p < end; ++p) {
555                                 if (*p != '\0')
556                                         break;
557                         }
558                         offset += p - buff;
559                         size -= p - buff;
560                         buff = p;
561                         if (size == 0)
562                                 break;
563
564                         /* Calculate next block boundary after offset. */
565                         block_end
566                             = (offset / block_size) * block_size + block_size;
567
568                         /* If the adjusted write would cross block boundary,
569                          * truncate it to the block boundary. */
570                         bytes_to_write = size;
571                         if (offset + bytes_to_write > block_end)
572                                 bytes_to_write = block_end - offset;
573                 }
574
575                 /* Seek if necessary to the specified offset. */
576                 if (offset != a->last_offset) {
577                         if (lseek(a->fd, offset, SEEK_SET) < 0) {
578                                 archive_set_error(&a->archive, errno,
579                                     "Seek failed");
580                                 return (ARCHIVE_FATAL);
581                         }
582                 }
583                 bytes_written = write(a->fd, buff, bytes_to_write);
584                 if (bytes_written < 0) {
585                         archive_set_error(&a->archive, errno, "Write failed");
586                         return (ARCHIVE_WARN);
587                 }
588                 buff += bytes_written;
589                 size -= bytes_written;
590                 offset += bytes_written;
591                 a->archive.file_position += bytes_written;
592                 a->archive.raw_position += bytes_written;
593                 a->last_offset = a->offset = offset;
594         }
595         return (bytes_written);
596 }
597
598 static ssize_t
599 _archive_write_data_block(struct archive *_a,
600     const void *buff, size_t size, off_t offset)
601 {
602         struct archive_write_disk *a = (struct archive_write_disk *)_a;
603         ssize_t r;
604
605         __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
606             ARCHIVE_STATE_DATA, "archive_write_disk_block");
607
608         r = write_data_block(a, buff, size, offset);
609
610         if (r < 0)
611                 return (r);
612         if ((size_t)r < size) {
613                 archive_set_error(&a->archive, 0,
614                     "Write request too large");
615                 return (ARCHIVE_WARN);
616         }
617         return (ARCHIVE_OK);
618 }
619
620 static ssize_t
621 _archive_write_data(struct archive *_a, const void *buff, size_t size)
622 {
623         struct archive_write_disk *a = (struct archive_write_disk *)_a;
624
625         __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
626             ARCHIVE_STATE_DATA, "archive_write_data");
627
628         return (write_data_block(a, buff, size, a->offset));
629 }
630
631 static int
632 _archive_write_finish_entry(struct archive *_a)
633 {
634         struct archive_write_disk *a = (struct archive_write_disk *)_a;
635         int ret = ARCHIVE_OK;
636
637         __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
638             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
639             "archive_write_finish_entry");
640         if (a->archive.state & ARCHIVE_STATE_HEADER)
641                 return (ARCHIVE_OK);
642         archive_clear_error(&a->archive);
643
644         /* Pad or truncate file to the right size. */
645         if (a->fd < 0) {
646                 /* There's no file. */
647         } else if (a->filesize < 0) {
648                 /* File size is unknown, so we can't set the size. */
649         } else if (a->last_offset == a->filesize) {
650                 /* Last write ended at exactly the filesize; we're done. */
651                 /* Hopefully, this is the common case. */
652         } else {
653 #if HAVE_FTRUNCATE
654                 if (ftruncate(a->fd, a->filesize) == -1 &&
655                     a->filesize == 0) {
656                         archive_set_error(&a->archive, errno,
657                             "File size could not be restored");
658                         return (ARCHIVE_FAILED);
659                 }
660 #endif
661                 /*
662                  * Explicitly stat the file as some platforms might not
663                  * implement the XSI option to extend files via ftruncate.
664                  */
665                 a->pst = NULL;
666                 if ((ret = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
667                         return (ret);
668                 if (a->st.st_size != a->filesize) {
669                         const char nul = '\0';
670                         if (lseek(a->fd, a->st.st_size - 1, SEEK_SET) < 0) {
671                                 archive_set_error(&a->archive, errno,
672                                     "Seek failed");
673                                 return (ARCHIVE_FATAL);
674                         }
675                         if (write(a->fd, &nul, 1) < 0) {
676                                 archive_set_error(&a->archive, errno,
677                                     "Write to restore size failed");
678                                 return (ARCHIVE_FATAL);
679                         }
680                         a->pst = NULL;
681                 }
682         }
683
684         /* Restore metadata. */
685
686         /*
687          * Look up the "real" UID only if we're going to need it.
688          * TODO: the TODO_SGID condition can be dropped here, can't it?
689          */
690         if (a->todo & (TODO_OWNER | TODO_SUID | TODO_SGID)) {
691                 a->uid = a->lookup_uid(a->lookup_uid_data,
692                     archive_entry_uname(a->entry),
693                     archive_entry_uid(a->entry));
694         }
695         /* Look up the "real" GID only if we're going to need it. */
696         /* TODO: the TODO_SUID condition can be dropped here, can't it? */
697         if (a->todo & (TODO_OWNER | TODO_SGID | TODO_SUID)) {
698                 a->gid = a->lookup_gid(a->lookup_gid_data,
699                     archive_entry_gname(a->entry),
700                     archive_entry_gid(a->entry));
701          }
702         /*
703          * If restoring ownership, do it before trying to restore suid/sgid
704          * bits.  If we set the owner, we know what it is and can skip
705          * a stat() call to examine the ownership of the file on disk.
706          */
707         if (a->todo & TODO_OWNER)
708                 ret = set_ownership(a);
709         if (a->todo & TODO_MODE) {
710                 int r2 = set_mode(a, a->mode);
711                 if (r2 < ret) ret = r2;
712         }
713         if (a->todo & TODO_ACLS) {
714                 int r2 = set_acls(a);
715                 if (r2 < ret) ret = r2;
716         }
717         if (a->todo & TODO_XATTR) {
718                 int r2 = set_xattrs(a);
719                 if (r2 < ret) ret = r2;
720         }
721         if (a->todo & TODO_FFLAGS) {
722                 int r2 = set_fflags(a);
723                 if (r2 < ret) ret = r2;
724         }
725         if (a->todo & TODO_TIMES) {
726                 int r2 = set_times(a);
727                 if (r2 < ret) ret = r2;
728         }
729
730         /* If there's an fd, we can close it now. */
731         if (a->fd >= 0) {
732                 close(a->fd);
733                 a->fd = -1;
734         }
735         /* If there's an entry, we can release it now. */
736         if (a->entry) {
737                 archive_entry_free(a->entry);
738                 a->entry = NULL;
739         }
740         a->archive.state = ARCHIVE_STATE_HEADER;
741         return (ret);
742 }
743
744 int
745 archive_write_disk_set_group_lookup(struct archive *_a,
746     void *private_data,
747     gid_t (*lookup_gid)(void *private, const char *gname, gid_t gid),
748     void (*cleanup_gid)(void *private))
749 {
750         struct archive_write_disk *a = (struct archive_write_disk *)_a;
751         __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
752             ARCHIVE_STATE_ANY, "archive_write_disk_set_group_lookup");
753
754         a->lookup_gid = lookup_gid;
755         a->cleanup_gid = cleanup_gid;
756         a->lookup_gid_data = private_data;
757         return (ARCHIVE_OK);
758 }
759
760 int
761 archive_write_disk_set_user_lookup(struct archive *_a,
762     void *private_data,
763     uid_t (*lookup_uid)(void *private, const char *uname, uid_t uid),
764     void (*cleanup_uid)(void *private))
765 {
766         struct archive_write_disk *a = (struct archive_write_disk *)_a;
767         __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
768             ARCHIVE_STATE_ANY, "archive_write_disk_set_user_lookup");
769
770         a->lookup_uid = lookup_uid;
771         a->cleanup_uid = cleanup_uid;
772         a->lookup_uid_data = private_data;
773         return (ARCHIVE_OK);
774 }
775
776
777 /*
778  * Create a new archive_write_disk object and initialize it with global state.
779  */
780 struct archive *
781 archive_write_disk_new(void)
782 {
783         struct archive_write_disk *a;
784
785         a = (struct archive_write_disk *)malloc(sizeof(*a));
786         if (a == NULL)
787                 return (NULL);
788         memset(a, 0, sizeof(*a));
789         a->archive.magic = ARCHIVE_WRITE_DISK_MAGIC;
790         /* We're ready to write a header immediately. */
791         a->archive.state = ARCHIVE_STATE_HEADER;
792         a->archive.vtable = archive_write_disk_vtable();
793         a->lookup_uid = trivial_lookup_uid;
794         a->lookup_gid = trivial_lookup_gid;
795         a->start_time = time(NULL);
796 #ifdef HAVE_GETEUID
797         a->user_uid = geteuid();
798 #endif /* HAVE_GETEUID */
799         if (archive_string_ensure(&a->path_safe, 512) == NULL) {
800                 free(a);
801                 return (NULL);
802         }
803         return (&a->archive);
804 }
805
806
807 /*
808  * If pathname is longer than PATH_MAX, chdir to a suitable
809  * intermediate dir and edit the path down to a shorter suffix.  Note
810  * that this routine never returns an error; if the chdir() attempt
811  * fails for any reason, we just go ahead with the long pathname.  The
812  * object creation is likely to fail, but any error will get handled
813  * at that time.
814  */
815 #ifdef HAVE_FCHDIR
816 static void
817 edit_deep_directories(struct archive_write_disk *a)
818 {
819         int ret;
820         char *tail = a->name;
821
822         a->restore_pwd = -1;
823
824         /* If path is short, avoid the open() below. */
825         if (strlen(tail) <= PATH_MAX)
826                 return;
827
828         /* Try to record our starting dir. */
829         a->restore_pwd = open(".", O_RDONLY | O_BINARY);
830         if (a->restore_pwd < 0)
831                 return;
832
833         /* As long as the path is too long... */
834         while (strlen(tail) > PATH_MAX) {
835                 /* Locate a dir prefix shorter than PATH_MAX. */
836                 tail += PATH_MAX - 8;
837                 while (tail > a->name && *tail != '/')
838                         tail--;
839                 /* Exit if we find a too-long path component. */
840                 if (tail <= a->name)
841                         return;
842                 /* Create the intermediate dir and chdir to it. */
843                 *tail = '\0'; /* Terminate dir portion */
844                 ret = create_dir(a, a->name);
845                 if (ret == ARCHIVE_OK && chdir(a->name) != 0)
846                         ret = ARCHIVE_FAILED;
847                 *tail = '/'; /* Restore the / we removed. */
848                 if (ret != ARCHIVE_OK)
849                         return;
850                 tail++;
851                 /* The chdir() succeeded; we've now shortened the path. */
852                 a->name = tail;
853         }
854         return;
855 }
856 #endif
857
858 /*
859  * The main restore function.
860  */
861 static int
862 restore_entry(struct archive_write_disk *a)
863 {
864         int ret = ARCHIVE_OK, en;
865
866         if (a->flags & ARCHIVE_EXTRACT_UNLINK && !S_ISDIR(a->mode)) {
867                 /*
868                  * TODO: Fix this.  Apparently, there are platforms
869                  * that still allow root to hose the entire filesystem
870                  * by unlinking a dir.  The S_ISDIR() test above
871                  * prevents us from using unlink() here if the new
872                  * object is a dir, but that doesn't mean the old
873                  * object isn't a dir.
874                  */
875                 if (unlink(a->name) == 0) {
876                         /* We removed it, reset cached stat. */
877                         a->pst = NULL;
878                 } else if (errno == ENOENT) {
879                         /* File didn't exist, that's just as good. */
880                 } else if (rmdir(a->name) == 0) {
881                         /* It was a dir, but now it's gone. */
882                         a->pst = NULL;
883                 } else {
884                         /* We tried, but couldn't get rid of it. */
885                         archive_set_error(&a->archive, errno,
886                             "Could not unlink");
887                         return(ARCHIVE_FAILED);
888                 }
889         }
890
891         /* Try creating it first; if this fails, we'll try to recover. */
892         en = create_filesystem_object(a);
893
894         if ((en == ENOTDIR || en == ENOENT)
895             && !(a->flags & ARCHIVE_EXTRACT_NO_AUTODIR)) {
896                 /* If the parent dir doesn't exist, try creating it. */
897                 create_parent_dir(a, a->name);
898                 /* Now try to create the object again. */
899                 en = create_filesystem_object(a);
900         }
901
902         if ((en == EISDIR || en == EEXIST)
903             && (a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
904                 /* If we're not overwriting, we're done. */
905                 archive_set_error(&a->archive, en, "Already exists");
906                 return (ARCHIVE_FAILED);
907         }
908
909         /*
910          * Some platforms return EISDIR if you call
911          * open(O_WRONLY | O_EXCL | O_CREAT) on a directory, some
912          * return EEXIST.  POSIX is ambiguous, requiring EISDIR
913          * for open(O_WRONLY) on a dir and EEXIST for open(O_EXCL | O_CREAT)
914          * on an existing item.
915          */
916         if (en == EISDIR) {
917                 /* A dir is in the way of a non-dir, rmdir it. */
918                 if (rmdir(a->name) != 0) {
919                         archive_set_error(&a->archive, errno,
920                             "Can't remove already-existing dir");
921                         return (ARCHIVE_FAILED);
922                 }
923                 a->pst = NULL;
924                 /* Try again. */
925                 en = create_filesystem_object(a);
926         } else if (en == EEXIST) {
927                 /*
928                  * We know something is in the way, but we don't know what;
929                  * we need to find out before we go any further.
930                  */
931                 int r = 0;
932                 /*
933                  * The SECURE_SYMLINK logic has already removed a
934                  * symlink to a dir if the client wants that.  So
935                  * follow the symlink if we're creating a dir.
936                  */
937                 if (S_ISDIR(a->mode))
938                         r = stat(a->name, &a->st);
939                 /*
940                  * If it's not a dir (or it's a broken symlink),
941                  * then don't follow it.
942                  */
943                 if (r != 0 || !S_ISDIR(a->mode))
944                         r = lstat(a->name, &a->st);
945                 if (r != 0) {
946                         archive_set_error(&a->archive, errno,
947                             "Can't stat existing object");
948                         return (ARCHIVE_FAILED);
949                 }
950
951                 /*
952                  * NO_OVERWRITE_NEWER doesn't apply to directories.
953                  */
954                 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER)
955                     &&  !S_ISDIR(a->st.st_mode)) {
956                         if (!older(&(a->st), a->entry)) {
957                                 archive_set_error(&a->archive, 0,
958                                     "File on disk is not older; skipping.");
959                                 return (ARCHIVE_FAILED);
960                         }
961                 }
962
963                 /* If it's our archive, we're done. */
964                 if (a->skip_file_dev > 0 &&
965                     a->skip_file_ino > 0 &&
966                     a->st.st_dev == a->skip_file_dev &&
967                     a->st.st_ino == a->skip_file_ino) {
968                         archive_set_error(&a->archive, 0, "Refusing to overwrite archive");
969                         return (ARCHIVE_FAILED);
970                 }
971
972                 if (!S_ISDIR(a->st.st_mode)) {
973                         /* A non-dir is in the way, unlink it. */
974                         if (unlink(a->name) != 0) {
975                                 archive_set_error(&a->archive, errno,
976                                     "Can't unlink already-existing object");
977                                 return (ARCHIVE_FAILED);
978                         }
979                         a->pst = NULL;
980                         /* Try again. */
981                         en = create_filesystem_object(a);
982                 } else if (!S_ISDIR(a->mode)) {
983                         /* A dir is in the way of a non-dir, rmdir it. */
984                         if (rmdir(a->name) != 0) {
985                                 archive_set_error(&a->archive, errno,
986                                     "Can't remove already-existing dir");
987                                 return (ARCHIVE_FAILED);
988                         }
989                         /* Try again. */
990                         en = create_filesystem_object(a);
991                 } else {
992                         /*
993                          * There's a dir in the way of a dir.  Don't
994                          * waste time with rmdir()/mkdir(), just fix
995                          * up the permissions on the existing dir.
996                          * Note that we don't change perms on existing
997                          * dirs unless _EXTRACT_PERM is specified.
998                          */
999                         if ((a->mode != a->st.st_mode)
1000                             && (a->todo & TODO_MODE_FORCE))
1001                                 a->deferred |= (a->todo & TODO_MODE);
1002                         /* Ownership doesn't need deferred fixup. */
1003                         en = 0; /* Forget the EEXIST. */
1004                 }
1005         }
1006
1007         if (en) {
1008                 /* Everything failed; give up here. */
1009                 archive_set_error(&a->archive, en, "Can't create '%s'", a->name);
1010                 return (ARCHIVE_FAILED);
1011         }
1012
1013         a->pst = NULL; /* Cached stat data no longer valid. */
1014         return (ret);
1015 }
1016
1017 /*
1018  * Returns 0 if creation succeeds, or else returns errno value from
1019  * the failed system call.   Note:  This function should only ever perform
1020  * a single system call.
1021  */
1022 int
1023 create_filesystem_object(struct archive_write_disk *a)
1024 {
1025         /* Create the entry. */
1026         const char *linkname;
1027         mode_t final_mode, mode;
1028         int r;
1029
1030         /* We identify hard/symlinks according to the link names. */
1031         /* Since link(2) and symlink(2) don't handle modes, we're done here. */
1032         linkname = archive_entry_hardlink(a->entry);
1033         if (linkname != NULL) {
1034                 r = link(linkname, a->name) ? errno : 0;
1035                 /*
1036                  * New cpio and pax formats allow hardlink entries
1037                  * to carry data, so we may have to open the file
1038                  * for hardlink entries.
1039                  *
1040                  * If the hardlink was successfully created and
1041                  * the archive doesn't have carry data for it,
1042                  * consider it to be non-authoritive for meta data.
1043                  * This is consistent with GNU tar and BSD pax.
1044                  * If the hardlink does carry data, let the last
1045                  * archive entry decide ownership.
1046                  */
1047                 if (r == 0 && a->filesize <= 0) {
1048                         a->todo = 0;
1049                         a->deferred = 0;
1050                 } if (r == 0 && a->filesize > 0) {
1051                         a->fd = open(a->name, O_WRONLY | O_TRUNC | O_BINARY);
1052                         if (a->fd < 0)
1053                                 r = errno;
1054                 }
1055                 return (r);
1056         }
1057         linkname = archive_entry_symlink(a->entry);
1058         if (linkname != NULL)
1059                 return symlink(linkname, a->name) ? errno : 0;
1060
1061         /*
1062          * The remaining system calls all set permissions, so let's
1063          * try to take advantage of that to avoid an extra chmod()
1064          * call.  (Recall that umask is set to zero right now!)
1065          */
1066
1067         /* Mode we want for the final restored object (w/o file type bits). */
1068         final_mode = a->mode & 07777;
1069         /*
1070          * The mode that will actually be restored in this step.  Note
1071          * that SUID, SGID, etc, require additional work to ensure
1072          * security, so we never restore them at this point.
1073          */
1074         mode = final_mode & 0777;
1075
1076         switch (a->mode & AE_IFMT) {
1077         default:
1078                 /* POSIX requires that we fall through here. */
1079                 /* FALLTHROUGH */
1080         case AE_IFREG:
1081                 a->fd = open(a->name,
1082                     O_WRONLY | O_CREAT | O_EXCL | O_BINARY, mode);
1083                 r = (a->fd < 0);
1084                 break;
1085         case AE_IFCHR:
1086 #ifdef HAVE_MKNOD
1087                 /* Note: we use AE_IFCHR for the case label, and
1088                  * S_IFCHR for the mknod() call.  This is correct.  */
1089                 r = mknod(a->name, mode | S_IFCHR,
1090                     archive_entry_rdev(a->entry));
1091 #else
1092                 /* TODO: Find a better way to warn about our inability
1093                  * to restore a char device node. */
1094                 return (EINVAL);
1095 #endif /* HAVE_MKNOD */
1096                 break;
1097         case AE_IFBLK:
1098 #ifdef HAVE_MKNOD
1099                 r = mknod(a->name, mode | S_IFBLK,
1100                     archive_entry_rdev(a->entry));
1101 #else
1102                 /* TODO: Find a better way to warn about our inability
1103                  * to restore a block device node. */
1104                 return (EINVAL);
1105 #endif /* HAVE_MKNOD */
1106                 break;
1107         case AE_IFDIR:
1108                 mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE;
1109                 r = mkdir(a->name, mode);
1110                 if (r == 0) {
1111                         /* Defer setting dir times. */
1112                         a->deferred |= (a->todo & TODO_TIMES);
1113                         a->todo &= ~TODO_TIMES;
1114                         /* Never use an immediate chmod(). */
1115                         /* We can't avoid the chmod() entirely if EXTRACT_PERM
1116                          * because of SysV SGID inheritance. */
1117                         if ((mode != final_mode)
1118                             || (a->flags & ARCHIVE_EXTRACT_PERM))
1119                                 a->deferred |= (a->todo & TODO_MODE);
1120                         a->todo &= ~TODO_MODE;
1121                 }
1122                 break;
1123         case AE_IFIFO:
1124 #ifdef HAVE_MKFIFO
1125                 r = mkfifo(a->name, mode);
1126 #else
1127                 /* TODO: Find a better way to warn about our inability
1128                  * to restore a fifo. */
1129                 return (EINVAL);
1130 #endif /* HAVE_MKFIFO */
1131                 break;
1132         }
1133
1134         /* All the system calls above set errno on failure. */
1135         if (r)
1136                 return (errno);
1137
1138         /* If we managed to set the final mode, we've avoided a chmod(). */
1139         if (mode == final_mode)
1140                 a->todo &= ~TODO_MODE;
1141         return (0);
1142 }
1143
1144 /*
1145  * Cleanup function for archive_extract.  Mostly, this involves processing
1146  * the fixup list, which is used to address a number of problems:
1147  *   * Dir permissions might prevent us from restoring a file in that
1148  *     dir, so we restore the dir with minimum 0700 permissions first,
1149  *     then correct the mode at the end.
1150  *   * Similarly, the act of restoring a file touches the directory
1151  *     and changes the timestamp on the dir, so we have to touch-up dir
1152  *     timestamps at the end as well.
1153  *   * Some file flags can interfere with the restore by, for example,
1154  *     preventing the creation of hardlinks to those files.
1155  *
1156  * Note that tar/cpio do not require that archives be in a particular
1157  * order; there is no way to know when the last file has been restored
1158  * within a directory, so there's no way to optimize the memory usage
1159  * here by fixing up the directory any earlier than the
1160  * end-of-archive.
1161  *
1162  * XXX TODO: Directory ACLs should be restored here, for the same
1163  * reason we set directory perms here. XXX
1164  */
1165 static int
1166 _archive_write_close(struct archive *_a)
1167 {
1168         struct archive_write_disk *a = (struct archive_write_disk *)_a;
1169         struct fixup_entry *next, *p;
1170         int ret;
1171
1172         __archive_check_magic(&a->archive, ARCHIVE_WRITE_DISK_MAGIC,
1173             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1174             "archive_write_disk_close");
1175         ret = _archive_write_finish_entry(&a->archive);
1176
1177         /* Sort dir list so directories are fixed up in depth-first order. */
1178         p = sort_dir_list(a->fixup_list);
1179
1180         while (p != NULL) {
1181                 a->pst = NULL; /* Mark stat cache as out-of-date. */
1182                 if (p->fixup & TODO_TIMES) {
1183 #ifdef HAVE_UTIMES
1184                         /* {f,l,}utimes() are preferred, when available. */
1185                         struct timeval times[2];
1186                         times[0].tv_sec = p->atime;
1187                         times[0].tv_usec = p->atime_nanos / 1000;
1188 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1189                         /* if it's valid and not mtime, push the birthtime first */
1190                         if (((times[1].tv_sec = p->birthtime) < p->mtime) &&
1191                         (p->birthtime > 0))
1192                         {
1193                                 times[1].tv_usec = p->birthtime_nanos / 1000;
1194                                 utimes(p->name, times);
1195                         }
1196 #endif
1197                         times[1].tv_sec = p->mtime;
1198                         times[1].tv_usec = p->mtime_nanos / 1000;
1199 #ifdef HAVE_LUTIMES
1200                         lutimes(p->name, times);
1201 #else
1202                         utimes(p->name, times);
1203 #endif
1204 #else
1205                         /* utime() is more portable, but less precise. */
1206                         struct utimbuf times;
1207                         times.modtime = p->mtime;
1208                         times.actime = p->atime;
1209
1210                         utime(p->name, &times);
1211 #endif
1212                 }
1213                 if (p->fixup & TODO_MODE_BASE)
1214                         chmod(p->name, p->mode);
1215
1216                 if (p->fixup & TODO_FFLAGS)
1217                         set_fflags_platform(a, -1, p->name,
1218                             p->mode, p->fflags_set, 0);
1219
1220                 next = p->next;
1221                 free(p->name);
1222                 free(p);
1223                 p = next;
1224         }
1225         a->fixup_list = NULL;
1226         return (ret);
1227 }
1228
1229 static int
1230 _archive_write_finish(struct archive *_a)
1231 {
1232         struct archive_write_disk *a = (struct archive_write_disk *)_a;
1233         int ret;
1234         ret = _archive_write_close(&a->archive);
1235         if (a->cleanup_gid != NULL && a->lookup_gid_data != NULL)
1236                 (a->cleanup_gid)(a->lookup_gid_data);
1237         if (a->cleanup_uid != NULL && a->lookup_uid_data != NULL)
1238                 (a->cleanup_uid)(a->lookup_uid_data);
1239         archive_string_free(&a->_name_data);
1240         archive_string_free(&a->archive.error_string);
1241         archive_string_free(&a->path_safe);
1242         free(a);
1243         return (ret);
1244 }
1245
1246 /*
1247  * Simple O(n log n) merge sort to order the fixup list.  In
1248  * particular, we want to restore dir timestamps depth-first.
1249  */
1250 static struct fixup_entry *
1251 sort_dir_list(struct fixup_entry *p)
1252 {
1253         struct fixup_entry *a, *b, *t;
1254
1255         if (p == NULL)
1256                 return (NULL);
1257         /* A one-item list is already sorted. */
1258         if (p->next == NULL)
1259                 return (p);
1260
1261         /* Step 1: split the list. */
1262         t = p;
1263         a = p->next->next;
1264         while (a != NULL) {
1265                 /* Step a twice, t once. */
1266                 a = a->next;
1267                 if (a != NULL)
1268                         a = a->next;
1269                 t = t->next;
1270         }
1271         /* Now, t is at the mid-point, so break the list here. */
1272         b = t->next;
1273         t->next = NULL;
1274         a = p;
1275
1276         /* Step 2: Recursively sort the two sub-lists. */
1277         a = sort_dir_list(a);
1278         b = sort_dir_list(b);
1279
1280         /* Step 3: Merge the returned lists. */
1281         /* Pick the first element for the merged list. */
1282         if (strcmp(a->name, b->name) > 0) {
1283                 t = p = a;
1284                 a = a->next;
1285         } else {
1286                 t = p = b;
1287                 b = b->next;
1288         }
1289
1290         /* Always put the later element on the list first. */
1291         while (a != NULL && b != NULL) {
1292                 if (strcmp(a->name, b->name) > 0) {
1293                         t->next = a;
1294                         a = a->next;
1295                 } else {
1296                         t->next = b;
1297                         b = b->next;
1298                 }
1299                 t = t->next;
1300         }
1301
1302         /* Only one list is non-empty, so just splice it on. */
1303         if (a != NULL)
1304                 t->next = a;
1305         if (b != NULL)
1306                 t->next = b;
1307
1308         return (p);
1309 }
1310
1311 /*
1312  * Returns a new, initialized fixup entry.
1313  *
1314  * TODO: Reduce the memory requirements for this list by using a tree
1315  * structure rather than a simple list of names.
1316  */
1317 static struct fixup_entry *
1318 new_fixup(struct archive_write_disk *a, const char *pathname)
1319 {
1320         struct fixup_entry *fe;
1321
1322         fe = (struct fixup_entry *)malloc(sizeof(struct fixup_entry));
1323         if (fe == NULL)
1324                 return (NULL);
1325         fe->next = a->fixup_list;
1326         a->fixup_list = fe;
1327         fe->fixup = 0;
1328         fe->name = strdup(pathname);
1329         return (fe);
1330 }
1331
1332 /*
1333  * Returns a fixup structure for the current entry.
1334  */
1335 static struct fixup_entry *
1336 current_fixup(struct archive_write_disk *a, const char *pathname)
1337 {
1338         if (a->current_fixup == NULL)
1339                 a->current_fixup = new_fixup(a, pathname);
1340         return (a->current_fixup);
1341 }
1342
1343 /* TODO: Make this work. */
1344 /*
1345  * TODO: The deep-directory support bypasses this; disable deep directory
1346  * support if we're doing symlink checks.
1347  */
1348 /*
1349  * TODO: Someday, integrate this with the deep dir support; they both
1350  * scan the path and both can be optimized by comparing against other
1351  * recent paths.
1352  */
1353 static int
1354 check_symlinks(struct archive_write_disk *a)
1355 {
1356         char *pn, *p;
1357         char c;
1358         int r;
1359         struct stat st;
1360
1361         /*
1362          * Guard against symlink tricks.  Reject any archive entry whose
1363          * destination would be altered by a symlink.
1364          */
1365         /* Whatever we checked last time doesn't need to be re-checked. */
1366         pn = a->name;
1367         p = a->path_safe.s;
1368         while ((*pn != '\0') && (*p == *pn))
1369                 ++p, ++pn;
1370         c = pn[0];
1371         /* Keep going until we've checked the entire name. */
1372         while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) {
1373                 /* Skip the next path element. */
1374                 while (*pn != '\0' && *pn != '/')
1375                         ++pn;
1376                 c = pn[0];
1377                 pn[0] = '\0';
1378                 /* Check that we haven't hit a symlink. */
1379                 r = lstat(a->name, &st);
1380                 if (r != 0) {
1381                         /* We've hit a dir that doesn't exist; stop now. */
1382                         if (errno == ENOENT)
1383                                 break;
1384                 } else if (S_ISLNK(st.st_mode)) {
1385                         if (c == '\0') {
1386                                 /*
1387                                  * Last element is symlink; remove it
1388                                  * so we can overwrite it with the
1389                                  * item being extracted.
1390                                  */
1391                                 if (unlink(a->name)) {
1392                                         archive_set_error(&a->archive, errno,
1393                                             "Could not remove symlink %s",
1394                                             a->name);
1395                                         pn[0] = c;
1396                                         return (ARCHIVE_FAILED);
1397                                 }
1398                                 a->pst = NULL;
1399                                 /*
1400                                  * Even if we did remove it, a warning
1401                                  * is in order.  The warning is silly,
1402                                  * though, if we're just replacing one
1403                                  * symlink with another symlink.
1404                                  */
1405                                 if (!S_ISLNK(a->mode)) {
1406                                         archive_set_error(&a->archive, 0,
1407                                             "Removing symlink %s",
1408                                             a->name);
1409                                 }
1410                                 /* Symlink gone.  No more problem! */
1411                                 pn[0] = c;
1412                                 return (0);
1413                         } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) {
1414                                 /* User asked us to remove problems. */
1415                                 if (unlink(a->name) != 0) {
1416                                         archive_set_error(&a->archive, 0,
1417                                             "Cannot remove intervening symlink %s",
1418                                             a->name);
1419                                         pn[0] = c;
1420                                         return (ARCHIVE_FAILED);
1421                                 }
1422                                 a->pst = NULL;
1423                         } else {
1424                                 archive_set_error(&a->archive, 0,
1425                                     "Cannot extract through symlink %s",
1426                                     a->name);
1427                                 pn[0] = c;
1428                                 return (ARCHIVE_FAILED);
1429                         }
1430                 }
1431         }
1432         pn[0] = c;
1433         /* We've checked and/or cleaned the whole path, so remember it. */
1434         archive_strcpy(&a->path_safe, a->name);
1435         return (ARCHIVE_OK);
1436 }
1437
1438 /*
1439  * Canonicalize the pathname.  In particular, this strips duplicate
1440  * '/' characters, '.' elements, and trailing '/'.  It also raises an
1441  * error for an empty path, a trailing '..' or (if _SECURE_NODOTDOT is
1442  * set) any '..' in the path.
1443  */
1444 static int
1445 cleanup_pathname(struct archive_write_disk *a)
1446 {
1447         char *dest, *src;
1448         char separator = '\0';
1449
1450         dest = src = a->name;
1451         if (*src == '\0') {
1452                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1453                     "Invalid empty pathname");
1454                 return (ARCHIVE_FAILED);
1455         }
1456
1457         /* Skip leading '/'. */
1458         if (*src == '/')
1459                 separator = *src++;
1460
1461         /* Scan the pathname one element at a time. */
1462         for (;;) {
1463                 /* src points to first char after '/' */
1464                 if (src[0] == '\0') {
1465                         break;
1466                 } else if (src[0] == '/') {
1467                         /* Found '//', ignore second one. */
1468                         src++;
1469                         continue;
1470                 } else if (src[0] == '.') {
1471                         if (src[1] == '\0') {
1472                                 /* Ignore trailing '.' */
1473                                 break;
1474                         } else if (src[1] == '/') {
1475                                 /* Skip './'. */
1476                                 src += 2;
1477                                 continue;
1478                         } else if (src[1] == '.') {
1479                                 if (src[2] == '/' || src[2] == '\0') {
1480                                         /* Conditionally warn about '..' */
1481                                         if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) {
1482                                                 archive_set_error(&a->archive,
1483                                                     ARCHIVE_ERRNO_MISC,
1484                                                     "Path contains '..'");
1485                                                 return (ARCHIVE_FAILED);
1486                                         }
1487                                 }
1488                                 /*
1489                                  * Note: Under no circumstances do we
1490                                  * remove '..' elements.  In
1491                                  * particular, restoring
1492                                  * '/foo/../bar/' should create the
1493                                  * 'foo' dir as a side-effect.
1494                                  */
1495                         }
1496                 }
1497
1498                 /* Copy current element, including leading '/'. */
1499                 if (separator)
1500                         *dest++ = '/';
1501                 while (*src != '\0' && *src != '/') {
1502                         *dest++ = *src++;
1503                 }
1504
1505                 if (*src == '\0')
1506                         break;
1507
1508                 /* Skip '/' separator. */
1509                 separator = *src++;
1510         }
1511         /*
1512          * We've just copied zero or more path elements, not including the
1513          * final '/'.
1514          */
1515         if (dest == a->name) {
1516                 /*
1517                  * Nothing got copied.  The path must have been something
1518                  * like '.' or '/' or './' or '/././././/./'.
1519                  */
1520                 if (separator)
1521                         *dest++ = '/';
1522                 else
1523                         *dest++ = '.';
1524         }
1525         /* Terminate the result. */
1526         *dest = '\0';
1527         return (ARCHIVE_OK);
1528 }
1529
1530 /*
1531  * Create the parent directory of the specified path, assuming path
1532  * is already in mutable storage.
1533  */
1534 static int
1535 create_parent_dir(struct archive_write_disk *a, char *path)
1536 {
1537         char *slash;
1538         int r;
1539
1540         /* Remove tail element to obtain parent name. */
1541         slash = strrchr(path, '/');
1542         if (slash == NULL)
1543                 return (ARCHIVE_OK);
1544         *slash = '\0';
1545         r = create_dir(a, path);
1546         *slash = '/';
1547         return (r);
1548 }
1549
1550 /*
1551  * Create the specified dir, recursing to create parents as necessary.
1552  *
1553  * Returns ARCHIVE_OK if the path exists when we're done here.
1554  * Otherwise, returns ARCHIVE_FAILED.
1555  * Assumes path is in mutable storage; path is unchanged on exit.
1556  */
1557 static int
1558 create_dir(struct archive_write_disk *a, char *path)
1559 {
1560         struct stat st;
1561         struct fixup_entry *le;
1562         char *slash, *base;
1563         mode_t mode_final, mode;
1564         int r;
1565
1566         r = ARCHIVE_OK;
1567
1568         /* Check for special names and just skip them. */
1569         slash = strrchr(path, '/');
1570         if (slash == NULL)
1571                 base = path;
1572         else
1573                 base = slash + 1;
1574
1575         if (base[0] == '\0' ||
1576             (base[0] == '.' && base[1] == '\0') ||
1577             (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
1578                 /* Don't bother trying to create null path, '.', or '..'. */
1579                 if (slash != NULL) {
1580                         *slash = '\0';
1581                         r = create_dir(a, path);
1582                         *slash = '/';
1583                         return (r);
1584                 }
1585                 return (ARCHIVE_OK);
1586         }
1587
1588         /*
1589          * Yes, this should be stat() and not lstat().  Using lstat()
1590          * here loses the ability to extract through symlinks.  Also note
1591          * that this should not use the a->st cache.
1592          */
1593         if (stat(path, &st) == 0) {
1594                 if (S_ISDIR(st.st_mode))
1595                         return (ARCHIVE_OK);
1596                 if ((a->flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
1597                         archive_set_error(&a->archive, EEXIST,
1598                             "Can't create directory '%s'", path);
1599                         return (ARCHIVE_FAILED);
1600                 }
1601                 if (unlink(path) != 0) {
1602                         archive_set_error(&a->archive, errno,
1603                             "Can't create directory '%s': "
1604                             "Conflicting file cannot be removed");
1605                         return (ARCHIVE_FAILED);
1606                 }
1607         } else if (errno != ENOENT && errno != ENOTDIR) {
1608                 /* Stat failed? */
1609                 archive_set_error(&a->archive, errno, "Can't test directory '%s'", path);
1610                 return (ARCHIVE_FAILED);
1611         } else if (slash != NULL) {
1612                 *slash = '\0';
1613                 r = create_dir(a, path);
1614                 *slash = '/';
1615                 if (r != ARCHIVE_OK)
1616                         return (r);
1617         }
1618
1619         /*
1620          * Mode we want for the final restored directory.  Per POSIX,
1621          * implicitly-created dirs must be created obeying the umask.
1622          * There's no mention whether this is different for privileged
1623          * restores (which the rest of this code handles by pretending
1624          * umask=0).  I've chosen here to always obey the user's umask for
1625          * implicit dirs, even if _EXTRACT_PERM was specified.
1626          */
1627         mode_final = DEFAULT_DIR_MODE & ~a->user_umask;
1628         /* Mode we want on disk during the restore process. */
1629         mode = mode_final;
1630         mode |= MINIMUM_DIR_MODE;
1631         mode &= MAXIMUM_DIR_MODE;
1632         if (mkdir(path, mode) == 0) {
1633                 if (mode != mode_final) {
1634                         le = new_fixup(a, path);
1635                         le->fixup |=TODO_MODE_BASE;
1636                         le->mode = mode_final;
1637                 }
1638                 return (ARCHIVE_OK);
1639         }
1640
1641         /*
1642          * Without the following check, a/b/../b/c/d fails at the
1643          * second visit to 'b', so 'd' can't be created.  Note that we
1644          * don't add it to the fixup list here, as it's already been
1645          * added.
1646          */
1647         if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
1648                 return (ARCHIVE_OK);
1649
1650         archive_set_error(&a->archive, errno, "Failed to create dir '%s'", path);
1651         return (ARCHIVE_FAILED);
1652 }
1653
1654 /*
1655  * Note: Although we can skip setting the user id if the desired user
1656  * id matches the current user, we cannot skip setting the group, as
1657  * many systems set the gid based on the containing directory.  So
1658  * we have to perform a chown syscall if we want to set the SGID
1659  * bit.  (The alternative is to stat() and then possibly chown(); it's
1660  * more efficient to skip the stat() and just always chown().)  Note
1661  * that a successful chown() here clears the TODO_SGID_CHECK bit, which
1662  * allows set_mode to skip the stat() check for the GID.
1663  */
1664 static int
1665 set_ownership(struct archive_write_disk *a)
1666 {
1667         /* If we know we can't change it, don't bother trying. */
1668         if (a->user_uid != 0  &&  a->user_uid != a->uid) {
1669                 archive_set_error(&a->archive, errno,
1670                     "Can't set UID=%d", a->uid);
1671                 return (ARCHIVE_WARN);
1672         }
1673
1674 #ifdef HAVE_FCHOWN
1675         /* If we have an fd, we can avoid a race. */
1676         if (a->fd >= 0 && fchown(a->fd, a->uid, a->gid) == 0) {
1677                 /* We've set owner and know uid/gid are correct. */
1678                 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1679                 return (ARCHIVE_OK);
1680         }
1681 #endif
1682
1683         /* We prefer lchown() but will use chown() if that's all we have. */
1684         /* Of course, if we have neither, this will always fail. */
1685 #ifdef HAVE_LCHOWN
1686         if (lchown(a->name, a->uid, a->gid) == 0) {
1687                 /* We've set owner and know uid/gid are correct. */
1688                 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1689                 return (ARCHIVE_OK);
1690         }
1691 #elif HAVE_CHOWN
1692         if (!S_ISLNK(a->mode) && chown(a->name, a->uid, a->gid) == 0) {
1693                 /* We've set owner and know uid/gid are correct. */
1694                 a->todo &= ~(TODO_OWNER | TODO_SGID_CHECK | TODO_SUID_CHECK);
1695                 return (ARCHIVE_OK);
1696         }
1697 #endif
1698
1699         archive_set_error(&a->archive, errno,
1700             "Can't set user=%d/group=%d for %s", a->uid, a->gid,
1701             a->name);
1702         return (ARCHIVE_WARN);
1703 }
1704
1705 #ifdef HAVE_UTIMES
1706 /*
1707  * The utimes()-family functions provide high resolution and
1708  * a way to set time on an fd or a symlink.  We prefer them
1709  * when they're available.
1710  */
1711 static int
1712 set_time(int fd, int mode, const char *name,
1713     time_t atime, long atime_nsec,
1714     time_t mtime, long mtime_nsec)
1715 {
1716         struct timeval times[2];
1717
1718         times[0].tv_sec = atime;
1719         times[0].tv_usec = atime_nsec / 1000;
1720         times[1].tv_sec = mtime;
1721         times[1].tv_usec = mtime_nsec / 1000;
1722
1723 #ifdef HAVE_FUTIMES
1724         if (fd >= 0)
1725                 return (futimes(fd, times));
1726 #else
1727         (void)fd; /* UNUSED */
1728 #endif
1729 #ifdef HAVE_LUTIMES
1730         (void)mode; /* UNUSED */
1731         return (lutimes(name, times));
1732 #else
1733         if (S_ISLNK(mode))
1734                 return (0);
1735         return (utimes(name, times));
1736 #endif
1737 }
1738 #elif defined(HAVE_UTIME)
1739 /*
1740  * utime() is an older, more standard interface that we'll use
1741  * if utimes() isn't available.
1742  */
1743 static int
1744 set_time(int fd, int mode, const char *name,
1745     time_t atime, long atime_nsec,
1746     time_t mtime, long mtime_nsec)
1747 {
1748         struct utimbuf times;
1749         (void)fd; /* UNUSED */
1750         (void)name; /* UNUSED */
1751         (void)atime_nsec; /* UNUSED */
1752         (void)mtime_nsec; /* UNUSED */
1753         times.actime = atime;
1754         times.modtime = mtime;
1755         if (S_ISLNK(mode))
1756                 return (ARCHIVE_OK);
1757         return (utime(name, &times));
1758 }
1759 #else
1760 static int
1761 set_time(int fd, int mode, const char *name,
1762     time_t atime, long atime_nsec,
1763     time_t mtime, long mtime_nsec)
1764 {
1765         return (ARCHIVE_WARN);
1766 }
1767 #endif
1768
1769 static int
1770 set_times(struct archive_write_disk *a)
1771 {
1772         time_t atime = a->start_time, mtime = a->start_time;
1773         long atime_nsec = 0, mtime_nsec = 0;
1774
1775         /* If no time was provided, we're done. */
1776         if (!archive_entry_atime_is_set(a->entry)
1777 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
1778             && !archive_entry_birthtime_is_set(a->entry)
1779 #endif
1780             && !archive_entry_mtime_is_set(a->entry))
1781                 return (ARCHIVE_OK);
1782
1783         /* If no atime was specified, use start time instead. */
1784         /* In theory, it would be marginally more correct to use
1785          * time(NULL) here, but that would cost us an extra syscall
1786          * for little gain. */
1787         if (archive_entry_atime_is_set(a->entry)) {
1788                 atime = archive_entry_atime(a->entry);
1789                 atime_nsec = archive_entry_atime_nsec(a->entry);
1790         }
1791
1792         /*
1793          * If you have struct stat.st_birthtime, we assume BSD birthtime
1794          * semantics, in which {f,l,}utimes() updates birthtime to earliest
1795          * mtime.  So we set the time twice, first using the birthtime,
1796          * then using the mtime.
1797          */
1798 #if HAVE_STRUCT_STAT_ST_BIRTHTIME
1799         /* If birthtime is set, flush that through to disk first. */
1800         if (archive_entry_birthtime_is_set(a->entry))
1801                 if (set_time(a->fd, a->mode, a->name, atime, atime_nsec,
1802                         archive_entry_birthtime(a->entry),
1803                         archive_entry_birthtime_nsec(a->entry))) {
1804                         archive_set_error(&a->archive, errno,
1805                             "Can't update time for %s",
1806                             a->name);
1807                         return (ARCHIVE_WARN);
1808                 }
1809 #endif
1810
1811         if (archive_entry_mtime_is_set(a->entry)) {
1812                 mtime = archive_entry_mtime(a->entry);
1813                 mtime_nsec = archive_entry_mtime_nsec(a->entry);
1814         }
1815         if (set_time(a->fd, a->mode, a->name,
1816                 atime, atime_nsec, mtime, mtime_nsec)) {
1817                 archive_set_error(&a->archive, errno,
1818                     "Can't update time for %s",
1819                     a->name);
1820                 return (ARCHIVE_WARN);
1821         }
1822
1823         /*
1824          * Note: POSIX does not provide a portable way to restore ctime.
1825          * (Apart from resetting the system clock, which is distasteful.)
1826          * So, any restoration of ctime will necessarily be OS-specific.
1827          */
1828
1829         return (ARCHIVE_OK);
1830 }
1831
1832 static int
1833 set_mode(struct archive_write_disk *a, int mode)
1834 {
1835         int r = ARCHIVE_OK;
1836         mode &= 07777; /* Strip off file type bits. */
1837
1838         if (a->todo & TODO_SGID_CHECK) {
1839                 /*
1840                  * If we don't know the GID is right, we must stat()
1841                  * to verify it.  We can't just check the GID of this
1842                  * process, since systems sometimes set GID from
1843                  * the enclosing dir or based on ACLs.
1844                  */
1845                 if ((r = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
1846                         return (r);
1847                 if (a->pst->st_gid != a->gid) {
1848                         mode &= ~ S_ISGID;
1849                         if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1850                                 /*
1851                                  * This is only an error if you
1852                                  * requested owner restore.  If you
1853                                  * didn't, we'll try to restore
1854                                  * sgid/suid, but won't consider it a
1855                                  * problem if we can't.
1856                                  */
1857                                 archive_set_error(&a->archive, -1,
1858                                     "Can't restore SGID bit");
1859                                 r = ARCHIVE_WARN;
1860                         }
1861                 }
1862                 /* While we're here, double-check the UID. */
1863                 if (a->pst->st_uid != a->uid
1864                     && (a->todo & TODO_SUID)) {
1865                         mode &= ~ S_ISUID;
1866                         if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1867                                 archive_set_error(&a->archive, -1,
1868                                     "Can't restore SUID bit");
1869                                 r = ARCHIVE_WARN;
1870                         }
1871                 }
1872                 a->todo &= ~TODO_SGID_CHECK;
1873                 a->todo &= ~TODO_SUID_CHECK;
1874         } else if (a->todo & TODO_SUID_CHECK) {
1875                 /*
1876                  * If we don't know the UID is right, we can just check
1877                  * the user, since all systems set the file UID from
1878                  * the process UID.
1879                  */
1880                 if (a->user_uid != a->uid) {
1881                         mode &= ~ S_ISUID;
1882                         if (a->flags & ARCHIVE_EXTRACT_OWNER) {
1883                                 archive_set_error(&a->archive, -1,
1884                                     "Can't make file SUID");
1885                                 r = ARCHIVE_WARN;
1886                         }
1887                 }
1888                 a->todo &= ~TODO_SUID_CHECK;
1889         }
1890
1891         if (S_ISLNK(a->mode)) {
1892 #ifdef HAVE_LCHMOD
1893                 /*
1894                  * If this is a symlink, use lchmod().  If the
1895                  * platform doesn't support lchmod(), just skip it.  A
1896                  * platform that doesn't provide a way to set
1897                  * permissions on symlinks probably ignores
1898                  * permissions on symlinks, so a failure here has no
1899                  * impact.
1900                  */
1901                 if (lchmod(a->name, mode) != 0) {
1902                         archive_set_error(&a->archive, errno,
1903                             "Can't set permissions to 0%o", (int)mode);
1904                         r = ARCHIVE_WARN;
1905                 }
1906 #endif
1907         } else if (!S_ISDIR(a->mode)) {
1908                 /*
1909                  * If it's not a symlink and not a dir, then use
1910                  * fchmod() or chmod(), depending on whether we have
1911                  * an fd.  Dirs get their perms set during the
1912                  * post-extract fixup, which is handled elsewhere.
1913                  */
1914 #ifdef HAVE_FCHMOD
1915                 if (a->fd >= 0) {
1916                         if (fchmod(a->fd, mode) != 0) {
1917                                 archive_set_error(&a->archive, errno,
1918                                     "Can't set permissions to 0%o", (int)mode);
1919                                 r = ARCHIVE_WARN;
1920                         }
1921                 } else
1922 #endif
1923                         /* If this platform lacks fchmod(), then
1924                          * we'll just use chmod(). */
1925                         if (chmod(a->name, mode) != 0) {
1926                                 archive_set_error(&a->archive, errno,
1927                                     "Can't set permissions to 0%o", (int)mode);
1928                                 r = ARCHIVE_WARN;
1929                         }
1930         }
1931         return (r);
1932 }
1933
1934 static int
1935 set_fflags(struct archive_write_disk *a)
1936 {
1937         struct fixup_entry *le;
1938         unsigned long   set, clear;
1939         int             r;
1940         int             critical_flags;
1941         mode_t          mode = archive_entry_mode(a->entry);
1942
1943         /*
1944          * Make 'critical_flags' hold all file flags that can't be
1945          * immediately restored.  For example, on BSD systems,
1946          * SF_IMMUTABLE prevents hardlinks from being created, so
1947          * should not be set until after any hardlinks are created.  To
1948          * preserve some semblance of portability, this uses #ifdef
1949          * extensively.  Ugly, but it works.
1950          *
1951          * Yes, Virginia, this does create a security race.  It's mitigated
1952          * somewhat by the practice of creating dirs 0700 until the extract
1953          * is done, but it would be nice if we could do more than that.
1954          * People restoring critical file systems should be wary of
1955          * other programs that might try to muck with files as they're
1956          * being restored.
1957          */
1958         /* Hopefully, the compiler will optimize this mess into a constant. */
1959         critical_flags = 0;
1960 #ifdef SF_IMMUTABLE
1961         critical_flags |= SF_IMMUTABLE;
1962 #endif
1963 #ifdef UF_IMMUTABLE
1964         critical_flags |= UF_IMMUTABLE;
1965 #endif
1966 #ifdef SF_APPEND
1967         critical_flags |= SF_APPEND;
1968 #endif
1969 #ifdef UF_APPEND
1970         critical_flags |= UF_APPEND;
1971 #endif
1972 #ifdef EXT2_APPEND_FL
1973         critical_flags |= EXT2_APPEND_FL;
1974 #endif
1975 #ifdef EXT2_IMMUTABLE_FL
1976         critical_flags |= EXT2_IMMUTABLE_FL;
1977 #endif
1978
1979         if (a->todo & TODO_FFLAGS) {
1980                 archive_entry_fflags(a->entry, &set, &clear);
1981
1982                 /*
1983                  * The first test encourages the compiler to eliminate
1984                  * all of this if it's not necessary.
1985                  */
1986                 if ((critical_flags != 0)  &&  (set & critical_flags)) {
1987                         le = current_fixup(a, a->name);
1988                         le->fixup |= TODO_FFLAGS;
1989                         le->fflags_set = set;
1990                         /* Store the mode if it's not already there. */
1991                         if ((le->fixup & TODO_MODE) == 0)
1992                                 le->mode = mode;
1993                 } else {
1994                         r = set_fflags_platform(a, a->fd,
1995                             a->name, mode, set, clear);
1996                         if (r != ARCHIVE_OK)
1997                                 return (r);
1998                 }
1999         }
2000         return (ARCHIVE_OK);
2001 }
2002
2003
2004 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && defined(HAVE_STRUCT_STAT_ST_FLAGS)
2005 /*
2006  * BSD reads flags using stat() and sets them with one of {f,l,}chflags()
2007  */
2008 static int
2009 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2010     mode_t mode, unsigned long set, unsigned long clear)
2011 {
2012         int r;
2013
2014         (void)mode; /* UNUSED */
2015         if (set == 0  && clear == 0)
2016                 return (ARCHIVE_OK);
2017
2018         /*
2019          * XXX Is the stat here really necessary?  Or can I just use
2020          * the 'set' flags directly?  In particular, I'm not sure
2021          * about the correct approach if we're overwriting an existing
2022          * file that already has flags on it. XXX
2023          */
2024         if ((r = _archive_write_disk_lazy_stat(a)) != ARCHIVE_OK)
2025                 return (r);
2026
2027         a->st.st_flags &= ~clear;
2028         a->st.st_flags |= set;
2029 #ifdef HAVE_FCHFLAGS
2030         /* If platform has fchflags() and we were given an fd, use it. */
2031         if (fd >= 0 && fchflags(fd, a->st.st_flags) == 0)
2032                 return (ARCHIVE_OK);
2033 #endif
2034         /*
2035          * If we can't use the fd to set the flags, we'll use the
2036          * pathname to set flags.  We prefer lchflags() but will use
2037          * chflags() if we must.
2038          */
2039 #ifdef HAVE_LCHFLAGS
2040         if (lchflags(name, a->st.st_flags) == 0)
2041                 return (ARCHIVE_OK);
2042 #elif defined(HAVE_CHFLAGS)
2043         if (S_ISLNK(a->st.st_mode)) {
2044                 archive_set_error(&a->archive, errno,
2045                     "Can't set file flags on symlink.");
2046                 return (ARCHIVE_WARN);
2047         }
2048         if (chflags(name, a->st.st_flags) == 0)
2049                 return (ARCHIVE_OK);
2050 #endif
2051         archive_set_error(&a->archive, errno,
2052             "Failed to set file flags");
2053         return (ARCHIVE_WARN);
2054 }
2055
2056 #elif defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS)
2057 /*
2058  * Linux uses ioctl() to read and write file flags.
2059  */
2060 static int
2061 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2062     mode_t mode, unsigned long set, unsigned long clear)
2063 {
2064         int              ret;
2065         int              myfd = fd;
2066         unsigned long newflags, oldflags;
2067         unsigned long sf_mask = 0;
2068
2069         if (set == 0  && clear == 0)
2070                 return (ARCHIVE_OK);
2071         /* Only regular files and dirs can have flags. */
2072         if (!S_ISREG(mode) && !S_ISDIR(mode))
2073                 return (ARCHIVE_OK);
2074
2075         /* If we weren't given an fd, open it ourselves. */
2076         if (myfd < 0)
2077                 myfd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY);
2078         if (myfd < 0)
2079                 return (ARCHIVE_OK);
2080
2081         /*
2082          * Linux has no define for the flags that are only settable by
2083          * the root user.  This code may seem a little complex, but
2084          * there seem to be some Linux systems that lack these
2085          * defines. (?)  The code below degrades reasonably gracefully
2086          * if sf_mask is incomplete.
2087          */
2088 #ifdef EXT2_IMMUTABLE_FL
2089         sf_mask |= EXT2_IMMUTABLE_FL;
2090 #endif
2091 #ifdef EXT2_APPEND_FL
2092         sf_mask |= EXT2_APPEND_FL;
2093 #endif
2094         /*
2095          * XXX As above, this would be way simpler if we didn't have
2096          * to read the current flags from disk. XXX
2097          */
2098         ret = ARCHIVE_OK;
2099         /* Try setting the flags as given. */
2100         if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
2101                 newflags = (oldflags & ~clear) | set;
2102                 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
2103                         goto cleanup;
2104                 if (errno != EPERM)
2105                         goto fail;
2106         }
2107         /* If we couldn't set all the flags, try again with a subset. */
2108         if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
2109                 newflags &= ~sf_mask;
2110                 oldflags &= sf_mask;
2111                 newflags |= oldflags;
2112                 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
2113                         goto cleanup;
2114         }
2115         /* We couldn't set the flags, so report the failure. */
2116 fail:
2117         archive_set_error(&a->archive, errno,
2118             "Failed to set file flags");
2119         ret = ARCHIVE_WARN;
2120 cleanup:
2121         if (fd < 0)
2122                 close(myfd);
2123         return (ret);
2124 }
2125
2126 #else
2127
2128 /*
2129  * Of course, some systems have neither BSD chflags() nor Linux' flags
2130  * support through ioctl().
2131  */
2132 static int
2133 set_fflags_platform(struct archive_write_disk *a, int fd, const char *name,
2134     mode_t mode, unsigned long set, unsigned long clear)
2135 {
2136         (void)a; /* UNUSED */
2137         (void)fd; /* UNUSED */
2138         (void)name; /* UNUSED */
2139         (void)mode; /* UNUSED */
2140         (void)set; /* UNUSED */
2141         (void)clear; /* UNUSED */
2142         return (ARCHIVE_OK);
2143 }
2144
2145 #endif /* __linux */
2146
2147 #ifndef HAVE_POSIX_ACL
2148 /* Default empty function body to satisfy mainline code. */
2149 static int
2150 set_acls(struct archive_write_disk *a)
2151 {
2152         (void)a; /* UNUSED */
2153         return (ARCHIVE_OK);
2154 }
2155
2156 #else
2157
2158 /*
2159  * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
2160  */
2161 static int
2162 set_acls(struct archive_write_disk *a)
2163 {
2164         int              ret;
2165
2166         ret = set_acl(a, a->fd, a->entry, ACL_TYPE_ACCESS,
2167             ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
2168         if (ret != ARCHIVE_OK)
2169                 return (ret);
2170         ret = set_acl(a, a->fd, a->entry, ACL_TYPE_DEFAULT,
2171             ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
2172         return (ret);
2173 }
2174
2175
2176 static int
2177 set_acl(struct archive_write_disk *a, int fd, struct archive_entry *entry,
2178     acl_type_t acl_type, int ae_requested_type, const char *tname)
2179 {
2180         acl_t            acl;
2181         acl_entry_t      acl_entry;
2182         acl_permset_t    acl_permset;
2183         int              ret;
2184         int              ae_type, ae_permset, ae_tag, ae_id;
2185         uid_t            ae_uid;
2186         gid_t            ae_gid;
2187         const char      *ae_name;
2188         int              entries;
2189         const char      *name;
2190
2191         ret = ARCHIVE_OK;
2192         entries = archive_entry_acl_reset(entry, ae_requested_type);
2193         if (entries == 0)
2194                 return (ARCHIVE_OK);
2195         acl = acl_init(entries);
2196         while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
2197                    &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
2198                 acl_create_entry(&acl, &acl_entry);
2199
2200                 switch (ae_tag) {
2201                 case ARCHIVE_ENTRY_ACL_USER:
2202                         acl_set_tag_type(acl_entry, ACL_USER);
2203                         ae_uid = a->lookup_uid(a->lookup_uid_data,
2204                             ae_name, ae_id);
2205                         acl_set_qualifier(acl_entry, &ae_uid);
2206                         break;
2207                 case ARCHIVE_ENTRY_ACL_GROUP:
2208                         acl_set_tag_type(acl_entry, ACL_GROUP);
2209                         ae_gid = a->lookup_gid(a->lookup_gid_data,
2210                             ae_name, ae_id);
2211                         acl_set_qualifier(acl_entry, &ae_gid);
2212                         break;
2213                 case ARCHIVE_ENTRY_ACL_USER_OBJ:
2214                         acl_set_tag_type(acl_entry, ACL_USER_OBJ);
2215                         break;
2216                 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
2217                         acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
2218                         break;
2219                 case ARCHIVE_ENTRY_ACL_MASK:
2220                         acl_set_tag_type(acl_entry, ACL_MASK);
2221                         break;
2222                 case ARCHIVE_ENTRY_ACL_OTHER:
2223                         acl_set_tag_type(acl_entry, ACL_OTHER);
2224                         break;
2225                 default:
2226                         /* XXX */
2227                         break;
2228                 }
2229
2230                 acl_get_permset(acl_entry, &acl_permset);
2231                 acl_clear_perms(acl_permset);
2232                 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
2233                         acl_add_perm(acl_permset, ACL_EXECUTE);
2234                 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
2235                         acl_add_perm(acl_permset, ACL_WRITE);
2236                 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
2237                         acl_add_perm(acl_permset, ACL_READ);
2238         }
2239
2240         name = archive_entry_pathname(entry);
2241
2242         /* Try restoring the ACL through 'fd' if we can. */
2243 #if HAVE_ACL_SET_FD
2244         if (fd >= 0 && acl_type == ACL_TYPE_ACCESS && acl_set_fd(fd, acl) == 0)
2245                 ret = ARCHIVE_OK;
2246         else
2247 #else
2248 #if HAVE_ACL_SET_FD_NP
2249         if (fd >= 0 && acl_set_fd_np(fd, acl, acl_type) == 0)
2250                 ret = ARCHIVE_OK;
2251         else
2252 #endif
2253 #endif
2254         if (acl_set_file(name, acl_type, acl) != 0) {
2255                 archive_set_error(&a->archive, errno, "Failed to set %s acl", tname);
2256                 ret = ARCHIVE_WARN;
2257         }
2258         acl_free(acl);
2259         return (ret);
2260 }
2261 #endif
2262
2263 #if HAVE_LSETXATTR
2264 /*
2265  * Restore extended attributes -  Linux implementation
2266  */
2267 static int
2268 set_xattrs(struct archive_write_disk *a)
2269 {
2270         struct archive_entry *entry = a->entry;
2271         static int warning_done = 0;
2272         int ret = ARCHIVE_OK;
2273         int i = archive_entry_xattr_reset(entry);
2274
2275         while (i--) {
2276                 const char *name;
2277                 const void *value;
2278                 size_t size;
2279                 archive_entry_xattr_next(entry, &name, &value, &size);
2280                 if (name != NULL &&
2281                                 strncmp(name, "xfsroot.", 8) != 0 &&
2282                                 strncmp(name, "system.", 7) != 0) {
2283                         int e;
2284 #if HAVE_FSETXATTR
2285                         if (a->fd >= 0)
2286                                 e = fsetxattr(a->fd, name, value, size, 0);
2287                         else
2288 #endif
2289                         {
2290                                 e = lsetxattr(archive_entry_pathname(entry),
2291                                     name, value, size, 0);
2292                         }
2293                         if (e == -1) {
2294                                 if (errno == ENOTSUP) {
2295                                         if (!warning_done) {
2296                                                 warning_done = 1;
2297                                                 archive_set_error(&a->archive, errno,
2298                                                     "Cannot restore extended "
2299                                                     "attributes on this file "
2300                                                     "system");
2301                                         }
2302                                 } else
2303                                         archive_set_error(&a->archive, errno,
2304                                             "Failed to set extended attribute");
2305                                 ret = ARCHIVE_WARN;
2306                         }
2307                 } else {
2308                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2309                             "Invalid extended attribute encountered");
2310                         ret = ARCHIVE_WARN;
2311                 }
2312         }
2313         return (ret);
2314 }
2315 #else
2316 /*
2317  * Restore extended attributes - stub implementation for unsupported systems
2318  */
2319 static int
2320 set_xattrs(struct archive_write_disk *a)
2321 {
2322         static int warning_done = 0;
2323
2324         /* If there aren't any extended attributes, then it's okay not
2325          * to extract them, otherwise, issue a single warning. */
2326         if (archive_entry_xattr_count(a->entry) != 0 && !warning_done) {
2327                 warning_done = 1;
2328                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2329                     "Cannot restore extended attributes on this system");
2330                 return (ARCHIVE_WARN);
2331         }
2332         /* Warning was already emitted; suppress further warnings. */
2333         return (ARCHIVE_OK);
2334 }
2335 #endif
2336
2337
2338 /*
2339  * Trivial implementations of gid/uid lookup functions.
2340  * These are normally overridden by the client, but these stub
2341  * versions ensure that we always have something that works.
2342  */
2343 static gid_t
2344 trivial_lookup_gid(void *private_data, const char *gname, gid_t gid)
2345 {
2346         (void)private_data; /* UNUSED */
2347         (void)gname; /* UNUSED */
2348         return (gid);
2349 }
2350
2351 static uid_t
2352 trivial_lookup_uid(void *private_data, const char *uname, uid_t uid)
2353 {
2354         (void)private_data; /* UNUSED */
2355         (void)uname; /* UNUSED */
2356         return (uid);
2357 }
2358
2359 /*
2360  * Test if file on disk is older than entry.
2361  */
2362 static int
2363 older(struct stat *st, struct archive_entry *entry)
2364 {
2365         /* First, test the seconds and return if we have a definite answer. */
2366         /* Definitely older. */
2367         if (st->st_mtime < archive_entry_mtime(entry))
2368                 return (1);
2369         /* Definitely younger. */
2370         if (st->st_mtime > archive_entry_mtime(entry))
2371                 return (0);
2372         /* If this platform supports fractional seconds, try those. */
2373 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
2374         /* Definitely older. */
2375         if (st->st_mtimespec.tv_nsec < archive_entry_mtime_nsec(entry))
2376                 return (1);
2377         /* Definitely younger. */
2378         if (st->st_mtimespec.tv_nsec > archive_entry_mtime_nsec(entry))
2379                 return (0);
2380 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
2381         /* Definitely older. */
2382         if (st->st_mtim.tv_nsec < archive_entry_mtime_nsec(entry))
2383                 return (1);
2384         /* Definitely older. */
2385         if (st->st_mtim.tv_nsec > archive_entry_mtime_nsec(entry))
2386                 return (0);
2387 #else
2388         /* This system doesn't have high-res timestamps. */
2389 #endif
2390         /* Same age, so not older. */
2391         return (0);
2392 }