2 * Copyright (c) 2003-2007 Tim Kientzle
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #include "bsdtar_platform.h"
27 __FBSDID("$FreeBSD$");
29 #ifdef HAVE_SYS_STAT_H
32 #ifdef HAVE_SYS_TYPES_H
33 #include <sys/types.h> /* Linux doesn't define mode_t, etc. in sys/stat.h. */
52 /* If we don't have wctype, we need to hack up some version of iswprint(). */
53 #define iswprint isprint
58 static void bsdtar_vwarnc(struct bsdtar *, int code,
59 const char *fmt, va_list ap);
60 static size_t bsdtar_expand_char(char *, size_t, char);
61 static const char *strip_components(const char *path, int elements);
63 /* TODO: Hack up a version of mbtowc for platforms with no wide
64 * character support at all. I think the following might suffice,
65 * but it needs careful testing.
67 * #define mbtowc(wcp, p, n) ((*wcp = *p), 1)
72 * Print a string, taking care with any non-printable characters.
74 * Note that we use a stack-allocated buffer to receive the formatted
75 * string if we can. This is partly performance (avoiding a call to
76 * malloc()), partly out of expedience (we have to call vsnprintf()
77 * before malloc() anyway to find out how big a buffer we need; we may
78 * as well point that first call at a small local buffer in case it
79 * works), but mostly for safety (so we can use this to print messages
80 * about out-of-memory conditions).
84 safe_fprintf(FILE *f, const char *fmt, ...)
86 char fmtbuff_stack[256]; /* Place to format the printf() string. */
87 char outbuff[256]; /* Buffer for outgoing characters. */
88 char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
89 char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */
98 /* Use a stack-allocated buffer if we can, for speed and safety. */
100 fmtbuff_length = sizeof(fmtbuff_stack);
101 fmtbuff = fmtbuff_stack;
103 /* Try formatting into the stack buffer. */
105 length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
108 /* If the result was too large, allocate a buffer on the heap. */
109 if (length >= fmtbuff_length) {
110 fmtbuff_length = length+1;
111 fmtbuff_heap = malloc(fmtbuff_length);
113 /* Reformat the result into the heap buffer if we can. */
114 if (fmtbuff_heap != NULL) {
115 fmtbuff = fmtbuff_heap;
117 length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
120 /* Leave fmtbuff pointing to the truncated
121 * string in fmtbuff_stack. */
122 length = sizeof(fmtbuff_stack) - 1;
126 /* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
127 * more portable, so we use that here instead. */
128 mbtowc(NULL, NULL, 0); /* Reset the shift state. */
130 /* Write data, expanding unprintable characters. */
137 /* Convert to wide char, test if the wide
138 * char is printable in the current locale. */
139 if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
141 if (iswprint(wc) && wc != L'\\') {
142 /* Printable, copy the bytes through. */
146 /* Not printable, format the bytes. */
148 i += bsdtar_expand_char(
152 /* After any conversion failure, don't bother
153 * trying to convert the rest. */
154 i += bsdtar_expand_char(outbuff, i, *p++);
158 /* If our output buffer is full, dump it and keep going. */
159 if (i > (sizeof(outbuff) - 20)) {
161 fprintf(f, "%s", outbuff);
166 fprintf(f, "%s", outbuff);
168 /* If we allocated a heap-based formatting buffer, free it now. */
169 if (fmtbuff_heap != NULL)
174 * Render an arbitrary sequence of bytes into printable ASCII characters.
177 bsdtar_expand_char(char *buff, size_t offset, char c)
181 if (isprint((unsigned char)c) && c != '\\')
186 case '\a': buff[i++] = 'a'; break;
187 case '\b': buff[i++] = 'b'; break;
188 case '\f': buff[i++] = 'f'; break;
189 case '\n': buff[i++] = 'n'; break;
191 /* On some platforms, \n and \r are the same. */
192 case '\r': buff[i++] = 'r'; break;
194 case '\t': buff[i++] = 't'; break;
195 case '\v': buff[i++] = 'v'; break;
196 case '\\': buff[i++] = '\\'; break;
198 sprintf(buff + i, "%03o", 0xFF & (int)c);
207 bsdtar_vwarnc(struct bsdtar *bsdtar, int code, const char *fmt, va_list ap)
209 fprintf(stderr, "%s: ", bsdtar->progname);
210 vfprintf(stderr, fmt, ap);
212 fprintf(stderr, ": %s", strerror(code));
213 fprintf(stderr, "\n");
217 bsdtar_warnc(struct bsdtar *bsdtar, int code, const char *fmt, ...)
222 bsdtar_vwarnc(bsdtar, code, fmt, ap);
227 bsdtar_errc(struct bsdtar *bsdtar, int eval, int code, const char *fmt, ...)
232 bsdtar_vwarnc(bsdtar, code, fmt, ap);
238 yes(const char *fmt, ...)
246 vfprintf(stderr, fmt, ap);
248 fprintf(stderr, " (y/N)? ");
251 l = read(2, buff, sizeof(buff) - 1);
256 for (p = buff; *p != '\0'; p++) {
257 if (isspace((unsigned char)*p))
273 * Read lines from file and do something with each one. If option_null
274 * is set, lines are terminated with zero bytes; otherwise, they're
275 * terminated with newlines.
277 * This uses a self-sizing buffer to handle arbitrarily-long lines.
278 * If the "process" function returns non-zero for any line, this
279 * function will return non-zero after attempting to process all
283 process_lines(struct bsdtar *bsdtar, const char *pathname,
284 int (*process)(struct bsdtar *, const char *))
287 char *buff, *buff_end, *line_start, *line_end, *p;
288 size_t buff_length, new_buff_length, bytes_read, bytes_wanted;
292 separator = bsdtar->option_null ? '\0' : '\n';
295 if (strcmp(pathname, "-") == 0)
298 f = fopen(pathname, "r");
300 bsdtar_errc(bsdtar, 1, errno, "Couldn't open %s", pathname);
302 buff = malloc(buff_length);
304 bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read %s", pathname);
305 line_start = line_end = buff_end = buff;
307 /* Get some more data into the buffer. */
308 bytes_wanted = buff + buff_length - buff_end;
309 bytes_read = fread(buff_end, 1, bytes_wanted, f);
310 buff_end += bytes_read;
311 /* Process all complete lines in the buffer. */
312 while (line_end < buff_end) {
313 if (*line_end == separator) {
315 if ((*process)(bsdtar, line_start) != 0)
317 line_start = line_end + 1;
318 line_end = line_start;
325 bsdtar_errc(bsdtar, 1, errno,
326 "Can't read %s", pathname);
327 if (line_start > buff) {
328 /* Move a leftover fractional line to the beginning. */
329 memmove(buff, line_start, buff_end - line_start);
330 buff_end -= line_start - buff;
331 line_end -= line_start - buff;
334 /* Line is too big; enlarge the buffer. */
335 new_buff_length = buff_length * 2;
336 if (new_buff_length <= buff_length)
337 bsdtar_errc(bsdtar, 1, ENOMEM,
338 "Line too long in %s", pathname);
339 buff_length = new_buff_length;
340 p = realloc(buff, buff_length);
342 bsdtar_errc(bsdtar, 1, ENOMEM,
343 "Line too long in %s", pathname);
344 buff_end = p + (buff_end - buff);
345 line_end = p + (line_end - buff);
346 line_start = buff = p;
349 /* At end-of-file, handle the final line. */
350 if (line_end > line_start) {
352 if ((*process)(bsdtar, line_start) != 0)
362 * The logic here for -C <dir> attempts to avoid
363 * chdir() as long as possible. For example:
364 * "-C /foo -C /bar file" needs chdir("/bar") but not chdir("/foo")
365 * "-C /foo -C bar file" needs chdir("/foo/bar")
366 * "-C /foo -C bar /file1" does not need chdir()
367 * "-C /foo -C bar /file1 file2" needs chdir("/foo/bar") before file2
369 * The only correct way to handle this is to record a "pending" chdir
370 * request and combine multiple requests intelligently until we
371 * need to process a non-absolute file. set_chdir() adds the new dir
372 * to the pending list; do_chdir() actually executes any pending chdir.
374 * This way, programs that build tar command lines don't have to worry
375 * about -C with non-existent directories; such requests will only
376 * fail if the directory must be accessed.
379 set_chdir(struct bsdtar *bsdtar, const char *newdir)
381 if (newdir[0] == '/') {
382 /* The -C /foo -C /bar case; dump first one. */
383 free(bsdtar->pending_chdir);
384 bsdtar->pending_chdir = NULL;
386 if (bsdtar->pending_chdir == NULL)
387 /* Easy case: no previously-saved dir. */
388 bsdtar->pending_chdir = strdup(newdir);
390 /* The -C /foo -C bar case; concatenate */
391 char *old_pending = bsdtar->pending_chdir;
392 size_t old_len = strlen(old_pending);
393 bsdtar->pending_chdir = malloc(old_len + strlen(newdir) + 2);
394 if (old_pending[old_len - 1] == '/')
395 old_pending[old_len - 1] = '\0';
396 if (bsdtar->pending_chdir != NULL)
397 sprintf(bsdtar->pending_chdir, "%s/%s",
398 old_pending, newdir);
401 if (bsdtar->pending_chdir == NULL)
402 bsdtar_errc(bsdtar, 1, errno, "No memory");
406 do_chdir(struct bsdtar *bsdtar)
408 if (bsdtar->pending_chdir == NULL)
411 if (chdir(bsdtar->pending_chdir) != 0) {
412 bsdtar_errc(bsdtar, 1, 0, "could not chdir to '%s'\n",
413 bsdtar->pending_chdir);
415 free(bsdtar->pending_chdir);
416 bsdtar->pending_chdir = NULL;
420 strip_components(const char *path, int elements)
422 const char *p = path;
424 while (elements > 0) {
431 /* Path is too short, skip it. */
445 * Handle --strip-components and any future path-rewriting options.
446 * Returns non-zero if the pathname should not be extracted.
448 * TODO: Support pax-style regex path rewrites.
451 edit_pathname(struct bsdtar *bsdtar, struct archive_entry *entry)
453 const char *name = archive_entry_pathname(entry);
460 r = apply_substitution(bsdtar, name, &subst_name, 0);
462 bsdtar_warnc(bsdtar, 0, "Invalid substitution, skipping entry");
466 archive_entry_copy_pathname(entry, subst_name);
467 if (*subst_name == '\0') {
472 name = archive_entry_pathname(entry);
475 if (archive_entry_hardlink(entry)) {
476 r = apply_substitution(bsdtar, archive_entry_hardlink(entry), &subst_name, 1);
478 bsdtar_warnc(bsdtar, 0, "Invalid substitution, skipping entry");
482 archive_entry_copy_hardlink(entry, subst_name);
486 if (archive_entry_symlink(entry) != NULL) {
487 r = apply_substitution(bsdtar, archive_entry_symlink(entry), &subst_name, 1);
489 bsdtar_warnc(bsdtar, 0, "Invalid substitution, skipping entry");
493 archive_entry_copy_symlink(entry, subst_name);
499 /* Strip leading dir names as per --strip-components option. */
500 if (bsdtar->strip_components > 0) {
501 const char *linkname = archive_entry_hardlink(entry);
503 name = strip_components(name, bsdtar->strip_components);
507 if (linkname != NULL) {
508 linkname = strip_components(linkname,
509 bsdtar->strip_components);
510 if (linkname == NULL)
512 archive_entry_copy_hardlink(entry, linkname);
516 /* By default, don't write or restore absolute pathnames. */
517 if (!bsdtar->option_absolute_paths) {
518 const char *rp, *p = name;
521 /* Remove leading "//./" or "//?/" or "//?/UNC/"
522 * (absolute path prefixes used by Windows API) */
523 if ((p[0] == '/' || p[0] == '\\') &&
524 (p[1] == '/' || p[1] == '\\') &&
525 (p[2] == '.' || p[2] == '?') &&
526 (p[3] == '/' || p[3] == '\\'))
529 (p[4] == 'U' || p[4] == 'u') &&
530 (p[5] == 'N' || p[5] == 'n') &&
531 (p[6] == 'C' || p[6] == 'c') &&
532 (p[7] == '/' || p[7] == '\\'))
540 /* Remove leading drive letter from archives created
542 if (((p[0] >= 'a' && p[0] <= 'z') ||
543 (p[0] >= 'A' && p[0] <= 'Z')) &&
548 /* Remove leading "/../", "//", etc. */
549 while (p[0] == '/' || p[0] == '\\') {
550 if (p[1] == '.' && p[2] == '.' &&
551 (p[3] == '/' || p[3] == '\\')) {
552 p += 3; /* Remove "/..", leave "/"
556 p += 1; /* Remove "/". */
560 if (p != name && !bsdtar->warned_lead_slash) {
561 /* Generate a warning the first time this happens. */
563 bsdtar_warnc(bsdtar, 0,
564 "Removing leading '%c' from member names",
567 bsdtar_warnc(bsdtar, 0,
568 "Removing leading drive letter from "
570 bsdtar->warned_lead_slash = 1;
573 /* Special case: Stripping everything yields ".". */
579 /* Strip redundant leading '/' characters. */
580 while (name[0] == '/' && name[1] == '/')
584 /* Safely replace name in archive_entry. */
585 if (name != archive_entry_pathname(entry)) {
586 char *q = strdup(name);
587 archive_entry_copy_pathname(entry, q);
594 * Like strcmp(), but try to be a little more aware of the fact that
595 * we're comparing two paths. Right now, it just handles leading
596 * "./" and trailing '/' specially, so that "a/b/" == "./a/b"
598 * TODO: Make this better, so that "./a//b/./c/" == "a/b/c"
599 * TODO: After this works, push it down into libarchive.
600 * TODO: Publish the path normalization routines in libarchive so
601 * that bsdtar can normalize paths and use fast strcmp() instead
606 pathcmp(const char *a, const char *b)
608 /* Skip leading './' */
609 if (a[0] == '.' && a[1] == '/' && a[2] != '\0')
611 if (b[0] == '.' && b[1] == '/' && b[2] != '\0')
613 /* Find the first difference, or return (0) if none. */
621 * If one ends in '/' and the other one doesn't,
624 if (a[0] == '/' && a[1] == '\0' && b[0] == '\0')
626 if (a[0] == '\0' && b[0] == '/' && b[1] == '\0')
628 /* They're really different, return the correct sign. */
629 return (*(const unsigned char *)a - *(const unsigned char *)b);