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