Import of libarchive and bsdtar 1.3.1
[dragonfly.git] / contrib / libarchive-1.3.1 / libarchive / archive_read_extract.c
1 /*-
2  * Copyright (c) 2003-2005 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: src/lib/libarchive/archive_read_extract.c,v 1.47 2006/09/05 05:59:45 kientzle Exp $");
29
30 #include <sys/types.h>
31 #ifdef HAVE_SYS_ACL_H
32 #include <sys/acl.h>
33 #endif
34 #ifdef HAVE_ATTR_XATTR_H
35 #include <attr/xattr.h>
36 #endif
37 #ifdef HAVE_SYS_IOCTL_H
38 #include <sys/ioctl.h>
39 #endif
40 #include <sys/stat.h>
41 #include <sys/time.h>
42
43 #ifdef HAVE_EXT2FS_EXT2_FS_H
44 #include <ext2fs/ext2_fs.h>     /* for Linux file flags */
45 #endif
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <grp.h>
49 #ifdef HAVE_LINUX_EXT2_FS_H
50 #include <linux/ext2_fs.h>      /* for Linux file flags */
51 #endif
52 #include <limits.h>
53 #include <pwd.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <unistd.h>
58
59 #include "archive.h"
60 #include "archive_string.h"
61 #include "archive_entry.h"
62 #include "archive_private.h"
63
64 struct fixup_entry {
65         struct fixup_entry      *next;
66         mode_t                   mode;
67         int64_t                  mtime;
68         int64_t                  atime;
69         unsigned long            mtime_nanos;
70         unsigned long            atime_nanos;
71         unsigned long            fflags_set;
72         int                      fixup; /* bitmask of what needs fixing */
73         char                    *name;
74 };
75
76 #define FIXUP_MODE      1
77 #define FIXUP_TIMES     2
78 #define FIXUP_FFLAGS    4
79
80 struct bucket {
81         char    *name;
82         int      hash;
83         id_t     id;
84 };
85
86 struct extract {
87         mode_t                   umask;
88         mode_t                   default_dir_mode;
89         struct archive_string    create_parent_dir;
90         struct fixup_entry      *fixup_list;
91         struct fixup_entry      *current_fixup;
92
93         struct bucket ucache[127];
94         struct bucket gcache[127];
95
96         /*
97          * Cached stat data from disk for the current entry.
98          * If this is valid, pst points to st.  Otherwise,
99          * pst is null.
100          */
101         struct stat              st;
102         struct stat             *pst;
103 };
104
105 /* Default mode for dirs created automatically (will be modified by umask). */
106 #define DEFAULT_DIR_MODE 0777
107 /*
108  * Mode to use for newly-created dirs during extraction; the correct
109  * mode will be set at the end of the extraction.
110  */
111 #define SECURE_DIR_MODE 0700
112
113 static int      archive_extract_cleanup(struct archive *);
114 static int      extract_block_device(struct archive *,
115                     struct archive_entry *, int);
116 static int      extract_char_device(struct archive *,
117                     struct archive_entry *, int);
118 static int      extract_device(struct archive *,
119                     struct archive_entry *, int flags, mode_t mode);
120 static int      extract_dir(struct archive *, struct archive_entry *, int);
121 static int      extract_fifo(struct archive *, struct archive_entry *, int);
122 static int      extract_file(struct archive *, struct archive_entry *, int);
123 static int      extract_hard_link(struct archive *, struct archive_entry *, int);
124 static int      extract_symlink(struct archive *, struct archive_entry *, int);
125 static unsigned int     hash(const char *);
126 static gid_t    lookup_gid(struct archive *, const char *uname, gid_t);
127 static uid_t    lookup_uid(struct archive *, const char *uname, uid_t);
128 static int      create_dir(struct archive *, const char *, int flags);
129 static int      create_dir_mutable(struct archive *, char *, int flags);
130 static int      create_dir_recursive(struct archive *, char *, int flags);
131 static int      create_parent_dir(struct archive *, const char *, int flags);
132 static int      create_parent_dir_mutable(struct archive *, char *, int flags);
133 static int      restore_metadata(struct archive *, int fd,
134                     struct archive_entry *, int flags);
135 #ifdef HAVE_POSIX_ACL
136 static int      set_acl(struct archive *, int fd, struct archive_entry *,
137                     acl_type_t, int archive_entry_acl_type, const char *tn);
138 #endif
139 static int      set_acls(struct archive *, int fd, struct archive_entry *);
140 static int      set_xattrs(struct archive *, int fd, struct archive_entry *);
141 static int      set_fflags(struct archive *, int fd, const char *name, mode_t,
142                     unsigned long fflags_set, unsigned long fflags_clear);
143 static int      set_ownership(struct archive *, int fd, struct archive_entry *,
144                     int flags);
145 static int      set_perm(struct archive *, int fd, struct archive_entry *,
146                     int mode, int flags);
147 static int      set_time(struct archive *, int fd, struct archive_entry *, int);
148 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
149
150
151 /*
152  * Extract this entry to disk.
153  *
154  * TODO: Validate hardlinks.  According to the standards, we're
155  * supposed to check each extracted hardlink and squawk if it refers
156  * to a file that we didn't restore.  I'm not entirely convinced this
157  * is a good idea, but more importantly: Is there any way to validate
158  * hardlinks without keeping a complete list of filenames from the
159  * entire archive?? Ugh.
160  *
161  */
162 int
163 archive_read_extract(struct archive *a, struct archive_entry *entry, int flags)
164 {
165         mode_t mode;
166         struct extract *extract;
167         int ret;
168         int restore_pwd;
169         char *original_filename;
170
171         if (a->extract == NULL) {
172                 a->extract = malloc(sizeof(*a->extract));
173                 if (a->extract == NULL) {
174                         archive_set_error(a, ENOMEM, "Can't extract");
175                         return (ARCHIVE_FATAL);
176                 }
177                 a->cleanup_archive_extract = archive_extract_cleanup;
178                 memset(a->extract, 0, sizeof(*a->extract));
179         }
180         extract = a->extract;
181         umask(extract->umask = umask(0)); /* Read the current umask. */
182         extract->default_dir_mode = DEFAULT_DIR_MODE & ~extract->umask;
183         extract->pst = NULL;
184         extract->current_fixup = NULL;
185         restore_pwd = -1;
186         original_filename = NULL;
187
188         /* The following is not possible without fchdir.  <sigh> */
189 #ifdef HAVE_FCHDIR
190         /*
191          * If pathname is longer than PATH_MAX, record starting directory
192          * and chdir to a suitable intermediate dir.
193          */
194         if (strlen(archive_entry_pathname(entry)) > PATH_MAX) {
195                 char *intdir, *tail;
196
197                 restore_pwd = open(".", O_RDONLY);
198                 if (restore_pwd < 0) {
199                                 archive_set_error(a, errno,
200                                     "Unable to restore long pathname");
201                                 return (ARCHIVE_WARN);
202                 }
203
204                 /*
205                  * Yes, the copy here is necessary because we edit
206                  * the pathname in-place to create intermediate dirnames.
207                  */
208                 original_filename = strdup(archive_entry_pathname(entry));
209
210                 /*
211                  * "intdir" points to the initial dir section we're going
212                  * to remove, "tail" points to the remainder of the path.
213                  */
214                 intdir = tail = original_filename;
215                 while (strlen(tail) > PATH_MAX) {
216                         intdir = tail;
217
218                         /* Locate a dir prefix shorter than PATH_MAX. */
219                         tail = intdir + PATH_MAX - 8;
220                         while (tail > intdir && *tail != '/')
221                                 tail--;
222                         if (tail <= intdir) {
223                                 archive_set_error(a, EPERM,
224                                     "Path element too long");
225                                 ret = ARCHIVE_WARN;
226                                 goto cleanup;
227                         }
228
229                         /* Create intdir and chdir to it. */
230                         *tail = '\0'; /* Terminate dir portion */
231                         ret = create_dir(a, intdir, flags);
232                         if (ret == ARCHIVE_OK && chdir(intdir) != 0) {
233                                 archive_set_error(a, errno, "Couldn't chdir");
234                                 ret = ARCHIVE_WARN;
235                         }
236                         *tail = '/'; /* Restore the / we removed. */
237                         if (ret != ARCHIVE_OK)
238                                 goto cleanup;
239                         tail++;
240                 }
241                 archive_entry_set_pathname(entry, tail);
242         }
243 #endif
244
245         if (stat(archive_entry_pathname(entry), &extract->st) == 0)
246                 extract->pst = &extract->st;
247
248         if (extract->pst != NULL &&
249             extract->pst->st_dev == a->skip_file_dev &&
250             extract->pst->st_ino == a->skip_file_ino) {
251                 archive_set_error(a, 0, "Refusing to overwrite archive");
252                 ret = ARCHIVE_WARN;
253         } else if (archive_entry_hardlink(entry) != NULL)
254                 ret = extract_hard_link(a, entry, flags);
255         else {
256                 mode = archive_entry_mode(entry);
257                 switch (mode & S_IFMT) {
258                 default:
259                         /* Fall through, as required by POSIX. */
260                 case S_IFREG:
261                         ret = extract_file(a, entry, flags);
262                         break;
263                 case S_IFLNK:   /* Symlink */
264                         ret = extract_symlink(a, entry, flags);
265                         break;
266                 case S_IFCHR:
267                         ret = extract_char_device(a, entry, flags);
268                         break;
269                 case S_IFBLK:
270                         ret = extract_block_device(a, entry, flags);
271                         break;
272                 case S_IFDIR:
273                         ret = extract_dir(a, entry, flags);
274                         break;
275                 case S_IFIFO:
276                         ret = extract_fifo(a, entry, flags);
277                         break;
278                 }
279         }
280
281
282 cleanup:
283 #ifdef HAVE_FCHDIR
284         /* If we changed directory above, restore it here. */
285         if (restore_pwd >= 0 && original_filename != NULL) {
286                 fchdir(restore_pwd);
287                 close(restore_pwd);
288                 archive_entry_copy_pathname(entry, original_filename);
289                 free(original_filename);
290         }
291 #endif
292
293         return (ret);
294 }
295
296 /*
297  * Cleanup function for archive_extract.  Mostly, this involves processing
298  * the fixup list, which is used to address a number of problems:
299  *   * Dir permissions might prevent us from restoring a file in that
300  *     dir, so we restore the dir 0700 first, then correct the
301  *     mode at the end.
302  *   * Similarly, the act of restoring a file touches the directory
303  *     and changes the timestamp on the dir, so we have to touch-up dir
304  *     timestamps at the end as well.
305  *   * Some file flags can interfere with the restore by, for example,
306  *     preventing the creation of hardlinks to those files.
307  *
308  * Note that tar/cpio do not require that archives be in a particular
309  * order; there is no way to know when the last file has been restored
310  * within a directory, so there's no way to optimize the memory usage
311  * here by fixing up the directory any earlier than the
312  * end-of-archive.
313  *
314  * XXX TODO: Directory ACLs should be restored here, for the same
315  * reason we set directory perms here. XXX
316  *
317  * Registering this function (rather than calling it explicitly by
318  * name from archive_read_finish) reduces static link pollution, since
319  * applications that don't use this API won't get this file linked in.
320  */
321 static int
322 archive_extract_cleanup(struct archive *a)
323 {
324         struct fixup_entry *next, *p;
325         struct extract *extract;
326
327         /* Sort dir list so directories are fixed up in depth-first order. */
328         extract = a->extract;
329         p = sort_dir_list(extract->fixup_list);
330
331         while (p != NULL) {
332                 extract->pst = NULL; /* Mark stat cache as out-of-date. */
333                 if (p->fixup & FIXUP_TIMES) {
334                         struct timeval times[2];
335                         times[1].tv_sec = p->mtime;
336                         times[1].tv_usec = p->mtime_nanos / 1000;
337                         times[0].tv_sec = p->atime;
338                         times[0].tv_usec = p->atime_nanos / 1000;
339                         utimes(p->name, times);
340                 }
341                 if (p->fixup & FIXUP_MODE)
342                         chmod(p->name, p->mode);
343
344                 if (p->fixup & FIXUP_FFLAGS)
345                         set_fflags(a, -1, p->name, p->mode, p->fflags_set, 0);
346
347                 next = p->next;
348                 free(p->name);
349                 free(p);
350                 p = next;
351         }
352         extract->fixup_list = NULL;
353         archive_string_free(&extract->create_parent_dir);
354         free(a->extract);
355         a->extract = NULL;
356         return (ARCHIVE_OK);
357 }
358
359 /*
360  * Simple O(n log n) merge sort to order the fixup list.  In
361  * particular, we want to restore dir timestamps depth-first.
362  */
363 static struct fixup_entry *
364 sort_dir_list(struct fixup_entry *p)
365 {
366         struct fixup_entry *a, *b, *t;
367
368         if (p == NULL)
369                 return (NULL);
370         /* A one-item list is already sorted. */
371         if (p->next == NULL)
372                 return (p);
373
374         /* Step 1: split the list. */
375         t = p;
376         a = p->next->next;
377         while (a != NULL) {
378                 /* Step a twice, t once. */
379                 a = a->next;
380                 if (a != NULL)
381                         a = a->next;
382                 t = t->next;
383         }
384         /* Now, t is at the mid-point, so break the list here. */
385         b = t->next;
386         t->next = NULL;
387         a = p;
388
389         /* Step 2: Recursively sort the two sub-lists. */
390         a = sort_dir_list(a);
391         b = sort_dir_list(b);
392
393         /* Step 3: Merge the returned lists. */
394         /* Pick the first element for the merged list. */
395         if (strcmp(a->name, b->name) > 0) {
396                 t = p = a;
397                 a = a->next;
398         } else {
399                 t = p = b;
400                 b = b->next;
401         }
402
403         /* Always put the later element on the list first. */
404         while (a != NULL && b != NULL) {
405                 if (strcmp(a->name, b->name) > 0) {
406                         t->next = a;
407                         a = a->next;
408                 } else {
409                         t->next = b;
410                         b = b->next;
411                 }
412                 t = t->next;
413         }
414
415         /* Only one list is non-empty, so just splice it on. */
416         if (a != NULL)
417                 t->next = a;
418         if (b != NULL)
419                 t->next = b;
420
421         return (p);
422 }
423
424 /*
425  * Returns a new, initialized fixup entry.
426  *
427  * TODO: Reduce the memory requirements for this list by using a tree
428  * structure rather than a simple list of names.
429  */
430 static struct fixup_entry *
431 new_fixup(struct archive *a, const char *pathname)
432 {
433         struct extract *extract;
434         struct fixup_entry *fe;
435
436         extract = a->extract;
437         fe = malloc(sizeof(struct fixup_entry));
438         if (fe == NULL)
439                 return (NULL);
440         fe->next = extract->fixup_list;
441         extract->fixup_list = fe;
442         fe->fixup = 0;
443         fe->name = strdup(pathname);
444         return (fe);
445 }
446
447 /*
448  * Returns a fixup structure for the current entry.
449  */
450 static struct fixup_entry *
451 current_fixup(struct archive *a, const char *pathname)
452 {
453         struct extract *extract;
454
455         extract = a->extract;
456         if (extract->current_fixup == NULL)
457                 extract->current_fixup = new_fixup(a, pathname);
458         return (extract->current_fixup);
459 }
460
461 static int
462 extract_file(struct archive *a, struct archive_entry *entry, int flags)
463 {
464         struct extract *extract;
465         const char *name;
466         mode_t mode;
467         int fd, r, r2;
468
469         extract = a->extract;
470         name = archive_entry_pathname(entry);
471         mode = archive_entry_mode(entry) & 0777;
472         r = ARCHIVE_OK;
473
474         /*
475          * If we're not supposed to overwrite pre-existing files,
476          * use O_EXCL.  Otherwise, use O_TRUNC.
477          */
478         if (flags & (ARCHIVE_EXTRACT_UNLINK | ARCHIVE_EXTRACT_NO_OVERWRITE))
479                 fd = open(name, O_WRONLY | O_CREAT | O_EXCL, mode);
480         else
481                 fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, mode);
482
483         /* Try removing a pre-existing file. */
484         if (fd < 0 && !(flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
485                 unlink(name);
486                 fd = open(name, O_WRONLY | O_CREAT | O_EXCL, mode);
487         }
488
489         /* Might be a non-existent parent dir; try fixing that. */
490         if (fd < 0) {
491                 create_parent_dir(a, name, flags);
492                 fd = open(name, O_WRONLY | O_CREAT | O_EXCL, mode);
493         }
494         if (fd < 0) {
495                 archive_set_error(a, errno, "Can't open '%s'", name);
496                 return (ARCHIVE_WARN);
497         }
498         r = archive_read_data_into_fd(a, fd);
499         extract->pst = NULL; /* Cached stat data no longer valid. */
500         r2 = restore_metadata(a, fd, entry, flags);
501         close(fd);
502         return (err_combine(r, r2));
503 }
504
505 static int
506 extract_dir(struct archive *a, struct archive_entry *entry, int flags)
507 {
508         struct extract *extract;
509         struct fixup_entry *fe;
510         char *path, *p;
511
512         extract = a->extract;
513         extract->pst = NULL; /* Invalidate cached stat data. */
514
515         /* Copy path to mutable storage. */
516         archive_strcpy(&(extract->create_parent_dir),
517             archive_entry_pathname(entry));
518         path = extract->create_parent_dir.s;
519
520         if (*path == '\0') {
521                 archive_set_error(a, ARCHIVE_ERRNO_MISC,
522                     "Invalid empty pathname");
523                 return (ARCHIVE_WARN);
524         }
525
526         /* Deal with any troublesome trailing path elements. */
527         /* TODO: Someday, generalize this to remove '//' or '/./' from
528          * the middle of paths.  But, it should not compress '..' from
529          * the middle of paths.  It's a feature that restoring
530          * "a/../b" creates both 'a' and 'b' directories. */
531         for (;;) {
532                 /* Locate last element. */
533                 p = strrchr(path, '/');
534                 if (p != NULL)
535                         p++;
536                 else
537                         p = path;
538                 /* Trim trailing '/' unless that's the entire path. */
539                 if (p[0] == '\0' && p - 1 > path) {
540                         p[-1] = '\0';
541                         continue;
542                 }
543                 /* Trim trailing '.' unless that's the entire path. */
544                 if (p > path && p[0] == '.' && p[1] == '\0') {
545                         p[0] = '\0';
546                         continue;
547                 }
548                 /* Just exit on trailing '..'. */
549                 if (p[0] == '.' && p[1] == '.' && p[2] == '\0') {
550                         archive_set_error(a, ARCHIVE_ERRNO_MISC,
551                             "Can't restore directory '..'");
552                         return (ARCHIVE_WARN);
553                 }
554                 break;
555         }
556
557         if (mkdir(path, SECURE_DIR_MODE) == 0)
558                 goto success;
559
560         if (extract->pst == NULL && stat(path, &extract->st) == 0)
561                 extract->pst = &extract->st;
562
563         if (extract->pst != NULL) {
564                 extract->pst = &extract->st;
565                 /* If dir already exists, don't reset permissions. */
566                 if (S_ISDIR(extract->pst->st_mode))
567                         return (ARCHIVE_OK);
568                 /* It exists but isn't a dir. */
569                 if ((flags & ARCHIVE_EXTRACT_UNLINK))
570                         unlink(path);
571         } else {
572                 /* Doesn't already exist; try building the parent path. */
573                 if (create_parent_dir_mutable(a, path, flags) != ARCHIVE_OK)
574                         return (ARCHIVE_WARN);
575         }
576
577         /* One final attempt to create the dir. */
578         if (mkdir(path, SECURE_DIR_MODE) != 0) {
579                 archive_set_error(a, errno, "Can't create directory");
580                 return (ARCHIVE_WARN);
581         }
582
583 success:
584         /* Add this dir to the fixup list. */
585         fe = current_fixup(a, path);
586         fe->fixup |= FIXUP_MODE;
587         fe->mode = archive_entry_mode(entry);
588         if ((flags & ARCHIVE_EXTRACT_PERM) == 0)
589                 fe->mode &= ~extract->umask;
590         if (flags & ARCHIVE_EXTRACT_TIME) {
591                 fe->fixup |= FIXUP_TIMES;
592                 fe->mtime = archive_entry_mtime(entry);
593                 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
594                 fe->atime = archive_entry_atime(entry);
595                 fe->atime_nanos = archive_entry_atime_nsec(entry);
596         }
597         /* For now, set the mode to SECURE_DIR_MODE. */
598         archive_entry_set_mode(entry, SECURE_DIR_MODE);
599         return (restore_metadata(a, -1, entry, flags));
600 }
601
602
603 /*
604  * Create the parent of the specified path.  Copy the provided
605  * path into mutable storage first.
606  */
607 static int
608 create_parent_dir(struct archive *a, const char *path, int flags)
609 {
610         int r;
611
612         /* Copy path to mutable storage. */
613         archive_strcpy(&(a->extract->create_parent_dir), path);
614         r = create_parent_dir_mutable(a, a->extract->create_parent_dir.s, flags);
615         return (r);
616 }
617
618 /*
619  * Like create_parent_dir, but creates the dir actually requested, not
620  * the parent.
621  */
622 static int
623 create_dir(struct archive *a, const char *path, int flags)
624 {
625         int r;
626         /* Copy path to mutable storage. */
627         archive_strcpy(&(a->extract->create_parent_dir), path);
628         r = create_dir_mutable(a, a->extract->create_parent_dir.s, flags);
629         return (r);
630 }
631
632 /*
633  * Create the parent directory of the specified path, assuming path
634  * is already in mutable storage.
635  */
636 static int
637 create_parent_dir_mutable(struct archive *a, char *path, int flags)
638 {
639         char *slash;
640         int r;
641
642         /* Remove tail element to obtain parent name. */
643         slash = strrchr(path, '/');
644         if (slash == NULL)
645                 return (ARCHIVE_OK);
646         *slash = '\0';
647         r = create_dir_mutable(a, path, flags);
648         *slash = '/';
649         return (r);
650 }
651
652 /*
653  * Create the specified dir, assuming path is already in
654  * mutable storage.
655  */
656 static int
657 create_dir_mutable(struct archive *a, char *path, int flags)
658 {
659         mode_t old_umask;
660         int r;
661
662         old_umask = umask(~SECURE_DIR_MODE);
663         r = create_dir_recursive(a, path, flags);
664         umask(old_umask);
665         return (r);
666 }
667
668 /*
669  * Create the specified dir, recursing to create parents as necessary.
670  *
671  * Returns ARCHIVE_OK if the path exists when we're done here.
672  * Otherwise, returns ARCHIVE_WARN.
673  */
674 static int
675 create_dir_recursive(struct archive *a, char *path, int flags)
676 {
677         struct stat st;
678         struct extract *extract;
679         struct fixup_entry *le;
680         char *slash, *base;
681         int r;
682
683         extract = a->extract;
684         r = ARCHIVE_OK;
685
686         /* Check for special names and just skip them. */
687         slash = strrchr(path, '/');
688         base = strrchr(path, '/');
689         if (slash == NULL)
690                 base = path;
691         else
692                 base = slash + 1;
693
694         if (base[0] == '\0' ||
695             (base[0] == '.' && base[1] == '\0') ||
696             (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
697                 /* Don't bother trying to create null path, '.', or '..'. */
698                 if (slash != NULL) {
699                         *slash = '\0';
700                         r = create_dir_recursive(a, path, flags);
701                         *slash = '/';
702                         return (r);
703                 }
704                 return (ARCHIVE_OK);
705         }
706
707         /*
708          * Yes, this should be stat() and not lstat().  Using lstat()
709          * here loses the ability to extract through symlinks.  Also note
710          * that this should not use the extract->st cache.
711          */
712         if (stat(path, &st) == 0) {
713                 if (S_ISDIR(st.st_mode))
714                         return (ARCHIVE_OK);
715                 if ((flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
716                         archive_set_error(a, EEXIST,
717                             "Can't create directory '%s'", path);
718                         return (ARCHIVE_WARN);
719                 }
720                 if (unlink(path) != 0) {
721                         archive_set_error(a, errno,
722                             "Can't create directory '%s': "
723                             "Conflicting file cannot be removed");
724                         return (ARCHIVE_WARN);
725                 }
726         } else if (errno != ENOENT && errno != ENOTDIR) {
727                 /* Stat failed? */
728                 archive_set_error(a, errno, "Can't test directory '%s'", path);
729                 return (ARCHIVE_WARN);
730         } else if (slash != NULL) {
731                 *slash = '\0';
732                 r = create_dir_recursive(a, path, flags);
733                 *slash = '/';
734                 if (r != ARCHIVE_OK)
735                         return (r);
736         }
737
738         if (mkdir(path, SECURE_DIR_MODE) == 0) {
739                 le = new_fixup(a, path);
740                 le->fixup |= FIXUP_MODE;
741                 le->mode = extract->default_dir_mode;
742                 return (ARCHIVE_OK);
743         }
744
745         /*
746          * Without the following check, a/b/../b/c/d fails at the
747          * second visit to 'b', so 'd' can't be created.  Note that we
748          * don't add it to the fixup list here, as it's already been
749          * added.
750          */
751         if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
752                 return (ARCHIVE_OK);
753
754         archive_set_error(a, errno, "Failed to create dir '%s'", path);
755         return (ARCHIVE_WARN);
756 }
757
758 static int
759 extract_hard_link(struct archive *a, struct archive_entry *entry, int flags)
760 {
761         struct extract *extract;
762         int r;
763         const char *pathname;
764         const char *linkname;
765
766         extract = a->extract;
767         pathname = archive_entry_pathname(entry);
768         linkname = archive_entry_hardlink(entry);
769
770         /* Just remove any pre-existing file with this name. */
771         if (!(flags & ARCHIVE_EXTRACT_NO_OVERWRITE))
772                 unlink(pathname);
773
774         r = link(linkname, pathname);
775         extract->pst = NULL; /* Invalidate cached stat data. */
776
777         if (r != 0) {
778                 /* Might be a non-existent parent dir; try fixing that. */
779                 create_parent_dir(a, pathname, flags);
780                 r = link(linkname, pathname);
781         }
782
783         if (r != 0) {
784                 /* XXX Better error message here XXX */
785                 archive_set_error(a, errno,
786                     "Can't restore hardlink to '%s'", linkname);
787                 return (ARCHIVE_WARN);
788         }
789
790         /* Set ownership, time, permission information. */
791         r = restore_metadata(a, -1, entry, flags);
792         return (r);
793 }
794
795 static int
796 extract_symlink(struct archive *a, struct archive_entry *entry, int flags)
797 {
798         struct extract *extract;
799         int r;
800         const char *pathname;
801         const char *linkname;
802
803         extract = a->extract;
804         pathname = archive_entry_pathname(entry);
805         linkname = archive_entry_symlink(entry);
806
807         /* Just remove any pre-existing file with this name. */
808         if (!(flags & ARCHIVE_EXTRACT_NO_OVERWRITE))
809                 unlink(pathname);
810
811         r = symlink(linkname, pathname);
812         extract->pst = NULL; /* Invalidate cached stat data. */
813
814         if (r != 0) {
815                 /* Might be a non-existent parent dir; try fixing that. */
816                 create_parent_dir(a, pathname, flags);
817                 r = symlink(linkname, pathname);
818         }
819
820         if (r != 0) {
821                 /* XXX Better error message here XXX */
822                 archive_set_error(a, errno,
823                     "Can't restore symlink to '%s'", linkname);
824                 return (ARCHIVE_WARN);
825         }
826
827         r = restore_metadata(a, -1, entry, flags);
828         return (r);
829 }
830
831 static int
832 extract_device(struct archive *a, struct archive_entry *entry,
833     int flags, mode_t mode)
834 {
835         struct extract *extract;
836         int r;
837
838         extract = a->extract;
839         /* Just remove any pre-existing file with this name. */
840         if (!(flags & ARCHIVE_EXTRACT_NO_OVERWRITE))
841                 unlink(archive_entry_pathname(entry));
842
843         r = mknod(archive_entry_pathname(entry), mode,
844             archive_entry_rdev(entry));
845         extract->pst = NULL; /* Invalidate cached stat data. */
846
847         /* Might be a non-existent parent dir; try fixing that. */
848         if (r != 0 && errno == ENOENT) {
849                 create_parent_dir(a, archive_entry_pathname(entry), flags);
850                 r = mknod(archive_entry_pathname(entry), mode,
851                     archive_entry_rdev(entry));
852         }
853
854         if (r != 0) {
855                 archive_set_error(a, errno, "Can't restore device node");
856                 return (ARCHIVE_WARN);
857         }
858
859         r = restore_metadata(a, -1, entry, flags);
860         return (r);
861 }
862
863 static int
864 extract_char_device(struct archive *a, struct archive_entry *entry, int flags)
865 {
866         mode_t mode;
867
868         mode = (archive_entry_mode(entry) & ~S_IFMT) | S_IFCHR;
869         return (extract_device(a, entry, flags, mode));
870 }
871
872 static int
873 extract_block_device(struct archive *a, struct archive_entry *entry, int flags)
874 {
875         mode_t mode;
876
877         mode = (archive_entry_mode(entry) & ~S_IFMT) | S_IFBLK;
878         return (extract_device(a, entry, flags, mode));
879 }
880
881 static int
882 extract_fifo(struct archive *a, struct archive_entry *entry, int flags)
883 {
884         struct extract *extract;
885         int r;
886
887         extract = a->extract;
888         /* Just remove any pre-existing file with this name. */
889         if (!(flags & ARCHIVE_EXTRACT_NO_OVERWRITE))
890                 unlink(archive_entry_pathname(entry));
891
892         r = mkfifo(archive_entry_pathname(entry),
893             archive_entry_mode(entry));
894         extract->pst = NULL; /* Invalidate cached stat data. */
895
896         /* Might be a non-existent parent dir; try fixing that. */
897         if (r != 0 && errno == ENOENT) {
898                 create_parent_dir(a, archive_entry_pathname(entry), flags);
899                 r = mkfifo(archive_entry_pathname(entry),
900                     archive_entry_mode(entry));
901         }
902
903         if (r != 0) {
904                 archive_set_error(a, errno, "Can't restore fifo");
905                 return (ARCHIVE_WARN);
906         }
907
908         r = restore_metadata(a, -1, entry, flags);
909         return (r);
910 }
911
912 static int
913 restore_metadata(struct archive *a, int fd, struct archive_entry *entry, int flags)
914 {
915         int r, r2;
916
917         r = set_ownership(a, fd, entry, flags);
918         r2 = set_time(a, fd, entry, flags);
919         r = err_combine(r, r2);
920         r2 = set_perm(a, fd, entry, archive_entry_mode(entry), flags);
921         return (err_combine(r, r2));
922 }
923
924 static int
925 set_ownership(struct archive *a, int fd,
926     struct archive_entry *entry, int flags)
927 {
928         uid_t uid;
929         gid_t gid;
930
931         /* Not changed. */
932         if ((flags & ARCHIVE_EXTRACT_OWNER) == 0)
933                 return (ARCHIVE_OK);
934
935         uid = lookup_uid(a, archive_entry_uname(entry),
936             archive_entry_uid(entry));
937         gid = lookup_gid(a, archive_entry_gname(entry),
938             archive_entry_gid(entry));
939
940         /* If we know we can't change it, don't bother trying. */
941         if (a->user_uid != 0  &&  a->user_uid != uid)
942                 return (ARCHIVE_OK);
943
944 #ifdef HAVE_FCHOWN
945         if (fd >= 0 && fchown(fd, uid, gid) == 0)
946                 return (ARCHIVE_OK);
947 #endif
948
949 #ifdef HAVE_LCHOWN
950         if (lchown(archive_entry_pathname(entry), uid, gid))
951 #else
952         if (!S_ISLNK(archive_entry_mode(entry))
953             && chown(archive_entry_pathname(entry), uid, gid) != 0)
954 #endif
955         {
956                 archive_set_error(a, errno,
957                     "Can't set user=%d/group=%d for %s", uid, gid,
958                     archive_entry_pathname(entry));
959                 return (ARCHIVE_WARN);
960         }
961         return (ARCHIVE_OK);
962 }
963
964 static int
965 set_time(struct archive *a, int fd, struct archive_entry *entry, int flags)
966 {
967         const struct stat *st;
968         struct timeval times[2];
969
970         (void)a; /* UNUSED */
971         st = archive_entry_stat(entry);
972
973         if ((flags & ARCHIVE_EXTRACT_TIME) == 0)
974                 return (ARCHIVE_OK);
975         /* It's a waste of time to mess with dir timestamps here. */
976         if (S_ISDIR(archive_entry_mode(entry)))
977                 return (ARCHIVE_OK);
978
979         times[1].tv_sec = st->st_mtime;
980         times[1].tv_usec = ARCHIVE_STAT_MTIME_NANOS(st) / 1000;
981
982         times[0].tv_sec = st->st_atime;
983         times[0].tv_usec = ARCHIVE_STAT_ATIME_NANOS(st) / 1000;
984
985 #ifdef HAVE_FUTIMES
986         if (fd >= 0 && futimes(fd, times) == 0)
987                 return (ARCHIVE_OK);
988 #endif
989
990 #ifdef HAVE_LUTIMES
991         if (lutimes(archive_entry_pathname(entry), times) != 0) {
992 #else
993         if ((archive_entry_mode(entry) & S_IFMT) != S_IFLNK &&
994             utimes(archive_entry_pathname(entry), times) != 0) {
995 #endif
996                 archive_set_error(a, errno, "Can't update time for %s",
997                     archive_entry_pathname(entry));
998                 return (ARCHIVE_WARN);
999         }
1000
1001         /*
1002          * Note: POSIX does not provide a portable way to restore ctime.
1003          * (Apart from resetting the system clock, which is distasteful.)
1004          * So, any restoration of ctime will necessarily be OS-specific.
1005          */
1006
1007         /* XXX TODO: Can FreeBSD restore ctime? XXX */
1008
1009         return (ARCHIVE_OK);
1010 }
1011
1012 static int
1013 set_perm(struct archive *a, int fd, struct archive_entry *entry,
1014     int mode, int flags)
1015 {
1016         struct extract *extract;
1017         struct fixup_entry *le;
1018         const char *name;
1019         unsigned long    set, clear;
1020         int              r;
1021         int              critical_flags;
1022
1023         extract = a->extract;
1024
1025         /* Obey umask unless ARCHIVE_EXTRACT_PERM. */
1026         if ((flags & ARCHIVE_EXTRACT_PERM) == 0)
1027                 mode &= ~extract->umask; /* Enforce umask. */
1028         name = archive_entry_pathname(entry);
1029
1030         if (mode & (S_ISUID | S_ISGID)) {
1031                 if (extract->pst != NULL) {
1032                         /* Already have stat() data available. */
1033 #ifdef HAVE_FSTAT
1034                 } else if (fd >= 0 && fstat(fd, &extract->st) == 0) {
1035                         extract->pst = &extract->st;
1036 #endif
1037                 } else if (stat(name, &extract->st) == 0) {
1038                         extract->pst = &extract->st;
1039                 } else {
1040                         archive_set_error(a, errno,
1041                             "Couldn't stat file");
1042                         return (ARCHIVE_WARN);
1043                 }
1044
1045                 /*
1046                  * TODO: Use the uid/gid looked up in set_ownership
1047                  * above rather than the uid/gid stored in the entry.
1048                  */
1049                 if (extract->pst->st_uid != archive_entry_uid(entry))
1050                         mode &= ~ S_ISUID;
1051                 if (extract->pst->st_gid != archive_entry_gid(entry))
1052                         mode &= ~ S_ISGID;
1053         }
1054
1055         /*
1056          * Ensure we change permissions on the object we extracted,
1057          * and not any incidental symlink that might have gotten in
1058          * the way.
1059          */
1060         if (!S_ISLNK(archive_entry_mode(entry))) {
1061 #ifdef HAVE_FCHMOD
1062                 if (fd >= 0) {
1063                         if (fchmod(fd, mode) != 0) {
1064                                 archive_set_error(a, errno,
1065                                     "Can't set permissions");
1066                                 return (ARCHIVE_WARN);
1067                         }
1068                 } else
1069 #endif
1070                 if (chmod(name, mode) != 0) {
1071                         archive_set_error(a, errno, "Can't set permissions");
1072                         return (ARCHIVE_WARN);
1073                 }
1074 #ifdef HAVE_LCHMOD
1075         } else {
1076                 /*
1077                  * If lchmod() isn't supported, it's no big deal.
1078                  * Permissions on symlinks are actually ignored on
1079                  * most platforms.
1080                  */
1081                 if (lchmod(name, mode) != 0) {
1082                         archive_set_error(a, errno, "Can't set permissions");
1083                         return (ARCHIVE_WARN);
1084                 }
1085 #endif
1086         }
1087
1088         if (flags & ARCHIVE_EXTRACT_ACL) {
1089                 r = set_acls(a, fd, entry);
1090                 if (r != ARCHIVE_OK)
1091                         return (r);
1092         }
1093
1094         if (flags & ARCHIVE_EXTRACT_XATTR) {
1095                 r = set_xattrs(a, fd, entry);
1096                 if (r != ARCHIVE_OK)
1097                         return (r);
1098         }
1099
1100         /*
1101          * Make 'critical_flags' hold all file flags that can't be
1102          * immediately restored.  For example, on BSD systems,
1103          * SF_IMMUTABLE prevents hardlinks from being created, so
1104          * should not be set until after any hardlinks are created.  To
1105          * preserve some semblance of portability, this uses #ifdef
1106          * extensively.  Ugly, but it works.
1107          *
1108          * Yes, Virginia, this does create a security race.  It's mitigated
1109          * somewhat by the practice of creating dirs 0700 until the extract
1110          * is done, but it would be nice if we could do more than that.
1111          * People restoring critical file systems should be wary of
1112          * other programs that might try to muck with files as they're
1113          * being restored.
1114          */
1115         /* Hopefully, the compiler will optimize this mess into a constant. */
1116         critical_flags = 0;
1117 #ifdef SF_IMMUTABLE
1118         critical_flags |= SF_IMMUTABLE;
1119 #endif
1120 #ifdef UF_IMMUTABLE
1121         critical_flags |= UF_IMMUTABLE;
1122 #endif
1123 #ifdef SF_APPEND
1124         critical_flags |= SF_APPEND;
1125 #endif
1126 #ifdef UF_APPEND
1127         critical_flags |= UF_APPEND;
1128 #endif
1129 #ifdef EXT2_APPEND_FL
1130         critical_flags |= EXT2_APPEND_FL;
1131 #endif
1132 #ifdef EXT2_IMMUTABLE_FL
1133         critical_flags |= EXT2_IMMUTABLE_FL;
1134 #endif
1135
1136         if (flags & ARCHIVE_EXTRACT_FFLAGS) {
1137                 archive_entry_fflags(entry, &set, &clear);
1138
1139                 /*
1140                  * The first test encourages the compiler to eliminate
1141                  * all of this if it's not necessary.
1142                  */
1143                 if ((critical_flags != 0)  &&  (set & critical_flags)) {
1144                         le = current_fixup(a, archive_entry_pathname(entry));
1145                         le->fixup |= FIXUP_FFLAGS;
1146                         le->fflags_set = set;
1147                         /* Store the mode if it's not already there. */
1148                         if ((le->fixup & FIXUP_MODE) == 0)
1149                                 le->mode = mode;
1150                 } else {
1151                         r = set_fflags(a, fd, archive_entry_pathname(entry),
1152                             mode, set, clear);
1153                         if (r != ARCHIVE_OK)
1154                                 return (r);
1155                 }
1156         }
1157         return (ARCHIVE_OK);
1158 }
1159
1160
1161 #if ( defined(HAVE_LCHFLAGS) || defined(HAVE_CHFLAGS) || defined(HAVE_FCHFLAGS) ) && !defined(__linux)
1162 static int
1163 set_fflags(struct archive *a, int fd, const char *name, mode_t mode,
1164     unsigned long set, unsigned long clear)
1165 {
1166         struct extract *extract;
1167
1168         extract = a->extract;
1169         if (set == 0  && clear == 0)
1170                 return (ARCHIVE_OK);
1171
1172         (void)mode; /* UNUSED */
1173         /*
1174          * XXX Is the stat here really necessary?  Or can I just use
1175          * the 'set' flags directly?  In particular, I'm not sure
1176          * about the correct approach if we're overwriting an existing
1177          * file that already has flags on it. XXX
1178          */
1179         if (extract->pst != NULL) {
1180                 /* Already have stat() data available. */
1181         } else if (fd >= 0 && fstat(fd, &extract->st) == 0)
1182                 extract->pst = &extract->st;
1183         else if (stat(name, &extract->st) == 0)
1184                 extract->pst = &extract->st;
1185         else {
1186                 archive_set_error(a, errno,
1187                     "Couldn't stat file");
1188                 return (ARCHIVE_WARN);
1189         }
1190
1191         extract->st.st_flags &= ~clear;
1192         extract->st.st_flags |= set;
1193 #ifdef HAVE_FCHFLAGS
1194         /* If platform has fchflags() and we were given an fd, use it. */
1195         if (fd >= 0 && fchflags(fd, extract->st.st_flags) == 0)
1196                 return (ARCHIVE_OK);
1197 #endif
1198         /*
1199          * If we can't use the fd to set the flags, we'll use the
1200          * pathname to set flags.  We prefer lchflags() but will use
1201          * chflags() if we must.
1202          */
1203 #ifdef HAVE_LCHFLAGS
1204         if (lchflags(name, extract->st.st_flags) == 0)
1205                 return (ARCHIVE_OK);
1206 #elif defined(HAVE_CHFLAGS)
1207         if (chflags(name, extract->st.st_flags) == 0)
1208                 return (ARCHIVE_OK);
1209 #endif
1210         archive_set_error(a, errno,
1211             "Failed to set file flags");
1212         return (ARCHIVE_WARN);
1213 }
1214
1215 #elif defined(__linux) && defined(EXT2_IOC_GETFLAGS) && defined(EXT2_IOC_SETFLAGS)
1216
1217 /*
1218  * Linux has flags too, but uses ioctl() to access them instead of
1219  * having a separate chflags() system call.
1220  */
1221 static int
1222 set_fflags(struct archive *a, int fd, const char *name, mode_t mode,
1223     unsigned long set, unsigned long clear)
1224 {
1225         struct extract *extract;
1226         int              ret;
1227         int              myfd = fd;
1228         unsigned long newflags, oldflags;
1229         unsigned long sf_mask = 0;
1230
1231         extract = a->extract;
1232         if (set == 0  && clear == 0)
1233                 return (ARCHIVE_OK);
1234         /* Only regular files and dirs can have flags. */
1235         if (!S_ISREG(mode) && !S_ISDIR(mode))
1236                 return (ARCHIVE_OK);
1237
1238         /* If we weren't given an fd, open it ourselves. */
1239         if (myfd < 0)
1240                 myfd = open(name, O_RDONLY|O_NONBLOCK);
1241         if (myfd < 0)
1242                 return (ARCHIVE_OK);
1243
1244         /*
1245          * Linux has no define for the flags that are only settable by
1246          * the root user.  This code may seem a little complex, but
1247          * there seem to be some Linux systems that lack these
1248          * defines. (?)  The code below degrades reasonably gracefully
1249          * if sf_mask is incomplete.
1250          */
1251 #ifdef EXT2_IMMUTABLE_FL
1252         sf_mask |= EXT2_IMMUTABLE_FL;
1253 #endif
1254 #ifdef EXT2_APPEND_FL
1255         sf_mask |= EXT2_APPEND_FL;
1256 #endif
1257         /*
1258          * XXX As above, this would be way simpler if we didn't have
1259          * to read the current flags from disk. XXX
1260          */
1261         ret = ARCHIVE_OK;
1262         /* Try setting the flags as given. */
1263         if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1264                 newflags = (oldflags & ~clear) | set;
1265                 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1266                         goto cleanup;
1267                 if (errno != EPERM)
1268                         goto fail;
1269         }
1270         /* If we couldn't set all the flags, try again with a subset. */
1271         if (ioctl(myfd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1272                 newflags &= ~sf_mask;
1273                 oldflags &= sf_mask;
1274                 newflags |= oldflags;
1275                 if (ioctl(myfd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1276                         goto cleanup;
1277         }
1278         /* We couldn't set the flags, so report the failure. */
1279 fail:
1280         archive_set_error(a, errno,
1281             "Failed to set file flags");
1282         ret = ARCHIVE_WARN;
1283 cleanup:
1284         if (fd < 0)
1285                 close(myfd);
1286         return (ret);
1287 }
1288
1289 #else /* Not HAVE_CHFLAGS && Not __linux */
1290
1291 /*
1292  * Of course, some systems have neither BSD chflags() nor Linux' flags
1293  * support through ioctl().
1294  */
1295 static int
1296 set_fflags(struct archive *a, int fd, const char *name, mode_t mode,
1297     unsigned long set, unsigned long clear)
1298 {
1299         (void)a;
1300         (void)fd;
1301         (void)name;
1302         (void)mode;
1303         (void)set;
1304         (void)clear;
1305         return (ARCHIVE_OK);
1306 }
1307
1308 #endif /* __linux */
1309
1310 #ifndef HAVE_POSIX_ACL
1311 /* Default empty function body to satisfy mainline code. */
1312 static int
1313 set_acls(struct archive *a, int fd, struct archive_entry *entry)
1314 {
1315         (void)a;
1316         (void)fd;
1317         (void)entry;
1318
1319         return (ARCHIVE_OK);
1320 }
1321
1322 #else
1323
1324 /*
1325  * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
1326  */
1327 static int
1328 set_acls(struct archive *a, int fd, struct archive_entry *entry)
1329 {
1330         int              ret;
1331
1332         ret = set_acl(a, fd, entry, ACL_TYPE_ACCESS,
1333             ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
1334         if (ret != ARCHIVE_OK)
1335                 return (ret);
1336         ret = set_acl(a, fd, entry, ACL_TYPE_DEFAULT,
1337             ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
1338         return (ret);
1339 }
1340
1341
1342 static int
1343 set_acl(struct archive *a, int fd, struct archive_entry *entry,
1344     acl_type_t acl_type, int ae_requested_type, const char *typename)
1345 {
1346         acl_t            acl;
1347         acl_entry_t      acl_entry;
1348         acl_permset_t    acl_permset;
1349         int              ret;
1350         int              ae_type, ae_permset, ae_tag, ae_id;
1351         uid_t            ae_uid;
1352         gid_t            ae_gid;
1353         const char      *ae_name;
1354         int              entries;
1355         const char      *name;
1356
1357         ret = ARCHIVE_OK;
1358         entries = archive_entry_acl_reset(entry, ae_requested_type);
1359         if (entries == 0)
1360                 return (ARCHIVE_OK);
1361         acl = acl_init(entries);
1362         while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
1363                    &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
1364                 acl_create_entry(&acl, &acl_entry);
1365
1366                 switch (ae_tag) {
1367                 case ARCHIVE_ENTRY_ACL_USER:
1368                         acl_set_tag_type(acl_entry, ACL_USER);
1369                         ae_uid = lookup_uid(a, ae_name, ae_id);
1370                         acl_set_qualifier(acl_entry, &ae_uid);
1371                         break;
1372                 case ARCHIVE_ENTRY_ACL_GROUP:
1373                         acl_set_tag_type(acl_entry, ACL_GROUP);
1374                         ae_gid = lookup_gid(a, ae_name, ae_id);
1375                         acl_set_qualifier(acl_entry, &ae_gid);
1376                         break;
1377                 case ARCHIVE_ENTRY_ACL_USER_OBJ:
1378                         acl_set_tag_type(acl_entry, ACL_USER_OBJ);
1379                         break;
1380                 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
1381                         acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
1382                         break;
1383                 case ARCHIVE_ENTRY_ACL_MASK:
1384                         acl_set_tag_type(acl_entry, ACL_MASK);
1385                         break;
1386                 case ARCHIVE_ENTRY_ACL_OTHER:
1387                         acl_set_tag_type(acl_entry, ACL_OTHER);
1388                         break;
1389                 default:
1390                         /* XXX */
1391                         break;
1392                 }
1393
1394                 acl_get_permset(acl_entry, &acl_permset);
1395                 acl_clear_perms(acl_permset);
1396                 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
1397                         acl_add_perm(acl_permset, ACL_EXECUTE);
1398                 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
1399                         acl_add_perm(acl_permset, ACL_WRITE);
1400                 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
1401                         acl_add_perm(acl_permset, ACL_READ);
1402         }
1403
1404         name = archive_entry_pathname(entry);
1405
1406         /* Try restoring the ACL through 'fd' if we can. */
1407 #if HAVE_ACL_SET_FD
1408         if (fd >= 0 && acl_type == ACL_TYPE_ACCESS && acl_set_fd(fd, acl) == 0)
1409                 ret = ARCHIVE_OK;
1410         else
1411 #else
1412 #if HAVE_ACL_SET_FD_NP
1413         if (fd >= 0 && acl_set_fd_np(fd, acl, acl_type) == 0)
1414                 ret = ARCHIVE_OK;
1415         else
1416 #endif
1417 #endif
1418         if (acl_set_file(name, acl_type, acl) != 0) {
1419                 archive_set_error(a, errno, "Failed to set %s acl", typename);
1420                 ret = ARCHIVE_WARN;
1421         }
1422         acl_free(acl);
1423         return (ret);
1424 }
1425 #endif
1426
1427 #if HAVE_LSETXATTR
1428 /*
1429  * Restore extended attributes -  Linux implementation
1430  */
1431 static int
1432 set_xattrs(struct archive *a, int fd, struct archive_entry *entry)
1433 {
1434         static int warning_done = 0;
1435         int ret = ARCHIVE_OK;
1436         int i = archive_entry_xattr_reset(entry);
1437
1438         while (i--) {
1439                 const char *name;
1440                 const void *value;
1441                 size_t size;
1442                 archive_entry_xattr_next(entry, &name, &value, &size);
1443                 if (name != NULL &&
1444                                 strncmp(name, "xfsroot.", 8) != 0 &&
1445                                 strncmp(name, "system.", 7) != 0) {
1446                         int e;
1447 #if HAVE_FSETXATTR
1448                         if (fd >= 0)
1449                                 e = fsetxattr(fd, name, value, size, 0);
1450                         else
1451 #endif
1452                         {
1453                                 e = lsetxattr(archive_entry_pathname(entry),
1454                                     name, value, size, 0);
1455                         }
1456                         if (e == -1) {
1457                                 if (errno == ENOTSUP) {
1458                                         if (!warning_done) {
1459                                                 warning_done = 1;
1460                                                 archive_set_error(a, errno,
1461                                                     "Cannot restore extended "
1462                                                     "attributes on this file "
1463                                                     "system");
1464                                         }
1465                                 } else
1466                                         archive_set_error(a, errno,
1467                                             "Failed to set extended attribute");
1468                                 ret = ARCHIVE_WARN;
1469                         }
1470                 } else {
1471                         archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1472                             "Invalid extended attribute encountered");
1473                         ret = ARCHIVE_WARN;
1474                 }
1475         }
1476         return (ret);
1477 }
1478 #else
1479 /*
1480  * Restore extended attributes - stub implementation for unsupported systems
1481  */
1482 static int
1483 set_xattrs(struct archive *a, int fd, struct archive_entry *entry)
1484 {
1485         static int warning_done = 0;
1486         (void)a; /* UNUSED */
1487         (void)fd; /* UNUSED */
1488
1489         /* If there aren't any extended attributes, then it's okay not
1490          * to extract them, otherwise, issue a single warning. */
1491         if (archive_entry_xattr_count(entry) != 0 && !warning_done) {
1492                 warning_done = 1;
1493                 archive_set_error(a, ARCHIVE_ERRNO_FILE_FORMAT,
1494                     "Cannot restore extended attributes on this system");
1495                 return (ARCHIVE_WARN);
1496         }
1497         /* Warning was already emitted; suppress further warnings. */
1498         return (ARCHIVE_OK);
1499 }
1500 #endif
1501
1502 /*
1503  * The following routines do some basic caching of uname/gname
1504  * lookups.  All such lookups go through these routines, including ACL
1505  * conversions.  Even a small cache here provides an enormous speedup,
1506  * especially on systems using NIS, LDAP, or a similar networked
1507  * directory system.
1508  *
1509  * TODO: Provide an API for clients to override these routines.
1510  */
1511 static gid_t
1512 lookup_gid(struct archive *a, const char *gname, gid_t gid)
1513 {
1514         struct group    *grent;
1515         struct extract *extract;
1516         int h;
1517         struct bucket *b;
1518         int cache_size;
1519
1520         extract = a->extract;
1521         cache_size = sizeof(extract->gcache) / sizeof(extract->gcache[0]);
1522
1523         /* If no gname, just use the gid provided. */
1524         if (gname == NULL || *gname == '\0')
1525                 return (gid);
1526
1527         /* Try to find gname in the cache. */
1528         h = hash(gname);
1529         b = &extract->gcache[h % cache_size ];
1530         if (b->name != NULL && b->hash == h && strcmp(gname, b->name) == 0)
1531                 return ((gid_t)b->id);
1532
1533         /* Free the cache slot for a new entry. */
1534         if (b->name != NULL)
1535                 free(b->name);
1536         b->name = strdup(gname);
1537         /* Note: If strdup fails, that's okay; we just won't cache. */
1538         b->hash = h;
1539         grent = getgrnam(gname);
1540         if (grent != NULL)
1541                 gid = grent->gr_gid;
1542         b->id = gid;
1543
1544         return (gid);
1545 }
1546
1547 static uid_t
1548 lookup_uid(struct archive *a, const char *uname, uid_t uid)
1549 {
1550         struct passwd   *pwent;
1551         struct extract *extract;
1552         int h;
1553         struct bucket *b;
1554         int cache_size;
1555
1556         extract = a->extract;
1557         cache_size = sizeof(extract->ucache) / sizeof(extract->ucache[0]);
1558
1559         /* If no uname, just use the uid provided. */
1560         if (uname == NULL || *uname == '\0')
1561                 return (uid);
1562
1563         /* Try to find uname in the cache. */
1564         h = hash(uname);
1565         b = &extract->ucache[h % cache_size ];
1566         if (b->name != NULL && b->hash == h && strcmp(uname, b->name) == 0)
1567                 return ((uid_t)b->id);
1568
1569         /* Free the cache slot for a new entry. */
1570         if (b->name != NULL)
1571                 free(b->name);
1572         b->name = strdup(uname);
1573         /* Note: If strdup fails, that's okay; we just won't cache. */
1574         b->hash = h;
1575         pwent = getpwnam(uname);
1576         if (pwent != NULL)
1577                 uid = pwent->pw_uid;
1578         b->id = uid;
1579
1580         return (uid);
1581 }
1582
1583 static unsigned int
1584 hash(const char *p)
1585 {
1586         /* A 32-bit version of Peter Weinberger's (PJW) hash algorithm,
1587            as used by ELF for hashing function names. */
1588         unsigned g, h = 0;
1589         while (*p != '\0') {
1590                 h = ( h << 4 ) + *p++;
1591                 if (( g = h & 0xF0000000 )) {
1592                         h ^= g >> 24;
1593                         h &= 0x0FFFFFFF;
1594                 }
1595         }
1596         return h;
1597 }
1598
1599 void
1600 archive_read_extract_set_progress_callback(struct archive *a,
1601     void (*progress_func)(void *), void *user_data)
1602 {
1603         a->extract_progress = progress_func;
1604         a->extract_progress_user_data = user_data;
1605 }