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
59 static size_t bsdtar_expand_char(char *, size_t, char);
60 static const char *strip_components(const char *path, int elements);
62 /* TODO: Hack up a version of mbtowc for platforms with no wide
63 * character support at all. I think the following might suffice,
64 * but it needs careful testing.
66 * #define mbtowc(wcp, p, n) ((*wcp = *p), 1)
71 * Print a string, taking care with any non-printable characters.
73 * Note that we use a stack-allocated buffer to receive the formatted
74 * string if we can. This is partly performance (avoiding a call to
75 * malloc()), partly out of expedience (we have to call vsnprintf()
76 * before malloc() anyway to find out how big a buffer we need; we may
77 * as well point that first call at a small local buffer in case it
78 * works), but mostly for safety (so we can use this to print messages
79 * about out-of-memory conditions).
83 safe_fprintf(FILE *f, const char *fmt, ...)
85 char fmtbuff_stack[256]; /* Place to format the printf() string. */
86 char outbuff[256]; /* Buffer for outgoing characters. */
87 char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
88 char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */
97 /* Use a stack-allocated buffer if we can, for speed and safety. */
99 fmtbuff_length = sizeof(fmtbuff_stack);
100 fmtbuff = fmtbuff_stack;
102 /* Try formatting into the stack buffer. */
104 length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
107 /* If the result was too large, allocate a buffer on the heap. */
108 if (length >= fmtbuff_length) {
109 fmtbuff_length = length+1;
110 fmtbuff_heap = malloc(fmtbuff_length);
112 /* Reformat the result into the heap buffer if we can. */
113 if (fmtbuff_heap != NULL) {
114 fmtbuff = fmtbuff_heap;
116 length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
119 /* Leave fmtbuff pointing to the truncated
120 * string in fmtbuff_stack. */
121 length = sizeof(fmtbuff_stack) - 1;
125 /* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
126 * more portable, so we use that here instead. */
127 mbtowc(NULL, NULL, 0); /* Reset the shift state. */
129 /* Write data, expanding unprintable characters. */
136 /* Convert to wide char, test if the wide
137 * char is printable in the current locale. */
138 if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
140 if (iswprint(wc) && wc != L'\\') {
141 /* Printable, copy the bytes through. */
145 /* Not printable, format the bytes. */
147 i += bsdtar_expand_char(
151 /* After any conversion failure, don't bother
152 * trying to convert the rest. */
153 i += bsdtar_expand_char(outbuff, i, *p++);
157 /* If our output buffer is full, dump it and keep going. */
158 if (i > (sizeof(outbuff) - 20)) {
160 fprintf(f, "%s", outbuff);
165 fprintf(f, "%s", outbuff);
167 /* If we allocated a heap-based formatting buffer, free it now. */
168 if (fmtbuff_heap != NULL)
173 * Render an arbitrary sequence of bytes into printable ASCII characters.
176 bsdtar_expand_char(char *buff, size_t offset, char c)
180 if (isprint((unsigned char)c) && c != '\\')
185 case '\a': buff[i++] = 'a'; break;
186 case '\b': buff[i++] = 'b'; break;
187 case '\f': buff[i++] = 'f'; break;
188 case '\n': buff[i++] = 'n'; break;
190 /* On some platforms, \n and \r are the same. */
191 case '\r': buff[i++] = 'r'; break;
193 case '\t': buff[i++] = 't'; break;
194 case '\v': buff[i++] = 'v'; break;
195 case '\\': buff[i++] = '\\'; break;
197 sprintf(buff + i, "%03o", 0xFF & (int)c);
206 yes(const char *fmt, ...)
214 vfprintf(stderr, fmt, ap);
216 fprintf(stderr, " (y/N)? ");
219 l = read(2, buff, sizeof(buff) - 1);
224 for (p = buff; *p != '\0'; p++) {
225 if (isspace((unsigned char)*p))
241 * Read lines from file and do something with each one. If option_null
242 * is set, lines are terminated with zero bytes; otherwise, they're
243 * terminated with newlines.
245 * This uses a self-sizing buffer to handle arbitrarily-long lines.
246 * If the "process" function returns non-zero for any line, this
247 * function will return non-zero after attempting to process all
251 process_lines(struct bsdtar *bsdtar, const char *pathname,
252 int (*process)(struct bsdtar *, const char *))
255 char *buff, *buff_end, *line_start, *line_end, *p;
256 size_t buff_length, new_buff_length, bytes_read, bytes_wanted;
260 separator = bsdtar->option_null ? '\0' : '\n';
263 if (strcmp(pathname, "-") == 0)
266 f = fopen(pathname, "r");
268 bsdtar_errc(1, errno, "Couldn't open %s", pathname);
270 buff = malloc(buff_length);
272 bsdtar_errc(1, ENOMEM, "Can't read %s", pathname);
273 line_start = line_end = buff_end = buff;
275 /* Get some more data into the buffer. */
276 bytes_wanted = buff + buff_length - buff_end;
277 bytes_read = fread(buff_end, 1, bytes_wanted, f);
278 buff_end += bytes_read;
279 /* Process all complete lines in the buffer. */
280 while (line_end < buff_end) {
281 if (*line_end == separator) {
283 if ((*process)(bsdtar, line_start) != 0)
285 line_start = line_end + 1;
286 line_end = line_start;
293 bsdtar_errc(1, errno,
294 "Can't read %s", pathname);
295 if (line_start > buff) {
296 /* Move a leftover fractional line to the beginning. */
297 memmove(buff, line_start, buff_end - line_start);
298 buff_end -= line_start - buff;
299 line_end -= line_start - buff;
302 /* Line is too big; enlarge the buffer. */
303 new_buff_length = buff_length * 2;
304 if (new_buff_length <= buff_length)
305 bsdtar_errc(1, ENOMEM,
306 "Line too long in %s", pathname);
307 buff_length = new_buff_length;
308 p = realloc(buff, buff_length);
310 bsdtar_errc(1, ENOMEM,
311 "Line too long in %s", pathname);
312 buff_end = p + (buff_end - buff);
313 line_end = p + (line_end - buff);
314 line_start = buff = p;
317 /* At end-of-file, handle the final line. */
318 if (line_end > line_start) {
320 if ((*process)(bsdtar, line_start) != 0)
330 * The logic here for -C <dir> attempts to avoid
331 * chdir() as long as possible. For example:
332 * "-C /foo -C /bar file" needs chdir("/bar") but not chdir("/foo")
333 * "-C /foo -C bar file" needs chdir("/foo/bar")
334 * "-C /foo -C bar /file1" does not need chdir()
335 * "-C /foo -C bar /file1 file2" needs chdir("/foo/bar") before file2
337 * The only correct way to handle this is to record a "pending" chdir
338 * request and combine multiple requests intelligently until we
339 * need to process a non-absolute file. set_chdir() adds the new dir
340 * to the pending list; do_chdir() actually executes any pending chdir.
342 * This way, programs that build tar command lines don't have to worry
343 * about -C with non-existent directories; such requests will only
344 * fail if the directory must be accessed.
347 set_chdir(struct bsdtar *bsdtar, const char *newdir)
349 if (newdir[0] == '/') {
350 /* The -C /foo -C /bar case; dump first one. */
351 free(bsdtar->pending_chdir);
352 bsdtar->pending_chdir = NULL;
354 if (bsdtar->pending_chdir == NULL)
355 /* Easy case: no previously-saved dir. */
356 bsdtar->pending_chdir = strdup(newdir);
358 /* The -C /foo -C bar case; concatenate */
359 char *old_pending = bsdtar->pending_chdir;
360 size_t old_len = strlen(old_pending);
361 bsdtar->pending_chdir = malloc(old_len + strlen(newdir) + 2);
362 if (old_pending[old_len - 1] == '/')
363 old_pending[old_len - 1] = '\0';
364 if (bsdtar->pending_chdir != NULL)
365 sprintf(bsdtar->pending_chdir, "%s/%s",
366 old_pending, newdir);
369 if (bsdtar->pending_chdir == NULL)
370 bsdtar_errc(1, errno, "No memory");
374 do_chdir(struct bsdtar *bsdtar)
376 if (bsdtar->pending_chdir == NULL)
379 if (chdir(bsdtar->pending_chdir) != 0) {
380 bsdtar_errc(1, 0, "could not chdir to '%s'\n",
381 bsdtar->pending_chdir);
383 free(bsdtar->pending_chdir);
384 bsdtar->pending_chdir = NULL;
388 strip_components(const char *path, int elements)
390 const char *p = path;
392 while (elements > 0) {
399 /* Path is too short, skip it. */
413 * Handle --strip-components and any future path-rewriting options.
414 * Returns non-zero if the pathname should not be extracted.
416 * TODO: Support pax-style regex path rewrites.
419 edit_pathname(struct bsdtar *bsdtar, struct archive_entry *entry)
421 const char *name = archive_entry_pathname(entry);
428 r = apply_substitution(bsdtar, name, &subst_name, 0);
430 bsdtar_warnc(0, "Invalid substitution, skipping entry");
434 archive_entry_copy_pathname(entry, subst_name);
435 if (*subst_name == '\0') {
440 name = archive_entry_pathname(entry);
443 if (archive_entry_hardlink(entry)) {
444 r = apply_substitution(bsdtar, archive_entry_hardlink(entry), &subst_name, 1);
446 bsdtar_warnc(0, "Invalid substitution, skipping entry");
450 archive_entry_copy_hardlink(entry, subst_name);
454 if (archive_entry_symlink(entry) != NULL) {
455 r = apply_substitution(bsdtar, archive_entry_symlink(entry), &subst_name, 1);
457 bsdtar_warnc(0, "Invalid substitution, skipping entry");
461 archive_entry_copy_symlink(entry, subst_name);
467 /* Strip leading dir names as per --strip-components option. */
468 if (bsdtar->strip_components > 0) {
469 const char *linkname = archive_entry_hardlink(entry);
471 name = strip_components(name, bsdtar->strip_components);
475 if (linkname != NULL) {
476 linkname = strip_components(linkname,
477 bsdtar->strip_components);
478 if (linkname == NULL)
480 archive_entry_copy_hardlink(entry, linkname);
484 /* By default, don't write or restore absolute pathnames. */
485 if (!bsdtar->option_absolute_paths) {
486 const char *rp, *p = name;
489 /* Remove leading "//./" or "//?/" or "//?/UNC/"
490 * (absolute path prefixes used by Windows API) */
491 if ((p[0] == '/' || p[0] == '\\') &&
492 (p[1] == '/' || p[1] == '\\') &&
493 (p[2] == '.' || p[2] == '?') &&
494 (p[3] == '/' || p[3] == '\\'))
497 (p[4] == 'U' || p[4] == 'u') &&
498 (p[5] == 'N' || p[5] == 'n') &&
499 (p[6] == 'C' || p[6] == 'c') &&
500 (p[7] == '/' || p[7] == '\\'))
508 /* Remove leading drive letter from archives created
510 if (((p[0] >= 'a' && p[0] <= 'z') ||
511 (p[0] >= 'A' && p[0] <= 'Z')) &&
516 /* Remove leading "/../", "//", etc. */
517 while (p[0] == '/' || p[0] == '\\') {
518 if (p[1] == '.' && p[2] == '.' &&
519 (p[3] == '/' || p[3] == '\\')) {
520 p += 3; /* Remove "/..", leave "/"
524 p += 1; /* Remove "/". */
528 if (p != name && !bsdtar->warned_lead_slash) {
529 /* Generate a warning the first time this happens. */
532 "Removing leading '%c' from member names",
536 "Removing leading drive letter from "
538 bsdtar->warned_lead_slash = 1;
541 /* Special case: Stripping everything yields ".". */
547 /* Strip redundant leading '/' characters. */
548 while (name[0] == '/' && name[1] == '/')
552 /* Safely replace name in archive_entry. */
553 if (name != archive_entry_pathname(entry)) {
554 char *q = strdup(name);
555 archive_entry_copy_pathname(entry, q);
562 * It would be nice to just use printf() for formatting large numbers,
563 * but the compatibility problems are quite a headache. Hence the
564 * following simple utility function.
567 tar_i64toa(int64_t n0)
569 static char buff[24];
570 int64_t n = n0 < 0 ? -n0 : n0;
571 char *p = buff + sizeof(buff);
575 *--p = '0' + (int)(n % 10);
584 * Like strcmp(), but try to be a little more aware of the fact that
585 * we're comparing two paths. Right now, it just handles leading
586 * "./" and trailing '/' specially, so that "a/b/" == "./a/b"
588 * TODO: Make this better, so that "./a//b/./c/" == "a/b/c"
589 * TODO: After this works, push it down into libarchive.
590 * TODO: Publish the path normalization routines in libarchive so
591 * that bsdtar can normalize paths and use fast strcmp() instead
596 pathcmp(const char *a, const char *b)
598 /* Skip leading './' */
599 if (a[0] == '.' && a[1] == '/' && a[2] != '\0')
601 if (b[0] == '.' && b[1] == '/' && b[2] != '\0')
603 /* Find the first difference, or return (0) if none. */
611 * If one ends in '/' and the other one doesn't,
614 if (a[0] == '/' && a[1] == '\0' && b[0] == '\0')
616 if (a[0] == '\0' && b[0] == '/' && b[1] == '\0')
618 /* They're really different, return the correct sign. */
619 return (*(const unsigned char *)a - *(const unsigned char *)b);