Merge from vendor branch HEIMDAL:
[dragonfly.git] / contrib / libarchive / archive_read_extract.c
1 /*-
2  * Copyright (c) 2003-2004 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.36 2004/11/05 05:16:40 kientzle Exp $");
29
30 #include <sys/types.h>
31 #ifdef HAVE_SYS_ACL_H
32 #include <sys/acl.h>
33 #endif
34 #ifdef HAVE_SYS_IOCTL_H
35 #include <sys/ioctl.h>
36 #endif
37 #include <sys/stat.h>
38 #include <sys/time.h>
39
40 #ifdef HAVE_EXT2FS_EXT2_FS_H
41 #include <ext2fs/ext2_fs.h>     /* for Linux file flags */
42 #endif
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <grp.h>
46 #ifdef HAVE_LINUX_EXT2_FS_H
47 #include <linux/ext2_fs.h>      /* for Linux file flags */
48 #endif
49 #include <limits.h>
50 #include <pwd.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <unistd.h>
55
56 #include "archive.h"
57 #include "archive_string.h"
58 #include "archive_entry.h"
59 #include "archive_private.h"
60
61 struct fixup_entry {
62         struct fixup_entry      *next;
63         mode_t                   mode;
64         int64_t                  mtime;
65         int64_t                  atime;
66         unsigned long            mtime_nanos;
67         unsigned long            atime_nanos;
68         unsigned long            fflags_set;
69         int                      fixup; /* bitmask of what needs fixing */
70         char                    *name;
71 };
72
73 #define FIXUP_MODE      1
74 #define FIXUP_TIMES     2
75 #define FIXUP_FFLAGS    4
76
77 struct bucket {
78         char    *name;
79         int      hash;
80         id_t     id;
81 };
82
83 struct extract {
84         mode_t                   umask;
85         mode_t                   default_dir_mode;
86         struct archive_string    create_parent_dir;
87         struct fixup_entry      *fixup_list;
88         struct fixup_entry      *current_fixup;
89
90         struct bucket ucache[127];
91         struct bucket gcache[127];
92
93         /*
94          * Cached stat data from disk for the current entry.
95          * If this is valid, pst points to st.  Otherwise,
96          * pst is null.
97          *
98          * TODO: Have all of the stat calls use this cached data
99          * if possible.
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 void     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_parent_dir(struct archive *, const char *, int flags);
129 static int      create_parent_dir_internal(struct archive *, char *,
130                     int flags);
131 static int      create_parent_dir_recursive(struct archive *, char *,
132                     int flags);
133 static int      restore_metadata(struct archive *, struct archive_entry *,
134                     int flags);
135 #ifdef HAVE_POSIX_ACL
136 static int      set_acl(struct archive *, struct archive_entry *,
137                     acl_type_t, int archive_entry_acl_type, const char *tn);
138 #endif
139 static int      set_acls(struct archive *, struct archive_entry *);
140 static int      set_fflags(struct archive *, const char *name, mode_t mode,
141                     unsigned long fflags_set, unsigned long fflags_clear);
142 static int      set_ownership(struct archive *, struct archive_entry *, int);
143 static int      set_perm(struct archive *, struct archive_entry *, int mode,
144                     int flags);
145 static int      set_time(struct archive *, struct archive_entry *, int);
146 static struct fixup_entry *sort_dir_list(struct fixup_entry *p);
147
148
149 /*
150  * Extract this entry to disk.
151  *
152  * TODO: Validate hardlinks.  According to the standards, we're
153  * supposed to check each extracted hardlink and squawk if it refers
154  * to a file that we didn't restore.  I'm not entirely convinced this
155  * is a good idea, but more importantly: Is there any way to validate
156  * hardlinks without keeping a complete list of filenames from the
157  * entire archive?? Ugh.
158  *
159  */
160 int
161 archive_read_extract(struct archive *a, struct archive_entry *entry, int flags)
162 {
163         mode_t mode;
164         struct extract *extract;
165         int ret;
166         int restore_pwd;
167
168         if (a->extract == NULL) {
169                 a->extract = malloc(sizeof(*a->extract));
170                 if (a->extract == NULL) {
171                         archive_set_error(a, ENOMEM, "Can't extract");
172                         return (ARCHIVE_FATAL);
173                 }
174                 a->cleanup_archive_extract = archive_extract_cleanup;
175                 memset(a->extract, 0, sizeof(*a->extract));
176         }
177         extract = a->extract;
178         umask(extract->umask = umask(0)); /* Read the current umask. */
179         extract->default_dir_mode = DEFAULT_DIR_MODE & ~extract->umask;
180         extract->pst = NULL;
181         extract->current_fixup = NULL;
182         restore_pwd = -1;
183
184         /*
185          * TODO: If pathname is longer than PATH_MAX, record starting
186          * directory and move to a suitable intermediate dir, which
187          * might require creating them!
188          */
189         if (strlen(archive_entry_pathname(entry)) > PATH_MAX) {
190                 restore_pwd = open(".", O_RDONLY);
191                 /* XXX chdir() to a suitable intermediate dir XXX */
192                 /* XXX Update pathname in 'entry' XXX */
193         }
194
195         if (stat(archive_entry_pathname(entry), &extract->st) == 0)
196                 extract->pst = &extract->st;
197
198         if (extract->pst != NULL &&
199             extract->pst->st_dev == a->skip_file_dev &&
200             extract->pst->st_ino == a->skip_file_ino) {
201                 archive_set_error(a, 0, "Refusing to overwrite archive");
202                 ret = ARCHIVE_WARN;
203         } else if (archive_entry_hardlink(entry) != NULL)
204                 ret = extract_hard_link(a, entry, flags);
205         else {
206                 mode = archive_entry_mode(entry);
207                 switch (mode & S_IFMT) {
208                 default:
209                         /* Fall through, as required by POSIX. */
210                 case S_IFREG:
211                         ret = extract_file(a, entry, flags);
212                         break;
213                 case S_IFLNK:   /* Symlink */
214                         ret = extract_symlink(a, entry, flags);
215                         break;
216                 case S_IFCHR:
217                         ret = extract_char_device(a, entry, flags);
218                         break;
219                 case S_IFBLK:
220                         ret = extract_block_device(a, entry, flags);
221                         break;
222                 case S_IFDIR:
223                         ret = extract_dir(a, entry, flags);
224                         break;
225                 case S_IFIFO:
226                         ret = extract_fifo(a, entry, flags);
227                         break;
228                 }
229         }
230
231         /* If we changed directory above, restore it here. */
232         if (restore_pwd >= 0)
233                 fchdir(restore_pwd);
234
235         return (ret);
236 }
237
238 /*
239  * Cleanup function for archive_extract.  Mostly, this involves processing
240  * the fixup list, which is used to address a number of problems:
241  *   * Dir permissions might prevent us from restoring a file in that
242  *     dir, so we restore the dir 0700 first, then correct the
243  *     mode at the end.
244  *   * Similarly, the act of restoring a file touches the directory
245  *     and changes the timestamp on the dir, so we have to touch-up the
246  *     timestamps at the end as well.
247  *   * Some file flags can interfere with the restore by, for example,
248  *     preventing the creation of hardlinks to those files.
249  *
250  * Note that tar/cpio do not require that archives be in a particular
251  * order; there is no way to know when the last file has been restored
252  * within a directory, so there's no way to optimize the memory usage
253  * here by fixing up the directory any earlier than the
254  * end-of-archive.
255  *
256  * XXX TODO: Directory ACLs should be restored here, for the same
257  * reason we set directory perms here. XXX
258  *
259  * Registering this function (rather than calling it explicitly by
260  * name from archive_read_finish) reduces static link pollution, since
261  * applications that don't use this API won't get this file linked in.
262  */
263 static void
264 archive_extract_cleanup(struct archive *a)
265 {
266         struct fixup_entry *next, *p;
267         struct extract *extract;
268
269         /* Sort dir list so directories are fixed up in depth-first order. */
270         extract = a->extract;
271         p = sort_dir_list(extract->fixup_list);
272
273         while (p != NULL) {
274                 extract->pst = NULL; /* Mark stat buff as out-of-date. */
275                 if (p->fixup & FIXUP_TIMES) {
276                         struct timeval times[2];
277                         times[1].tv_sec = p->mtime;
278                         times[1].tv_usec = p->mtime_nanos / 1000;
279                         times[0].tv_sec = p->atime;
280                         times[0].tv_usec = p->atime_nanos / 1000;
281                         utimes(p->name, times);
282                 }
283                 if (p->fixup & FIXUP_MODE)
284                         chmod(p->name, p->mode);
285
286                 if (p->fixup & FIXUP_FFLAGS)
287                         set_fflags(a, p->name, p->mode, p->fflags_set, 0);
288
289                 next = p->next;
290                 free(p->name);
291                 free(p);
292                 p = next;
293         }
294         extract->fixup_list = NULL;
295         archive_string_free(&extract->create_parent_dir);
296         free(a->extract);
297         a->extract = NULL;
298 }
299
300 /*
301  * Simple O(n log n) merge sort to order the fixup list.  In
302  * particular, we want to restore dir timestamps depth-first.
303  */
304 static struct fixup_entry *
305 sort_dir_list(struct fixup_entry *p)
306 {
307         struct fixup_entry *a, *b, *t;
308
309         if (p == NULL)
310                 return (NULL);
311         /* A one-item list is already sorted. */
312         if (p->next == NULL)
313                 return (p);
314
315         /* Step 1: split the list. */
316         t = p;
317         a = p->next->next;
318         while (a != NULL) {
319                 /* Step a twice, t once. */
320                 a = a->next;
321                 if (a != NULL)
322                         a = a->next;
323                 t = t->next;
324         }
325         /* Now, t is at the mid-point, so break the list here. */
326         b = t->next;
327         t->next = NULL;
328         a = p;
329
330         /* Step 2: Recursively sort the two sub-lists. */
331         a = sort_dir_list(a);
332         b = sort_dir_list(b);
333
334         /* Step 3: Merge the returned lists. */
335         /* Pick the first element for the merged list. */
336         if (strcmp(a->name, b->name) > 0) {
337                 t = p = a;
338                 a = a->next;
339         } else {
340                 t = p = b;
341                 b = b->next;
342         }
343
344         /* Always put the later element on the list first. */
345         while (a != NULL && b != NULL) {
346                 if (strcmp(a->name, b->name) > 0) {
347                         t->next = a;
348                         a = a->next;
349                 } else {
350                         t->next = b;
351                         b = b->next;
352                 }
353                 t = t->next;
354         }
355
356         /* Only one list is non-empty, so just splice it on. */
357         if (a != NULL)
358                 t->next = a;
359         if (b != NULL)
360                 t->next = b;
361
362         return (p);
363 }
364
365 /*
366  * Returns a new, initialized fixup entry.
367  */
368 static struct fixup_entry *
369 new_fixup(struct archive *a, const char *pathname)
370 {
371         struct extract *extract;
372         struct fixup_entry *fe;
373
374         extract = a->extract;
375         fe = malloc(sizeof(struct fixup_entry));
376         if (fe == NULL)
377                 return (NULL);
378         fe->next = extract->fixup_list;
379         extract->fixup_list = fe;
380         fe->fixup = 0;
381         fe->name = strdup(pathname);
382         return (fe);
383 }
384
385 /*
386  * Returns a fixup structure for the current entry.
387  */
388 static struct fixup_entry *
389 current_fixup(struct archive *a, const char *pathname)
390 {
391         struct extract *extract;
392
393         extract = a->extract;
394         if (extract->current_fixup == NULL)
395                 extract->current_fixup = new_fixup(a, pathname);
396         return (extract->current_fixup);
397 }
398
399 static int
400 extract_file(struct archive *a, struct archive_entry *entry, int flags)
401 {
402         struct extract *extract;
403         const char *name;
404         mode_t mode;
405         int fd, r, r2;
406
407         extract = a->extract;
408         name = archive_entry_pathname(entry);
409         mode = archive_entry_mode(entry) & 0777;
410         r = ARCHIVE_OK;
411
412         /*
413          * If we're not supposed to overwrite pre-existing files,
414          * use O_EXCL.  Otherwise, use O_TRUNC.
415          */
416         if (flags & (ARCHIVE_EXTRACT_UNLINK | ARCHIVE_EXTRACT_NO_OVERWRITE))
417                 fd = open(name, O_WRONLY | O_CREAT | O_EXCL, mode);
418         else
419                 fd = open(name, O_WRONLY | O_CREAT | O_TRUNC, mode);
420
421         /* Try removing a pre-existing file. */
422         if (fd < 0 && !(flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
423                 unlink(name);
424                 fd = open(name, O_WRONLY | O_CREAT | O_EXCL, mode);
425         }
426
427         /* Might be a non-existent parent dir; try fixing that. */
428         if (fd < 0) {
429                 create_parent_dir(a, name, flags);
430                 fd = open(name, O_WRONLY | O_CREAT | O_EXCL, mode);
431         }
432         if (fd < 0) {
433                 archive_set_error(a, errno, "Can't open '%s'", name);
434                 return (ARCHIVE_WARN);
435         }
436         r = archive_read_data_into_fd(a, fd);
437         extract->pst = NULL; /* Cached stat data no longer valid. */
438         r2 = restore_metadata(a, entry, flags);
439         close(fd);
440         return (err_combine(r, r2));
441 }
442
443 static int
444 extract_dir(struct archive *a, struct archive_entry *entry, int flags)
445 {
446         struct extract *extract;
447         struct fixup_entry *fe;
448         char *path, *p;
449
450         extract = a->extract;
451         extract->pst = NULL; /* Invalidate cached stat data. */
452
453         /* Copy path to mutable storage. */
454         archive_strcpy(&(extract->create_parent_dir),
455             archive_entry_pathname(entry));
456         path = extract->create_parent_dir.s;
457
458         /* Deal with any troublesome trailing path elements. */
459         for (;;) {
460                 if (*path == '\0')
461                         return (ARCHIVE_OK);
462                 /* Locate last element; trim trailing '/'. */
463                 p = strrchr(path, '/');
464                 if (p != NULL) {
465                         if (p[1] == '\0') {
466                                 *p = '\0';
467                                 continue;
468                         }
469                         p++;
470                 } else
471                         p = path;
472                 /* Trim trailing '.'. */
473                 if (p[0] == '.' && p[1] == '\0') {
474                         p[0] = '\0';
475                         continue;
476                 }
477                 /* Just exit on trailing '..'. */
478                 if (p[0] == '.' && p[1] == '.' && p[2] == '\0')
479                         return (ARCHIVE_OK);
480                 break;
481         }
482
483         if (mkdir(path, SECURE_DIR_MODE) == 0)
484                 goto success;
485
486         if (extract->pst == NULL && stat(path, &extract->st) == 0)
487                 extract->pst = &extract->st;
488
489         if (extract->pst != NULL) {
490                 extract->pst = &extract->st;
491                 /* If dir already exists, don't reset permissions. */
492                 if (S_ISDIR(extract->pst->st_mode))
493                         return (ARCHIVE_OK);
494                 /* It exists but isn't a dir. */
495                 if ((flags & ARCHIVE_EXTRACT_UNLINK))
496                         unlink(path);
497         } else {
498                 /* Doesn't already exist; try building the parent path. */
499                 if (create_parent_dir_internal(a, path, flags) != ARCHIVE_OK)
500                         return (ARCHIVE_WARN);
501         }
502
503         /* One final attempt to create the dir. */
504         if (mkdir(path, SECURE_DIR_MODE) != 0) {
505                 archive_set_error(a, errno, "Can't create directory");
506                 return (ARCHIVE_WARN);
507         }
508
509 success:
510         /* Add this dir to the fixup list. */
511         fe = current_fixup(a, path);
512         fe->fixup |= FIXUP_MODE;
513         fe->mode = archive_entry_mode(entry);
514         if ((flags & ARCHIVE_EXTRACT_PERM) == 0)
515                 fe->mode &= ~extract->umask;
516         if (flags & ARCHIVE_EXTRACT_TIME) {
517                 fe->fixup |= FIXUP_TIMES;
518                 fe->mtime = archive_entry_mtime(entry);
519                 fe->mtime_nanos = archive_entry_mtime_nsec(entry);
520                 fe->atime = archive_entry_atime(entry);
521                 fe->atime_nanos = archive_entry_atime_nsec(entry);
522         }
523         /* For now, set the mode to SECURE_DIR_MODE. */
524         archive_entry_set_mode(entry, SECURE_DIR_MODE);
525         return (restore_metadata(a, entry, flags));
526 }
527
528
529 /*
530  * Create the parent of the specified path.  Copy the provided
531  * path into mutable storage first.
532  */
533 static int
534 create_parent_dir(struct archive *a, const char *path, int flags)
535 {
536         struct extract *extract;
537         int r;
538
539         extract = a->extract;
540
541         /* Copy path to mutable storage. */
542         archive_strcpy(&(extract->create_parent_dir), path);
543
544         r = create_parent_dir_internal(a, extract->create_parent_dir.s, flags);
545         return (r);
546 }
547
548 /*
549  * Handle remaining setup for create_parent_dir_recursive(), assuming
550  * path is already in mutable storage.
551  */
552 static int
553 create_parent_dir_internal(struct archive *a, char *path, int flags)
554 {
555         char *slash;
556         mode_t old_umask;
557         int r;
558
559         /* Remove tail element to obtain parent name. */
560         slash = strrchr(path, '/');
561         if (slash == NULL)
562                 return (ARCHIVE_OK);
563         *slash = '\0';
564         old_umask = umask(~SECURE_DIR_MODE);
565         r = create_parent_dir_recursive(a, path, flags);
566         umask(old_umask);
567         *slash = '/';
568         return (r);
569 }
570
571 /*
572  * Create the specified dir, recursing to create parents as necessary.
573  *
574  * Returns ARCHIVE_OK if the path exists when we're done here.
575  * Otherwise, returns ARCHIVE_WARN.
576  */
577 static int
578 create_parent_dir_recursive(struct archive *a, char *path, int flags)
579 {
580         struct stat st;
581         struct extract *extract;
582         struct fixup_entry *le;
583         char *slash, *base;
584         int r;
585
586         extract = a->extract;
587         r = ARCHIVE_OK;
588
589         /* Check for special names and just skip them. */
590         slash = strrchr(path, '/');
591         base = strrchr(path, '/');
592         if (slash == NULL)
593                 base = path;
594         else
595                 base = slash + 1;
596
597         if (base[0] == '\0' ||
598             (base[0] == '.' && base[1] == '\0') ||
599             (base[0] == '.' && base[1] == '.' && base[2] == '\0')) {
600                 /* Don't bother trying to create null path, '.', or '..'. */
601                 if (slash != NULL) {
602                         *slash = '\0';
603                         r = create_parent_dir_recursive(a, path, flags);
604                         *slash = '/';
605                         return (r);
606                 }
607                 return (ARCHIVE_OK);
608         }
609
610         /*
611          * Yes, this should be stat() and not lstat().  Using lstat()
612          * here loses the ability to extract through symlinks.  Also note
613          * that this should not use the extract->st cache.
614          */
615         if (stat(path, &st) == 0) {
616                 if (S_ISDIR(st.st_mode))
617                         return (ARCHIVE_OK);
618                 if ((flags & ARCHIVE_EXTRACT_NO_OVERWRITE)) {
619                         archive_set_error(a, EEXIST,
620                             "Can't create directory '%s'", path);
621                         return (ARCHIVE_WARN);
622                 }
623                 if (unlink(path) != 0) {
624                         archive_set_error(a, errno,
625                             "Can't create directory '%s': "
626                             "Conflicting file cannot be removed");
627                         return (ARCHIVE_WARN);
628                 }
629         } else if (errno != ENOENT && errno != ENOTDIR) {
630                 /* Stat failed? */
631                 archive_set_error(a, errno, "Can't test directory '%s'", path);
632                 return (ARCHIVE_WARN);
633         } else if (slash != NULL) {
634                 *slash = '\0';
635                 r = create_parent_dir_recursive(a, path, flags);
636                 *slash = '/';
637                 if (r != ARCHIVE_OK)
638                         return (r);
639         }
640
641         if (mkdir(path, SECURE_DIR_MODE) == 0) {
642                 le = new_fixup(a, path);
643                 le->fixup |= FIXUP_MODE;
644                 le->mode = extract->default_dir_mode;
645                 return (ARCHIVE_OK);
646         }
647
648         /*
649          * Without the following check, a/b/../b/c/d fails at the
650          * second visit to 'b', so 'd' can't be created.  Note that we
651          * don't add it to the fixup list here, as it's already been
652          * added.
653          */
654         if (stat(path, &st) == 0 && S_ISDIR(st.st_mode))
655                 return (ARCHIVE_OK);
656
657         archive_set_error(a, errno, "Failed to create dir '%s'", path);
658         return (ARCHIVE_WARN);
659 }
660
661 static int
662 extract_hard_link(struct archive *a, struct archive_entry *entry, int flags)
663 {
664         struct extract *extract;
665         int r;
666         const char *pathname;
667         const char *linkname;
668
669         extract = a->extract;
670         pathname = archive_entry_pathname(entry);
671         linkname = archive_entry_hardlink(entry);
672
673         /* Just remove any pre-existing file with this name. */
674         if (!(flags & ARCHIVE_EXTRACT_NO_OVERWRITE))
675                 unlink(pathname);
676
677         r = link(linkname, pathname);
678         extract->pst = NULL; /* Invalidate cached stat data. */
679
680         if (r != 0) {
681                 /* Might be a non-existent parent dir; try fixing that. */
682                 create_parent_dir(a, pathname, flags);
683                 r = link(linkname, pathname);
684         }
685
686         if (r != 0) {
687                 /* XXX Better error message here XXX */
688                 archive_set_error(a, errno,
689                     "Can't restore hardlink to '%s'", linkname);
690                 return (ARCHIVE_WARN);
691         }
692
693         /* Set ownership, time, permission information. */
694         r = restore_metadata(a, entry, flags);
695         return (r);
696 }
697
698 static int
699 extract_symlink(struct archive *a, struct archive_entry *entry, int flags)
700 {
701         struct extract *extract;
702         int r;
703         const char *pathname;
704         const char *linkname;
705
706         extract = a->extract;
707         pathname = archive_entry_pathname(entry);
708         linkname = archive_entry_symlink(entry);
709
710         /* Just remove any pre-existing file with this name. */
711         if (!(flags & ARCHIVE_EXTRACT_NO_OVERWRITE))
712                 unlink(pathname);
713
714         r = symlink(linkname, pathname);
715         extract->pst = NULL; /* Invalidate cached stat data. */
716
717         if (r != 0) {
718                 /* Might be a non-existent parent dir; try fixing that. */
719                 create_parent_dir(a, pathname, flags);
720                 r = symlink(linkname, pathname);
721         }
722
723         if (r != 0) {
724                 /* XXX Better error message here XXX */
725                 archive_set_error(a, errno,
726                     "Can't restore symlink to '%s'", linkname);
727                 return (ARCHIVE_WARN);
728         }
729
730         r = restore_metadata(a, entry, flags);
731         return (r);
732 }
733
734 static int
735 extract_device(struct archive *a, struct archive_entry *entry,
736     int flags, mode_t mode)
737 {
738         struct extract *extract;
739         int r;
740
741         extract = a->extract;
742         /* Just remove any pre-existing file with this name. */
743         if (!(flags & ARCHIVE_EXTRACT_NO_OVERWRITE))
744                 unlink(archive_entry_pathname(entry));
745
746         r = mknod(archive_entry_pathname(entry), mode,
747             archive_entry_rdev(entry));
748         extract->pst = NULL; /* Invalidate cached stat data. */
749
750         /* Might be a non-existent parent dir; try fixing that. */
751         if (r != 0 && errno == ENOENT) {
752                 create_parent_dir(a, archive_entry_pathname(entry), flags);
753                 r = mknod(archive_entry_pathname(entry), mode,
754                     archive_entry_rdev(entry));
755         }
756
757         if (r != 0) {
758                 archive_set_error(a, errno, "Can't restore device node");
759                 return (ARCHIVE_WARN);
760         }
761
762         r = restore_metadata(a, entry, flags);
763         return (r);
764 }
765
766 static int
767 extract_char_device(struct archive *a, struct archive_entry *entry, int flags)
768 {
769         mode_t mode;
770
771         mode = (archive_entry_mode(entry) & ~S_IFMT) | S_IFCHR;
772         return (extract_device(a, entry, flags, mode));
773 }
774
775 static int
776 extract_block_device(struct archive *a, struct archive_entry *entry, int flags)
777 {
778         mode_t mode;
779
780         mode = (archive_entry_mode(entry) & ~S_IFMT) | S_IFBLK;
781         return (extract_device(a, entry, flags, mode));
782 }
783
784 static int
785 extract_fifo(struct archive *a, struct archive_entry *entry, int flags)
786 {
787         struct extract *extract;
788         int r;
789
790         extract = a->extract;
791         /* Just remove any pre-existing file with this name. */
792         if (!(flags & ARCHIVE_EXTRACT_NO_OVERWRITE))
793                 unlink(archive_entry_pathname(entry));
794
795         r = mkfifo(archive_entry_pathname(entry),
796             archive_entry_mode(entry));
797         extract->pst = NULL; /* Invalidate cached stat data. */
798
799         /* Might be a non-existent parent dir; try fixing that. */
800         if (r != 0 && errno == ENOENT) {
801                 create_parent_dir(a, archive_entry_pathname(entry), flags);
802                 r = mkfifo(archive_entry_pathname(entry),
803                     archive_entry_mode(entry));
804         }
805
806         if (r != 0) {
807                 archive_set_error(a, errno, "Can't restore fifo");
808                 return (ARCHIVE_WARN);
809         }
810
811         r = restore_metadata(a, entry, flags);
812         return (r);
813 }
814
815 static int
816 restore_metadata(struct archive *a, struct archive_entry *entry, int flags)
817 {
818         int r, r2;
819
820         r = set_ownership(a, entry, flags);
821         r2 = set_time(a, entry, flags);
822         r = err_combine(r, r2);
823         r2 = set_perm(a, entry, archive_entry_mode(entry), flags);
824         return (err_combine(r, r2));
825 }
826
827 static int
828 set_ownership(struct archive *a, struct archive_entry *entry, int flags)
829 {
830         uid_t uid;
831         gid_t gid;
832
833         /* Not changed. */
834         if ((flags & ARCHIVE_EXTRACT_OWNER) == 0)
835                 return (ARCHIVE_OK);
836
837         uid = lookup_uid(a, archive_entry_uname(entry),
838             archive_entry_uid(entry));
839         gid = lookup_gid(a, archive_entry_gname(entry),
840             archive_entry_gid(entry));
841
842         /* If we know we can't change it, don't bother trying. */
843         if (a->user_uid != 0  &&  a->user_uid != uid)
844                 return (ARCHIVE_OK);
845
846 #ifdef HAVE_LCHOWN
847         if (lchown(archive_entry_pathname(entry), uid, gid))
848 #else
849         if (!S_ISLNK(archive_entry_mode(entry))
850             && chown(archive_entry_pathname(entry), uid, gid) != 0)
851 #endif
852         {
853                 archive_set_error(a, errno,
854                     "Can't set user=%d/group=%d for %s", uid, gid,
855                     archive_entry_pathname(entry));
856                 return (ARCHIVE_WARN);
857         }
858         return (ARCHIVE_OK);
859 }
860
861 static int
862 set_time(struct archive *a, struct archive_entry *entry, int flags)
863 {
864         const struct stat *st;
865         struct timeval times[2];
866
867         (void)a; /* UNUSED */
868         st = archive_entry_stat(entry);
869
870         if ((flags & ARCHIVE_EXTRACT_TIME) == 0)
871                 return (ARCHIVE_OK);
872         /* It's a waste of time to mess with dir timestamps here. */
873         if (S_ISDIR(archive_entry_mode(entry)))
874                 return (ARCHIVE_OK);
875
876         times[1].tv_sec = st->st_mtime;
877         times[1].tv_usec = ARCHIVE_STAT_MTIME_NANOS(st) / 1000;
878
879         times[0].tv_sec = st->st_atime;
880         times[0].tv_usec = ARCHIVE_STAT_ATIME_NANOS(st) / 1000;
881
882 #ifdef HAVE_LUTIMES
883         if (lutimes(archive_entry_pathname(entry), times) != 0) {
884 #else
885         if ((archive_entry_mode(entry) & S_IFMT) != S_IFLNK &&
886             utimes(archive_entry_pathname(entry), times) != 0) {
887 #endif
888                 archive_set_error(a, errno, "Can't update time for %s",
889                     archive_entry_pathname(entry));
890                 return (ARCHIVE_WARN);
891         }
892
893         /*
894          * Note: POSIX does not provide a portable way to restore ctime.
895          * (Apart from resetting the system clock, which is distasteful.)
896          * So, any restoration of ctime will necessarily be OS-specific.
897          */
898
899         /* XXX TODO: Can FreeBSD restore ctime? XXX */
900
901         return (ARCHIVE_OK);
902 }
903
904 static int
905 set_perm(struct archive *a, struct archive_entry *entry, int mode, int flags)
906 {
907         struct extract *extract;
908         struct fixup_entry *le;
909         const char *name;
910         unsigned long    set, clear;
911         int              r;
912         int              critical_flags;
913
914         extract = a->extract;
915
916         /* Obey umask unless ARCHIVE_EXTRACT_PERM. */
917         if ((flags & ARCHIVE_EXTRACT_PERM) == 0)
918                 mode &= ~extract->umask; /* Enforce umask. */
919         name = archive_entry_pathname(entry);
920
921         if (mode & (S_ISUID | S_ISGID)) {
922                 if (extract->pst == NULL && stat(name, &extract->st) != 0) {
923                         archive_set_error(a, errno, "Can't check ownership");
924                         return (ARCHIVE_WARN);
925                 }
926                 extract->pst = &extract->st;
927                 /*
928                  * TODO: Use the uid/gid looked up in set_ownership
929                  * above rather than the uid/gid stored in the entry.
930                  */
931                 if (extract->pst->st_uid != archive_entry_uid(entry))
932                         mode &= ~ S_ISUID;
933                 if (extract->pst->st_gid != archive_entry_gid(entry))
934                         mode &= ~ S_ISGID;
935         }
936
937         /*
938          * Ensure we change permissions on the object we extracted,
939          * and not any incidental symlink that might have gotten in
940          * the way.
941          */
942         if (!S_ISLNK(archive_entry_mode(entry))) {
943                 if (chmod(name, mode) != 0) {
944                         archive_set_error(a, errno, "Can't set permissions");
945                         return (ARCHIVE_WARN);
946                 }
947 #ifdef HAVE_LCHMOD
948         } else {
949                 /*
950                  * If lchmod() isn't supported, it's no big deal.
951                  * Permissions on symlinks are actually ignored on
952                  * most platforms.
953                  */
954                 if (lchmod(name, mode) != 0) {
955                         archive_set_error(a, errno, "Can't set permissions");
956                         return (ARCHIVE_WARN);
957                 }
958 #endif
959         }
960
961         if (flags & ARCHIVE_EXTRACT_ACL) {
962                 r = set_acls(a, entry);
963                 if (r != ARCHIVE_OK)
964                         return (r);
965         }
966
967         /*
968          * Make 'critical_flags' hold all file flags that can't be
969          * immediately restored.  For example, on BSD systems,
970          * SF_IMMUTABLE prevents hardlinks from being created, so
971          * should not be set until after any hardlinks are created.  To
972          * preserve some semblance of portability, this uses #ifdef
973          * extensively.  Ugly, but it works.
974          *
975          * Yes, Virginia, this does create a security race.  It's mitigated
976          * somewhat by the practice of creating dirs 0700 until the extract
977          * is done, but it would be nice if we could do more than that.
978          * People restoring critical file systems should be wary of
979          * other programs that might try to muck with files as they're
980          * being restored.
981          */
982         /* Hopefully, the compiler will optimize this mess into a constant. */
983         critical_flags = 0;
984 #ifdef SF_IMMUTABLE
985         critical_flags |= SF_IMMUTABLE;
986 #endif
987 #ifdef UF_IMMUTABLE
988         critical_flags |= UF_IMMUTABLE;
989 #endif
990 #ifdef SF_APPEND
991         critical_flags |= SF_APPEND;
992 #endif
993 #ifdef UF_APPEND
994         critical_flags |= UF_APPEND;
995 #endif
996 #ifdef EXT2_APPEND_FL
997         critical_flags |= EXT2_APPEND_FL;
998 #endif
999 #ifdef EXT2_IMMUTABLE_FL
1000         critical_flags |= EXT2_IMMUTABLE_FL;
1001 #endif
1002
1003         if (flags & ARCHIVE_EXTRACT_FFLAGS) {
1004                 archive_entry_fflags(entry, &set, &clear);
1005
1006                 /*
1007                  * The first test encourages the compiler to eliminate
1008                  * all of this if it's not necessary.
1009                  */
1010                 if ((critical_flags != 0)  &&  (set & critical_flags)) {
1011                         le = current_fixup(a, archive_entry_pathname(entry));
1012                         le->fixup |= FIXUP_FFLAGS;
1013                         le->fflags_set = set;
1014                 } else {
1015                         r = set_fflags(a, archive_entry_pathname(entry),
1016                             archive_entry_mode(entry), set, clear);
1017                         if (r != ARCHIVE_OK)
1018                                 return (r);
1019                 }
1020         }
1021         return (ARCHIVE_OK);
1022 }
1023
1024 static int
1025 set_fflags(struct archive *a, const char *name, mode_t mode,
1026     unsigned long set, unsigned long clear)
1027 {
1028         struct extract *extract;
1029         int              ret;
1030 #ifdef linux
1031         int              fd;
1032         int              err;
1033         unsigned long newflags, oldflags;
1034 #endif
1035
1036         extract = a->extract;
1037         ret = ARCHIVE_OK;
1038         if (set == 0  && clear == 0)
1039                 return (ret);
1040
1041 #ifdef HAVE_CHFLAGS
1042         (void)mode; /* UNUSED */
1043         /*
1044          * XXX Is the stat here really necessary?  Or can I just use
1045          * the 'set' flags directly?  In particular, I'm not sure
1046          * about the correct approach if we're overwriting an existing
1047          * file that already has flags on it. XXX
1048          */
1049         if (stat(name, &extract->st) == 0) {
1050                 extract->st.st_flags &= ~clear;
1051                 extract->st.st_flags |= set;
1052                 if (chflags(name, extract->st.st_flags) != 0) {
1053                         archive_set_error(a, errno,
1054                             "Failed to set file flags");
1055                         ret = ARCHIVE_WARN;
1056                 }
1057                 extract->pst = &extract->st;
1058         }
1059 #else
1060 #ifdef linux
1061         /* Linux has flags too, but no chflags syscall */
1062         /*
1063          * Linux has no define for the flags that are only settable
1064          * by the root user...
1065          */
1066 #define SF_MASK                 (EXT2_IMMUTABLE_FL|EXT2_APPEND_FL)
1067
1068         /*
1069          * XXX As above, this would be way simpler if we didn't have
1070          * to read the current flags from disk. XXX
1071          */
1072         if ((S_ISREG(mode) || S_ISDIR(mode)) &&
1073             ((fd = open(name, O_RDONLY|O_NONBLOCK)) >= 0)) {
1074                 err = 1;
1075                 if (fd >= 0 && (ioctl(fd, EXT2_IOC_GETFLAGS, &oldflags) >= 0)) {
1076                         newflags = (oldflags & ~clear) | set;
1077                         if (ioctl(fd, EXT2_IOC_SETFLAGS, &newflags) >= 0) {
1078                                 err = 0;
1079                         } else if (errno == EPERM) {
1080                                 if (ioctl(fd, EXT2_IOC_GETFLAGS, &oldflags) >= 0) {
1081                                         newflags &= ~SF_MASK;
1082                                         oldflags &= SF_MASK;
1083                                         newflags |= oldflags;
1084                                         if (ioctl(fd, EXT2_IOC_SETFLAGS, &newflags) >= 0)
1085                                                 err = 0;
1086                                 }
1087                         }
1088                 }
1089                 close(fd);
1090                 if (err) {
1091                         archive_set_error(a, errno,
1092                             "Failed to set file flags");
1093                         ret = ARCHIVE_WARN;
1094                 }
1095         }
1096 #endif /* linux */
1097 #endif /* HAVE_CHFLAGS */
1098
1099         return (ret);
1100 }
1101
1102 #ifndef HAVE_POSIX_ACL
1103 /* Default empty function body to satisfy mainline code. */
1104 static int
1105 set_acls(struct archive *a, struct archive_entry *entry)
1106 {
1107         (void)a;
1108         (void)entry;
1109
1110         return (ARCHIVE_OK);
1111 }
1112
1113 #else
1114
1115 /*
1116  * XXX TODO: What about ACL types other than ACCESS and DEFAULT?
1117  */
1118 static int
1119 set_acls(struct archive *a, struct archive_entry *entry)
1120 {
1121         int              ret;
1122
1123         ret = set_acl(a, entry, ACL_TYPE_ACCESS,
1124             ARCHIVE_ENTRY_ACL_TYPE_ACCESS, "access");
1125         if (ret != ARCHIVE_OK)
1126                 return (ret);
1127         ret = set_acl(a, entry, ACL_TYPE_DEFAULT,
1128             ARCHIVE_ENTRY_ACL_TYPE_DEFAULT, "default");
1129         return (ret);
1130 }
1131
1132
1133 static int
1134 set_acl(struct archive *a, struct archive_entry *entry, acl_type_t acl_type,
1135     int ae_requested_type, const char *typename)
1136 {
1137         acl_t            acl;
1138         acl_entry_t      acl_entry;
1139         acl_permset_t    acl_permset;
1140         int              ret;
1141         int              ae_type, ae_permset, ae_tag, ae_id;
1142         uid_t            ae_uid;
1143         gid_t            ae_gid;
1144         const char      *ae_name;
1145         int              entries;
1146         const char      *name;
1147
1148         ret = ARCHIVE_OK;
1149         entries = archive_entry_acl_reset(entry, ae_requested_type);
1150         if (entries == 0)
1151                 return (ARCHIVE_OK);
1152         acl = acl_init(entries);
1153         while (archive_entry_acl_next(entry, ae_requested_type, &ae_type,
1154                    &ae_permset, &ae_tag, &ae_id, &ae_name) == ARCHIVE_OK) {
1155                 acl_create_entry(&acl, &acl_entry);
1156
1157                 switch (ae_tag) {
1158                 case ARCHIVE_ENTRY_ACL_USER:
1159                         acl_set_tag_type(acl_entry, ACL_USER);
1160                         ae_uid = lookup_uid(a, ae_name, ae_id);
1161                         acl_set_qualifier(acl_entry, &ae_uid);
1162                         break;
1163                 case ARCHIVE_ENTRY_ACL_GROUP:
1164                         acl_set_tag_type(acl_entry, ACL_GROUP);
1165                         ae_gid = lookup_gid(a, ae_name, ae_id);
1166                         acl_set_qualifier(acl_entry, &ae_gid);
1167                         break;
1168                 case ARCHIVE_ENTRY_ACL_USER_OBJ:
1169                         acl_set_tag_type(acl_entry, ACL_USER_OBJ);
1170                         break;
1171                 case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
1172                         acl_set_tag_type(acl_entry, ACL_GROUP_OBJ);
1173                         break;
1174                 case ARCHIVE_ENTRY_ACL_MASK:
1175                         acl_set_tag_type(acl_entry, ACL_MASK);
1176                         break;
1177                 case ARCHIVE_ENTRY_ACL_OTHER:
1178                         acl_set_tag_type(acl_entry, ACL_OTHER);
1179                         break;
1180                 default:
1181                         /* XXX */
1182                         break;
1183                 }
1184
1185                 acl_get_permset(acl_entry, &acl_permset);
1186                 acl_clear_perms(acl_permset);
1187                 if (ae_permset & ARCHIVE_ENTRY_ACL_EXECUTE)
1188                         acl_add_perm(acl_permset, ACL_EXECUTE);
1189                 if (ae_permset & ARCHIVE_ENTRY_ACL_WRITE)
1190                         acl_add_perm(acl_permset, ACL_WRITE);
1191                 if (ae_permset & ARCHIVE_ENTRY_ACL_READ)
1192                         acl_add_perm(acl_permset, ACL_READ);
1193         }
1194
1195         name = archive_entry_pathname(entry);
1196
1197         if (acl_set_file(name, acl_type, acl) != 0) {
1198                 archive_set_error(a, errno, "Failed to set %s acl", typename);
1199                 ret = ARCHIVE_WARN;
1200         }
1201         acl_free(acl);
1202         return (ret);
1203 }
1204 #endif
1205
1206 /*
1207  * The following routines do some basic caching of uname/gname lookups.
1208  * All such lookups go through these routines, including ACL conversions.
1209  *
1210  * TODO: Provide an API for clients to override these routines.
1211  */
1212 static gid_t
1213 lookup_gid(struct archive *a, const char *gname, gid_t gid)
1214 {
1215         struct group    *grent;
1216         struct extract *extract;
1217         int h;
1218         struct bucket *b;
1219         int cache_size;
1220
1221         extract = a->extract;
1222         cache_size = sizeof(extract->gcache) / sizeof(extract->gcache[0]);
1223
1224         /* If no gname, just use the gid provided. */
1225         if (gname == NULL || *gname == '\0')
1226                 return (gid);
1227
1228         /* Try to find gname in the cache. */
1229         h = hash(gname);
1230         b = &extract->gcache[h % cache_size ];
1231         if (b->name != NULL && b->hash == h && strcmp(gname, b->name) == 0)
1232                 return ((gid_t)b->id);
1233
1234         /* Free the cache slot for a new entry. */
1235         if (b->name != NULL)
1236                 free(b->name);
1237         b->name = strdup(gname);
1238         /* Note: If strdup fails, that's okay; we just won't cache. */
1239         b->hash = h;
1240         grent = getgrnam(gname);
1241         if (grent != NULL)
1242                 gid = grent->gr_gid;
1243         b->id = gid;
1244
1245         return (gid);
1246 }
1247
1248 static uid_t
1249 lookup_uid(struct archive *a, const char *uname, uid_t uid)
1250 {
1251         struct passwd   *pwent;
1252         struct extract *extract;
1253         int h;
1254         struct bucket *b;
1255         int cache_size;
1256
1257         extract = a->extract;
1258         cache_size = sizeof(extract->ucache) / sizeof(extract->ucache[0]);
1259
1260         /* If no uname, just use the uid provided. */
1261         if (uname == NULL || *uname == '\0')
1262                 return (uid);
1263
1264         /* Try to find uname in the cache. */
1265         h = hash(uname);
1266         b = &extract->ucache[h % cache_size ];
1267         if (b->name != NULL && b->hash == h && strcmp(uname, b->name) == 0)
1268                 return ((uid_t)b->id);
1269
1270         /* Free the cache slot for a new entry. */
1271         if (b->name != NULL)
1272                 free(b->name);
1273         b->name = strdup(uname);
1274         /* Note: If strdup fails, that's okay; we just won't cache. */
1275         b->hash = h;
1276         pwent = getpwnam(uname);
1277         if (pwent != NULL)
1278                 uid = pwent->pw_uid;
1279         b->id = uid;
1280
1281         return (uid);
1282 }
1283
1284 static unsigned int
1285 hash(const char *p)
1286 {
1287   /* A 32-bit version of Peter Weinberger's (PJW) hash algorithm,
1288      as used by ELF for hashing function names. */
1289   unsigned g,h = 0;
1290   while(*p != '\0') {
1291     h = ( h << 4 ) + *p++;
1292     if (( g = h & 0xF0000000 )) {
1293       h ^= g >> 24;
1294       h &= 0x0FFFFFFF;
1295     }
1296   }
1297   return h;
1298 }
1299
1300 void
1301 archive_read_extract_set_progress_callback(struct archive *a,
1302     void (*progress_func)(void *), void *user_data)
1303 {
1304         a->extract_progress = progress_func;
1305         a->extract_progress_user_data = user_data;
1306 }