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: src/usr.bin/tar/util.c,v 1.23 2008/12/15 06:00:25 kientzle Exp $");
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. */
58 /* If we don't have wctype, we need to hack up some version of iswprint(). */
59 #define iswprint isprint
65 static size_t bsdtar_expand_char(char *, size_t, char);
66 static const char *strip_components(const char *path, int elements);
68 #if defined(_WIN32) && !defined(__CYGWIN__)
72 /* TODO: Hack up a version of mbtowc for platforms with no wide
73 * character support at all. I think the following might suffice,
74 * but it needs careful testing.
76 * #define mbtowc(wcp, p, n) ((*wcp = *p), 1)
81 * Print a string, taking care with any non-printable characters.
83 * Note that we use a stack-allocated buffer to receive the formatted
84 * string if we can. This is partly performance (avoiding a call to
85 * malloc()), partly out of expedience (we have to call vsnprintf()
86 * before malloc() anyway to find out how big a buffer we need; we may
87 * as well point that first call at a small local buffer in case it
88 * works), but mostly for safety (so we can use this to print messages
89 * about out-of-memory conditions).
93 safe_fprintf(FILE *f, const char *fmt, ...)
95 char fmtbuff_stack[256]; /* Place to format the printf() string. */
96 char outbuff[256]; /* Buffer for outgoing characters. */
97 char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
98 char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */
107 /* Use a stack-allocated buffer if we can, for speed and safety. */
109 fmtbuff_length = sizeof(fmtbuff_stack);
110 fmtbuff = fmtbuff_stack;
112 /* Try formatting into the stack buffer. */
114 length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
117 /* If the result was too large, allocate a buffer on the heap. */
118 while (length < 0 || length >= fmtbuff_length) {
119 if (length >= fmtbuff_length)
120 fmtbuff_length = length+1;
121 else if (fmtbuff_length < 8192)
123 else if (fmtbuff_length < 1000000)
124 fmtbuff_length += fmtbuff_length / 4;
126 length = fmtbuff_length;
127 fmtbuff_heap[length-1] = '\0';
131 fmtbuff_heap = malloc(fmtbuff_length);
133 /* Reformat the result into the heap buffer if we can. */
134 if (fmtbuff_heap != NULL) {
135 fmtbuff = fmtbuff_heap;
137 length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
140 /* Leave fmtbuff pointing to the truncated
141 * string in fmtbuff_stack. */
142 length = sizeof(fmtbuff_stack) - 1;
147 /* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
148 * more portable, so we use that here instead. */
149 if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */
150 /* mbtowc() should never fail in practice, but
151 * handle the theoretical error anyway. */
156 /* Write data, expanding unprintable characters. */
162 /* Convert to wide char, test if the wide
163 * char is printable in the current locale. */
164 if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
166 if (iswprint(wc) && wc != L'\\') {
167 /* Printable, copy the bytes through. */
171 /* Not printable, format the bytes. */
173 i += (unsigned)bsdtar_expand_char(
177 /* After any conversion failure, don't bother
178 * trying to convert the rest. */
179 i += (unsigned)bsdtar_expand_char(outbuff, i, *p++);
183 /* If our output buffer is full, dump it and keep going. */
184 if (i > (sizeof(outbuff) - 20)) {
186 fprintf(f, "%s", outbuff);
191 fprintf(f, "%s", outbuff);
193 /* If we allocated a heap-based formatting buffer, free it now. */
198 * Render an arbitrary sequence of bytes into printable ASCII characters.
201 bsdtar_expand_char(char *buff, size_t offset, char c)
205 if (isprint((unsigned char)c) && c != '\\')
210 case '\a': buff[i++] = 'a'; break;
211 case '\b': buff[i++] = 'b'; break;
212 case '\f': buff[i++] = 'f'; break;
213 case '\n': buff[i++] = 'n'; break;
215 /* On some platforms, \n and \r are the same. */
216 case '\r': buff[i++] = 'r'; break;
218 case '\t': buff[i++] = 't'; break;
219 case '\v': buff[i++] = 'v'; break;
220 case '\\': buff[i++] = '\\'; break;
222 sprintf(buff + i, "%03o", 0xFF & (int)c);
231 yes(const char *fmt, ...)
239 vfprintf(stderr, fmt, ap);
241 fprintf(stderr, " (y/N)? ");
244 l = read(2, buff, sizeof(buff) - 1);
246 fprintf(stderr, "Keyboard read failed\n");
253 for (p = buff; *p != '\0'; p++) {
254 if (isspace((unsigned char)*p))
270 * The logic here for -C <dir> attempts to avoid
271 * chdir() as long as possible. For example:
272 * "-C /foo -C /bar file" needs chdir("/bar") but not chdir("/foo")
273 * "-C /foo -C bar file" needs chdir("/foo/bar")
274 * "-C /foo -C bar /file1" does not need chdir()
275 * "-C /foo -C bar /file1 file2" needs chdir("/foo/bar") before file2
277 * The only correct way to handle this is to record a "pending" chdir
278 * request and combine multiple requests intelligently until we
279 * need to process a non-absolute file. set_chdir() adds the new dir
280 * to the pending list; do_chdir() actually executes any pending chdir.
282 * This way, programs that build tar command lines don't have to worry
283 * about -C with non-existent directories; such requests will only
284 * fail if the directory must be accessed.
288 set_chdir(struct bsdtar *bsdtar, const char *newdir)
290 #if defined(_WIN32) && !defined(__CYGWIN__)
291 if (newdir[0] == '/' || newdir[0] == '\\' ||
292 /* Detect this type, for example, "C:\" or "C:/" */
293 (((newdir[0] >= 'a' && newdir[0] <= 'z') ||
294 (newdir[0] >= 'A' && newdir[0] <= 'Z')) &&
295 newdir[1] == ':' && (newdir[2] == '/' || newdir[2] == '\\'))) {
297 if (newdir[0] == '/') {
299 /* The -C /foo -C /bar case; dump first one. */
300 free(bsdtar->pending_chdir);
301 bsdtar->pending_chdir = NULL;
303 if (bsdtar->pending_chdir == NULL)
304 /* Easy case: no previously-saved dir. */
305 bsdtar->pending_chdir = strdup(newdir);
307 /* The -C /foo -C bar case; concatenate */
308 char *old_pending = bsdtar->pending_chdir;
309 size_t old_len = strlen(old_pending);
310 bsdtar->pending_chdir = malloc(old_len + strlen(newdir) + 2);
311 if (old_pending[old_len - 1] == '/')
312 old_pending[old_len - 1] = '\0';
313 if (bsdtar->pending_chdir != NULL)
314 sprintf(bsdtar->pending_chdir, "%s/%s",
315 old_pending, newdir);
318 if (bsdtar->pending_chdir == NULL)
319 lafe_errc(1, errno, "No memory");
323 do_chdir(struct bsdtar *bsdtar)
325 if (bsdtar->pending_chdir == NULL)
328 if (chdir(bsdtar->pending_chdir) != 0) {
329 lafe_errc(1, 0, "could not chdir to '%s'\n",
330 bsdtar->pending_chdir);
332 free(bsdtar->pending_chdir);
333 bsdtar->pending_chdir = NULL;
337 strip_components(const char *p, int elements)
339 /* Skip as many elements as necessary. */
340 while (elements > 0) {
343 #if defined(_WIN32) && !defined(__CYGWIN__)
344 case '\\': /* Support \ path sep on Windows ONLY. */
349 /* Path is too short, skip it. */
354 /* Skip any / characters. This handles short paths that have
355 * additional / termination. This also handles the case where
356 * the logic above stops in the middle of a duplicate //
357 * sequence (which would otherwise get converted to an
362 #if defined(_WIN32) && !defined(__CYGWIN__)
363 case '\\': /* Support \ path sep on Windows ONLY. */
376 * Handle --strip-components and any future path-rewriting options.
377 * Returns non-zero if the pathname should not be extracted.
379 * TODO: Support pax-style regex path rewrites.
382 edit_pathname(struct bsdtar *bsdtar, struct archive_entry *entry)
384 const char *name = archive_entry_pathname(entry);
385 #if defined(HAVE_REGEX_H) || defined(HAVE_PCREPOSIX_H)
389 r = apply_substitution(bsdtar, name, &subst_name, 0, 0);
391 lafe_warnc(0, "Invalid substitution, skipping entry");
395 archive_entry_copy_pathname(entry, subst_name);
396 if (*subst_name == '\0') {
401 name = archive_entry_pathname(entry);
404 if (archive_entry_hardlink(entry)) {
405 r = apply_substitution(bsdtar, archive_entry_hardlink(entry), &subst_name, 0, 1);
407 lafe_warnc(0, "Invalid substitution, skipping entry");
411 archive_entry_copy_hardlink(entry, subst_name);
415 if (archive_entry_symlink(entry) != NULL) {
416 r = apply_substitution(bsdtar, archive_entry_symlink(entry), &subst_name, 1, 0);
418 lafe_warnc(0, "Invalid substitution, skipping entry");
422 archive_entry_copy_symlink(entry, subst_name);
428 /* Strip leading dir names as per --strip-components option. */
429 if (bsdtar->strip_components > 0) {
430 const char *linkname = archive_entry_hardlink(entry);
432 name = strip_components(name, bsdtar->strip_components);
436 if (linkname != NULL) {
437 linkname = strip_components(linkname,
438 bsdtar->strip_components);
439 if (linkname == NULL)
441 archive_entry_copy_hardlink(entry, linkname);
445 /* By default, don't write or restore absolute pathnames. */
446 if (!bsdtar->option_absolute_paths) {
447 const char *rp, *p = name;
450 /* Remove leading "//./" or "//?/" or "//?/UNC/"
451 * (absolute path prefixes used by Windows API) */
452 if ((p[0] == '/' || p[0] == '\\') &&
453 (p[1] == '/' || p[1] == '\\') &&
454 (p[2] == '.' || p[2] == '?') &&
455 (p[3] == '/' || p[3] == '\\'))
458 (p[4] == 'U' || p[4] == 'u') &&
459 (p[5] == 'N' || p[5] == 'n') &&
460 (p[6] == 'C' || p[6] == 'c') &&
461 (p[7] == '/' || p[7] == '\\'))
469 /* Remove leading drive letter from archives created
471 if (((p[0] >= 'a' && p[0] <= 'z') ||
472 (p[0] >= 'A' && p[0] <= 'Z')) &&
477 /* Remove leading "/../", "//", etc. */
478 while (p[0] == '/' || p[0] == '\\') {
479 if (p[1] == '.' && p[2] == '.' &&
480 (p[3] == '/' || p[3] == '\\')) {
481 p += 3; /* Remove "/..", leave "/"
485 p += 1; /* Remove "/". */
489 if (p != name && !bsdtar->warned_lead_slash) {
490 /* Generate a warning the first time this happens. */
493 "Removing leading '%c' from member names",
497 "Removing leading drive letter from "
499 bsdtar->warned_lead_slash = 1;
502 /* Special case: Stripping everything yields ".". */
508 /* Strip redundant leading '/' characters. */
509 while (name[0] == '/' && name[1] == '/')
513 /* Safely replace name in archive_entry. */
514 if (name != archive_entry_pathname(entry)) {
515 char *q = strdup(name);
516 archive_entry_copy_pathname(entry, q);
523 * It would be nice to just use printf() for formatting large numbers,
524 * but the compatibility problems are quite a headache. Hence the
525 * following simple utility function.
528 tar_i64toa(int64_t n0)
530 static char buff[24];
531 uint64_t n = n0 < 0 ? -n0 : n0;
532 char *p = buff + sizeof(buff);
536 *--p = '0' + (int)(n % 10);
544 * Like strcmp(), but try to be a little more aware of the fact that
545 * we're comparing two paths. Right now, it just handles leading
546 * "./" and trailing '/' specially, so that "a/b/" == "./a/b"
548 * TODO: Make this better, so that "./a//b/./c/" == "a/b/c"
549 * TODO: After this works, push it down into libarchive.
550 * TODO: Publish the path normalization routines in libarchive so
551 * that bsdtar can normalize paths and use fast strcmp() instead
554 * Note: This is currently only used within write.c, so should
555 * not handle \ path separators.
559 pathcmp(const char *a, const char *b)
561 /* Skip leading './' */
562 if (a[0] == '.' && a[1] == '/' && a[2] != '\0')
564 if (b[0] == '.' && b[1] == '/' && b[2] != '\0')
566 /* Find the first difference, or return (0) if none. */
574 * If one ends in '/' and the other one doesn't,
577 if (a[0] == '/' && a[1] == '\0' && b[0] == '\0')
579 if (a[0] == '\0' && b[0] == '/' && b[1] == '\0')
581 /* They're really different, return the correct sign. */
582 return (*(const unsigned char *)a - *(const unsigned char *)b);