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