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