xref: /freebsd/contrib/libarchive/tar/util.c (revision ab0b9f6b3073e6c4d1dfbf07444d7db67a189a96)
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  * 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.
13  *
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.
24  */
25 
26 #include "bsdtar_platform.h"
27 __FBSDID("$FreeBSD$");
28 
29 #ifdef HAVE_SYS_STAT_H
30 #include <sys/stat.h>
31 #endif
32 #ifdef HAVE_SYS_TYPES_H
33 #include <sys/types.h>  /* Linux doesn't define mode_t, etc. in sys/stat.h. */
34 #endif
35 #include <ctype.h>
36 #ifdef HAVE_ERRNO_H
37 #include <errno.h>
38 #endif
39 #ifdef HAVE_IO_H
40 #include <io.h>
41 #endif
42 #ifdef HAVE_STDARG_H
43 #include <stdarg.h>
44 #endif
45 #ifdef HAVE_STDINT_H
46 #include <stdint.h>
47 #endif
48 #include <stdio.h>
49 #ifdef HAVE_STDLIB_H
50 #include <stdlib.h>
51 #endif
52 #ifdef HAVE_STRING_H
53 #include <string.h>
54 #endif
55 #ifdef HAVE_WCTYPE_H
56 #include <wctype.h>
57 #else
58 /* If we don't have wctype, we need to hack up some version of iswprint(). */
59 #define	iswprint isprint
60 #endif
61 
62 #include "bsdtar.h"
63 #include "err.h"
64 
65 static size_t	bsdtar_expand_char(char *, size_t, char);
66 static const char *strip_components(const char *path, int elements);
67 
68 #if defined(_WIN32) && !defined(__CYGWIN__)
69 #define	read _read
70 #endif
71 
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.
75  * #if !HAVE_MBTOWC
76  * #define	mbtowc(wcp, p, n) ((*wcp = *p), 1)
77  * #endif
78  */
79 
80 /*
81  * Print a string, taking care with any non-printable characters.
82  *
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).
90  */
91 
92 void
93 safe_fprintf(FILE *f, const char *fmt, ...)
94 {
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. */
99 	int fmtbuff_length;
100 	int length, n;
101 	va_list ap;
102 	const char *p;
103 	unsigned i;
104 	wchar_t wc;
105 	char try_wc;
106 
107 	/* Use a stack-allocated buffer if we can, for speed and safety. */
108 	fmtbuff_heap = NULL;
109 	fmtbuff_length = sizeof(fmtbuff_stack);
110 	fmtbuff = fmtbuff_stack;
111 
112 	/* Try formatting into the stack buffer. */
113 	va_start(ap, fmt);
114 	length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
115 	va_end(ap);
116 
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)
122 			fmtbuff_length *= 2;
123 		else if (fmtbuff_length < 1000000)
124 			fmtbuff_length += fmtbuff_length / 4;
125 		else {
126 			length = fmtbuff_length;
127 			fmtbuff_heap[length-1] = '\0';
128 			break;
129 		}
130 		free(fmtbuff_heap);
131 		fmtbuff_heap = malloc(fmtbuff_length);
132 
133 		/* Reformat the result into the heap buffer if we can. */
134 		if (fmtbuff_heap != NULL) {
135 			fmtbuff = fmtbuff_heap;
136 			va_start(ap, fmt);
137 			length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
138 			va_end(ap);
139 		} else {
140 			/* Leave fmtbuff pointing to the truncated
141 			 * string in fmtbuff_stack. */
142 			length = sizeof(fmtbuff_stack) - 1;
143 			break;
144 		}
145 	}
146 
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. */
152 		free(fmtbuff_heap);
153 		return;
154 	}
155 
156 	/* Write data, expanding unprintable characters. */
157 	p = fmtbuff;
158 	i = 0;
159 	try_wc = 1;
160 	while (*p != '\0') {
161 
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) {
165 			length -= n;
166 			if (iswprint(wc) && wc != L'\\') {
167 				/* Printable, copy the bytes through. */
168 				while (n-- > 0)
169 					outbuff[i++] = *p++;
170 			} else {
171 				/* Not printable, format the bytes. */
172 				while (n-- > 0)
173 					i += (unsigned)bsdtar_expand_char(
174 					    outbuff, i, *p++);
175 			}
176 		} else {
177 			/* After any conversion failure, don't bother
178 			 * trying to convert the rest. */
179 			i += (unsigned)bsdtar_expand_char(outbuff, i, *p++);
180 			try_wc = 0;
181 		}
182 
183 		/* If our output buffer is full, dump it and keep going. */
184 		if (i > (sizeof(outbuff) - 20)) {
185 			outbuff[i] = '\0';
186 			fprintf(f, "%s", outbuff);
187 			i = 0;
188 		}
189 	}
190 	outbuff[i] = '\0';
191 	fprintf(f, "%s", outbuff);
192 
193 	/* If we allocated a heap-based formatting buffer, free it now. */
194 	free(fmtbuff_heap);
195 }
196 
197 /*
198  * Render an arbitrary sequence of bytes into printable ASCII characters.
199  */
200 static size_t
201 bsdtar_expand_char(char *buff, size_t offset, char c)
202 {
203 	size_t i = offset;
204 
205 	if (isprint((unsigned char)c) && c != '\\')
206 		buff[i++] = c;
207 	else {
208 		buff[i++] = '\\';
209 		switch (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;
214 #if '\r' != '\n'
215 		/* On some platforms, \n and \r are the same. */
216 		case '\r': buff[i++] = 'r'; break;
217 #endif
218 		case '\t': buff[i++] = 't'; break;
219 		case '\v': buff[i++] = 'v'; break;
220 		case '\\': buff[i++] = '\\'; break;
221 		default:
222 			sprintf(buff + i, "%03o", 0xFF & (int)c);
223 			i += 3;
224 		}
225 	}
226 
227 	return (i - offset);
228 }
229 
230 int
231 yes(const char *fmt, ...)
232 {
233 	char buff[32];
234 	char *p;
235 	ssize_t l;
236 
237 	va_list ap;
238 	va_start(ap, fmt);
239 	vfprintf(stderr, fmt, ap);
240 	va_end(ap);
241 	fprintf(stderr, " (y/N)? ");
242 	fflush(stderr);
243 
244 	l = read(2, buff, sizeof(buff) - 1);
245 	if (l < 0) {
246 	  fprintf(stderr, "Keyboard read failed\n");
247 	  exit(1);
248 	}
249 	if (l == 0)
250 		return (0);
251 	buff[l] = 0;
252 
253 	for (p = buff; *p != '\0'; p++) {
254 		if (isspace((unsigned char)*p))
255 			continue;
256 		switch(*p) {
257 		case 'y': case 'Y':
258 			return (1);
259 		case 'n': case 'N':
260 			return (0);
261 		default:
262 			return (0);
263 		}
264 	}
265 
266 	return (0);
267 }
268 
269 /*-
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
276  *
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.
281  *
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.
285  *
286  */
287 void
288 set_chdir(struct bsdtar *bsdtar, const char *newdir)
289 {
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] == '\\'))) {
296 #else
297 	if (newdir[0] == '/') {
298 #endif
299 		/* The -C /foo -C /bar case; dump first one. */
300 		free(bsdtar->pending_chdir);
301 		bsdtar->pending_chdir = NULL;
302 	}
303 	if (bsdtar->pending_chdir == NULL)
304 		/* Easy case: no previously-saved dir. */
305 		bsdtar->pending_chdir = strdup(newdir);
306 	else {
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);
316 		free(old_pending);
317 	}
318 	if (bsdtar->pending_chdir == NULL)
319 		lafe_errc(1, errno, "No memory");
320 }
321 
322 void
323 do_chdir(struct bsdtar *bsdtar)
324 {
325 	if (bsdtar->pending_chdir == NULL)
326 		return;
327 
328 	if (chdir(bsdtar->pending_chdir) != 0) {
329 		lafe_errc(1, 0, "could not chdir to '%s'\n",
330 		    bsdtar->pending_chdir);
331 	}
332 	free(bsdtar->pending_chdir);
333 	bsdtar->pending_chdir = NULL;
334 }
335 
336 static const char *
337 strip_components(const char *p, int elements)
338 {
339 	/* Skip as many elements as necessary. */
340 	while (elements > 0) {
341 		switch (*p++) {
342 		case '/':
343 #if defined(_WIN32) && !defined(__CYGWIN__)
344 		case '\\': /* Support \ path sep on Windows ONLY. */
345 #endif
346 			elements--;
347 			break;
348 		case '\0':
349 			/* Path is too short, skip it. */
350 			return (NULL);
351 		}
352 	}
353 
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
358 	 * absolute path). */
359 	for (;;) {
360 		switch (*p) {
361 		case '/':
362 #if defined(_WIN32) && !defined(__CYGWIN__)
363 		case '\\': /* Support \ path sep on Windows ONLY. */
364 #endif
365 			++p;
366 			break;
367 		case '\0':
368 			return (NULL);
369 		default:
370 			return (p);
371 		}
372 	}
373 }
374 
375 /*
376  * Handle --strip-components and any future path-rewriting options.
377  * Returns non-zero if the pathname should not be extracted.
378  *
379  * TODO: Support pax-style regex path rewrites.
380  */
381 int
382 edit_pathname(struct bsdtar *bsdtar, struct archive_entry *entry)
383 {
384 	const char *name = archive_entry_pathname(entry);
385 #if defined(HAVE_REGEX_H) || defined(HAVE_PCREPOSIX_H)
386 	char *subst_name;
387 	int r;
388 
389 	r = apply_substitution(bsdtar, name, &subst_name, 0, 0);
390 	if (r == -1) {
391 		lafe_warnc(0, "Invalid substitution, skipping entry");
392 		return 1;
393 	}
394 	if (r == 1) {
395 		archive_entry_copy_pathname(entry, subst_name);
396 		if (*subst_name == '\0') {
397 			free(subst_name);
398 			return -1;
399 		} else
400 			free(subst_name);
401 		name = archive_entry_pathname(entry);
402 	}
403 
404 	if (archive_entry_hardlink(entry)) {
405 		r = apply_substitution(bsdtar, archive_entry_hardlink(entry), &subst_name, 0, 1);
406 		if (r == -1) {
407 			lafe_warnc(0, "Invalid substitution, skipping entry");
408 			return 1;
409 		}
410 		if (r == 1) {
411 			archive_entry_copy_hardlink(entry, subst_name);
412 			free(subst_name);
413 		}
414 	}
415 	if (archive_entry_symlink(entry) != NULL) {
416 		r = apply_substitution(bsdtar, archive_entry_symlink(entry), &subst_name, 1, 0);
417 		if (r == -1) {
418 			lafe_warnc(0, "Invalid substitution, skipping entry");
419 			return 1;
420 		}
421 		if (r == 1) {
422 			archive_entry_copy_symlink(entry, subst_name);
423 			free(subst_name);
424 		}
425 	}
426 #endif
427 
428 	/* Strip leading dir names as per --strip-components option. */
429 	if (bsdtar->strip_components > 0) {
430 		const char *linkname = archive_entry_hardlink(entry);
431 
432 		name = strip_components(name, bsdtar->strip_components);
433 		if (name == NULL)
434 			return (1);
435 
436 		if (linkname != NULL) {
437 			linkname = strip_components(linkname,
438 			    bsdtar->strip_components);
439 			if (linkname == NULL)
440 				return (1);
441 			archive_entry_copy_hardlink(entry, linkname);
442 		}
443 	}
444 
445 	/* By default, don't write or restore absolute pathnames. */
446 	if (!bsdtar->option_absolute_paths) {
447 		const char *rp, *p = name;
448 		int slashonly = 1;
449 
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] == '\\'))
456 		{
457 			if (p[2] == '?' &&
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] == '\\'))
462 				p += 8;
463 			else
464 				p += 4;
465 			slashonly = 0;
466 		}
467 		do {
468 			rp = p;
469 			/* Remove leading drive letter from archives created
470 			 * on Windows. */
471 			if (((p[0] >= 'a' && p[0] <= 'z') ||
472 			     (p[0] >= 'A' && p[0] <= 'Z')) &&
473 				 p[1] == ':') {
474 				p += 2;
475 				slashonly = 0;
476 			}
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 "/"
482 							 * for next pass. */
483 					slashonly = 0;
484 				} else
485 					p += 1; /* Remove "/". */
486 			}
487 		} while (rp != p);
488 
489 		if (p != name && !bsdtar->warned_lead_slash) {
490 			/* Generate a warning the first time this happens. */
491 			if (slashonly)
492 				lafe_warnc(0,
493 				    "Removing leading '%c' from member names",
494 				    name[0]);
495 			else
496 				lafe_warnc(0,
497 				    "Removing leading drive letter from "
498 				    "member names");
499 			bsdtar->warned_lead_slash = 1;
500 		}
501 
502 		/* Special case: Stripping everything yields ".". */
503 		if (*p == '\0')
504 			name = ".";
505 		else
506 			name = p;
507 	} else {
508 		/* Strip redundant leading '/' characters. */
509 		while (name[0] == '/' && name[1] == '/')
510 			name++;
511 	}
512 
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);
517 		free(q);
518 	}
519 	return (0);
520 }
521 
522 /*
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.
526  */
527 const char *
528 tar_i64toa(int64_t n0)
529 {
530 	static char buff[24];
531 	uint64_t n = n0 < 0 ? -n0 : n0;
532 	char *p = buff + sizeof(buff);
533 
534 	*--p = '\0';
535 	do {
536 		*--p = '0' + (int)(n % 10);
537 	} while (n /= 10);
538 	if (n0 < 0)
539 		*--p = '-';
540 	return p;
541 }
542 
543 /*
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"
547  *
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
552  * of this.
553  *
554  * Note: This is currently only used within write.c, so should
555  * not handle \ path separators.
556  */
557 
558 int
559 pathcmp(const char *a, const char *b)
560 {
561 	/* Skip leading './' */
562 	if (a[0] == '.' && a[1] == '/' && a[2] != '\0')
563 		a += 2;
564 	if (b[0] == '.' && b[1] == '/' && b[2] != '\0')
565 		b += 2;
566 	/* Find the first difference, or return (0) if none. */
567 	while (*a == *b) {
568 		if (*a == '\0')
569 			return (0);
570 		a++;
571 		b++;
572 	}
573 	/*
574 	 * If one ends in '/' and the other one doesn't,
575 	 * they're the same.
576 	 */
577 	if (a[0] == '/' && a[1] == '\0' && b[0] == '\0')
578 		return (0);
579 	if (a[0] == '\0' && b[0] == '/' && b[1] == '\0')
580 		return (0);
581 	/* They're really different, return the correct sign. */
582 	return (*(const unsigned char *)a - *(const unsigned char *)b);
583 }
584