Home | History | Annotate | Line # | Download | only in tar
      1 /*-
      2  * SPDX-License-Identifier: BSD-2-Clause
      3  *
      4  * Copyright (c) 2003-2007 Tim Kientzle
      5  * All rights reserved.
      6  */
      7 
      8 #include "bsdtar_platform.h"
      9 
     10 #ifdef HAVE_SYS_STAT_H
     11 #include <sys/stat.h>
     12 #endif
     13 #ifdef HAVE_SYS_TYPES_H
     14 #include <sys/types.h>  /* Linux doesn't define mode_t, etc. in sys/stat.h. */
     15 #endif
     16 #include <ctype.h>
     17 #ifdef HAVE_ERRNO_H
     18 #include <errno.h>
     19 #endif
     20 #ifdef HAVE_IO_H
     21 #include <io.h>
     22 #endif
     23 #ifdef HAVE_STDARG_H
     24 #include <stdarg.h>
     25 #endif
     26 #ifdef HAVE_STDINT_H
     27 #include <stdint.h>
     28 #endif
     29 #include <stdio.h>
     30 #ifdef HAVE_STDLIB_H
     31 #include <stdlib.h>
     32 #endif
     33 #ifdef HAVE_STRING_H
     34 #include <string.h>
     35 #endif
     36 #ifdef HAVE_WCTYPE_H
     37 #include <wctype.h>
     38 #else
     39 /* If we don't have wctype, we need to hack up some version of iswprint(). */
     40 #define	iswprint isprint
     41 #endif
     42 
     43 #include "bsdtar.h"
     44 #include "lafe_err.h"
     45 #include "passphrase.h"
     46 
     47 static size_t	bsdtar_expand_char(char *, size_t, size_t, char);
     48 static const char *strip_components(const char *path, int elements);
     49 
     50 #if defined(_WIN32) && !defined(__CYGWIN__)
     51 #define	read _read
     52 #endif
     53 
     54 /* TODO:  Hack up a version of mbtowc for platforms with no wide
     55  * character support at all.  I think the following might suffice,
     56  * but it needs careful testing.
     57  * #if !HAVE_MBTOWC
     58  * #define	mbtowc(wcp, p, n) ((*wcp = *p), 1)
     59  * #endif
     60  */
     61 
     62 /*
     63  * Print a string, taking care with any non-printable characters.
     64  *
     65  * Note that we use a stack-allocated buffer to receive the formatted
     66  * string if we can.  This is partly performance (avoiding a call to
     67  * malloc()), partly out of expedience (we have to call vsnprintf()
     68  * before malloc() anyway to find out how big a buffer we need; we may
     69  * as well point that first call at a small local buffer in case it
     70  * works).
     71  */
     72 
     73 void
     74 safe_fprintf(FILE * restrict f, const char * restrict fmt, ...)
     75 {
     76 	char fmtbuff_stack[256]; /* Place to format the printf() string. */
     77 	char outbuff[256]; /* Buffer for outgoing characters. */
     78 	char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
     79 	char *fmtbuff;  /* Pointer to fmtbuff_stack or fmtbuff_heap. */
     80 	size_t fmtbuff_length;
     81 	int length, n;
     82 	va_list ap;
     83 	const char *p;
     84 	size_t i;
     85 	wchar_t wc;
     86 	char try_wc;
     87 
     88 	/* Use a stack-allocated buffer if we can, for speed and safety. */
     89 	memset(fmtbuff_stack, '\0', sizeof(fmtbuff_stack));
     90 	fmtbuff_heap = NULL;
     91 	fmtbuff_length = sizeof(fmtbuff_stack);
     92 	fmtbuff = fmtbuff_stack;
     93 
     94 	/* Try formatting into the stack buffer. */
     95 	va_start(ap, fmt);
     96 	length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
     97 	va_end(ap);
     98 
     99 	/* If vsnprintf will always fail, stop early. */
    100 	if (length < 0 && errno == EOVERFLOW)
    101 		return;
    102 
    103 	/* If the result was too large, allocate a buffer on the heap. */
    104 	while (length < 0 || (size_t)length >= fmtbuff_length) {
    105 		if (length >= 0 && (size_t)length >= fmtbuff_length)
    106 			fmtbuff_length = (size_t)length + 1;
    107 		else if (fmtbuff_length < 8192)
    108 			fmtbuff_length *= 2;
    109 		else if (fmtbuff_length < 1000000)
    110 			fmtbuff_length += fmtbuff_length / 4;
    111 		else {
    112 			fmtbuff[fmtbuff_length - 1] = '\0';
    113 			length = (int)strlen(fmtbuff);
    114 			break;
    115 		}
    116 		free(fmtbuff_heap);
    117 		fmtbuff_heap = malloc(fmtbuff_length);
    118 
    119 		/* Reformat the result into the heap buffer if we can. */
    120 		if (fmtbuff_heap != NULL) {
    121 			fmtbuff = fmtbuff_heap;
    122 			va_start(ap, fmt);
    123 			length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
    124 			va_end(ap);
    125 		} else {
    126 			/* Leave fmtbuff pointing to the truncated
    127 			 * string in fmtbuff_stack. */
    128 			fmtbuff_stack[sizeof(fmtbuff_stack) - 1] = '\0';
    129 			fmtbuff = fmtbuff_stack;
    130 			length = (int)strlen(fmtbuff);
    131 			break;
    132 		}
    133 	}
    134 
    135 	/* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
    136 	 * more portable, so we use that here instead. */
    137 	if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */
    138 		/* mbtowc() should never fail in practice, but
    139 		 * handle the theoretical error anyway. */
    140 		free(fmtbuff_heap);
    141 		return;
    142 	}
    143 
    144 	/* Write data, expanding unprintable characters. */
    145 	p = fmtbuff;
    146 	i = 0;
    147 	try_wc = 1;
    148 	while (*p != '\0') {
    149 
    150 		/* Convert to wide char, test if the wide
    151 		 * char is printable in the current locale. */
    152 		if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
    153 			length -= n;
    154 			if (iswprint(wc) && wc != L'\\') {
    155 				/* Printable, copy the bytes through. */
    156 				while (n-- > 0)
    157 					outbuff[i++] = *p++;
    158 			} else {
    159 				/* Not printable, format the bytes. */
    160 				while (n-- > 0)
    161 					i += bsdtar_expand_char(
    162 					    outbuff, sizeof(outbuff), i, *p++);
    163 			}
    164 		} else {
    165 			/* After any conversion failure, don't bother
    166 			 * trying to convert the rest. */
    167 			i += bsdtar_expand_char(outbuff, sizeof(outbuff), i, *p++);
    168 			try_wc = 0;
    169 		}
    170 
    171 		/* If our output buffer is full, dump it and keep going. */
    172 		if (i > (sizeof(outbuff) - 128)) {
    173 			outbuff[i] = '\0';
    174 			fprintf(f, "%s", outbuff);
    175 			i = 0;
    176 		}
    177 	}
    178 	outbuff[i] = '\0';
    179 	fprintf(f, "%s", outbuff);
    180 
    181 	/* If we allocated a heap-based formatting buffer, free it now. */
    182 	free(fmtbuff_heap);
    183 }
    184 
    185 /*
    186  * Render an arbitrary sequence of bytes into printable ASCII characters.
    187  */
    188 static size_t
    189 bsdtar_expand_char(char *buff, size_t buffsize, size_t offset, char c)
    190 {
    191 	size_t i = offset;
    192 
    193 	if (isprint((unsigned char)c) && c != '\\')
    194 		buff[i++] = c;
    195 	else {
    196 		buff[i++] = '\\';
    197 		switch (c) {
    198 		case '\a': buff[i++] = 'a'; break;
    199 		case '\b': buff[i++] = 'b'; break;
    200 		case '\f': buff[i++] = 'f'; break;
    201 		case '\n': buff[i++] = 'n'; break;
    202 #if '\r' != '\n'
    203 		/* On some platforms, \n and \r are the same. */
    204 		case '\r': buff[i++] = 'r'; break;
    205 #endif
    206 		case '\t': buff[i++] = 't'; break;
    207 		case '\v': buff[i++] = 'v'; break;
    208 		case '\\': buff[i++] = '\\'; break;
    209 		default:
    210 			snprintf(buff + i, buffsize - i, "%03o",
    211 			    0xFF & (unsigned int)c);
    212 			i += 3;
    213 		}
    214 	}
    215 
    216 	return (i - offset);
    217 }
    218 
    219 int
    220 yes(const char *fmt, ...)
    221 {
    222 	char buff[32];
    223 	char *p;
    224 	ssize_t l;
    225 	int read_fd = 2; /* stderr */
    226 
    227 	va_list ap;
    228 	va_start(ap, fmt);
    229 	vfprintf(stderr, fmt, ap);
    230 	va_end(ap);
    231 	fprintf(stderr, " (y/N)? ");
    232 	fflush(stderr);
    233 
    234 #if defined(_WIN32) && !defined(__CYGWIN__)
    235 	/* To be resilient when stdin is a pipe, bsdtar prefers to read from
    236 	 * stderr.  On Windows, stderr cannot be read. The nearest "piping
    237 	 * resilient" equivalent is reopening the console input handle.
    238 	 */
    239 	read_fd = _open("CONIN$", O_RDONLY);
    240 	if (read_fd < 0) {
    241 	  fprintf(stderr, "Keyboard read failed\n");
    242 	  exit(1);
    243 	}
    244 #endif
    245 
    246 	l = read(read_fd, buff, sizeof(buff) - 1);
    247 
    248 #if defined(_WIN32) && !defined(__CYGWIN__)
    249 	_close(read_fd);
    250 #endif
    251 
    252 	if (l < 0) {
    253 	  fprintf(stderr, "Keyboard read failed\n");
    254 	  exit(1);
    255 	}
    256 	if (l == 0)
    257 		return (0);
    258 	buff[l] = 0;
    259 
    260 	for (p = buff; *p != '\0'; p++) {
    261 		if (isspace((unsigned char)*p))
    262 			continue;
    263 		switch(*p) {
    264 		case 'y': case 'Y':
    265 			return (1);
    266 		case 'n': case 'N':
    267 			return (0);
    268 		default:
    269 			return (0);
    270 		}
    271 	}
    272 
    273 	return (0);
    274 }
    275 
    276 /*-
    277  * The logic here for -C <dir> attempts to avoid
    278  * chdir() as long as possible.  For example:
    279  * "-C /foo -C /bar file"          needs chdir("/bar") but not chdir("/foo")
    280  * "-C /foo -C bar file"           needs chdir("/foo/bar")
    281  * "-C /foo -C bar /file1"         does not need chdir()
    282  * "-C /foo -C bar /file1 file2"   needs chdir("/foo/bar") before file2
    283  *
    284  * The only correct way to handle this is to record a "pending" chdir
    285  * request and combine multiple requests intelligently until we
    286  * need to process a non-absolute file.  set_chdir() adds the new dir
    287  * to the pending list; do_chdir() actually executes any pending chdir.
    288  *
    289  * This way, programs that build tar command lines don't have to worry
    290  * about -C with non-existent directories; such requests will only
    291  * fail if the directory must be accessed.
    292  *
    293  */
    294 void
    295 set_chdir(struct bsdtar *bsdtar, const char *newdir)
    296 {
    297 #if defined(_WIN32) && !defined(__CYGWIN__)
    298 	if (newdir[0] == '/' || newdir[0] == '\\' ||
    299 	    /* Detect this type, for example, "C:\" or "C:/" */
    300 	    (((newdir[0] >= 'a' && newdir[0] <= 'z') ||
    301 	      (newdir[0] >= 'A' && newdir[0] <= 'Z')) &&
    302 	    newdir[1] == ':' && (newdir[2] == '/' || newdir[2] == '\\'))) {
    303 #else
    304 	if (newdir[0] == '/') {
    305 #endif
    306 		/* The -C /foo -C /bar case; dump first one. */
    307 		free(bsdtar->pending_chdir);
    308 		bsdtar->pending_chdir = NULL;
    309 	}
    310 	if (bsdtar->pending_chdir == NULL)
    311 		/* Easy case: no previously-saved dir. */
    312 		bsdtar->pending_chdir = strdup(newdir);
    313 	else {
    314 		/* The -C /foo -C bar case; concatenate */
    315 		char *old_pending = bsdtar->pending_chdir;
    316 		size_t old_len = strlen(old_pending);
    317 		size_t newdir_len = strlen(newdir);
    318 		size_t new_len = old_len + newdir_len + 2;
    319 		if (old_len > SIZE_MAX - newdir_len - 2)
    320 		    lafe_errc(1, errno, "Path too long");
    321 		bsdtar->pending_chdir = malloc(new_len);
    322 		if (old_pending[old_len - 1] == '/')
    323 			old_pending[old_len - 1] = '\0';
    324 		if (bsdtar->pending_chdir != NULL)
    325 			snprintf(bsdtar->pending_chdir, new_len, "%s/%s",
    326 			    old_pending, newdir);
    327 		free(old_pending);
    328 	}
    329 	if (bsdtar->pending_chdir == NULL)
    330 		lafe_errc(1, errno, "No memory");
    331 }
    332 
    333 void
    334 do_chdir(struct bsdtar *bsdtar)
    335 {
    336 	if (bsdtar->pending_chdir == NULL)
    337 		return;
    338 
    339 	if (chdir(bsdtar->pending_chdir) != 0) {
    340 		lafe_errc(1, 0, "could not chdir to '%s'",
    341 		    bsdtar->pending_chdir);
    342 	}
    343 	free(bsdtar->pending_chdir);
    344 	bsdtar->pending_chdir = NULL;
    345 }
    346 
    347 static const char *
    348 strip_components(const char *p, int elements)
    349 {
    350 	/* Skip as many elements as necessary. */
    351 	while (elements > 0) {
    352 		switch (*p++) {
    353 		case '/':
    354 #if defined(_WIN32) && !defined(__CYGWIN__)
    355 		case '\\': /* Support \ path sep on Windows ONLY. */
    356 #endif
    357 			elements--;
    358 			break;
    359 		case '\0':
    360 			/* Path is too short, skip it. */
    361 			return (NULL);
    362 		}
    363 	}
    364 
    365 	/* Skip any / characters.  This handles short paths that have
    366 	 * additional / termination.  This also handles the case where
    367 	 * the logic above stops in the middle of a duplicate //
    368 	 * sequence (which would otherwise get converted to an
    369 	 * absolute path). */
    370 	for (;;) {
    371 		switch (*p) {
    372 		case '/':
    373 #if defined(_WIN32) && !defined(__CYGWIN__)
    374 		case '\\': /* Support \ path sep on Windows ONLY. */
    375 #endif
    376 			++p;
    377 			break;
    378 		case '\0':
    379 			return (NULL);
    380 		default:
    381 			return (p);
    382 		}
    383 	}
    384 }
    385 
    386 static void
    387 warn_strip_leading_char(struct bsdtar *bsdtar, const char *c)
    388 {
    389 	if (!bsdtar->warned_lead_slash) {
    390 		lafe_warnc(0,
    391 			   "Removing leading '%c' from member names",
    392 			   c[0]);
    393 		bsdtar->warned_lead_slash = 1;
    394 	}
    395 }
    396 
    397 static void
    398 warn_strip_drive_letter(struct bsdtar *bsdtar)
    399 {
    400 	if (!bsdtar->warned_lead_slash) {
    401 		lafe_warnc(0,
    402 			   "Removing leading drive letter from "
    403 			   "member names");
    404 		bsdtar->warned_lead_slash = 1;
    405 	}
    406 }
    407 
    408 /*
    409  * Convert absolute path to non-absolute path by skipping leading
    410  * absolute path prefixes.
    411  */
    412 static const char*
    413 strip_absolute_path(struct bsdtar *bsdtar, const char *p)
    414 {
    415 	const char *rp;
    416 
    417 	/* Remove leading "//./" or "//?/" or "//?/UNC/"
    418 	 * (absolute path prefixes used by Windows API) */
    419 	if ((p[0] == '/' || p[0] == '\\') &&
    420 	    (p[1] == '/' || p[1] == '\\') &&
    421 	    (p[2] == '.' || p[2] == '?') &&
    422 	    (p[3] == '/' || p[3] == '\\'))
    423 	{
    424 		if (p[2] == '?' &&
    425 		    (p[4] == 'U' || p[4] == 'u') &&
    426 		    (p[5] == 'N' || p[5] == 'n') &&
    427 		    (p[6] == 'C' || p[6] == 'c') &&
    428 		    (p[7] == '/' || p[7] == '\\'))
    429 			p += 8;
    430 		else
    431 			p += 4;
    432 		warn_strip_drive_letter(bsdtar);
    433 	}
    434 
    435 	/* Remove multiple leading slashes and Windows drive letters. */
    436 	do {
    437 		rp = p;
    438 		if (((p[0] >= 'a' && p[0] <= 'z') ||
    439 		     (p[0] >= 'A' && p[0] <= 'Z')) &&
    440 		    p[1] == ':') {
    441 			p += 2;
    442 			warn_strip_drive_letter(bsdtar);
    443 		}
    444 
    445 		/* Remove leading "/../", "/./", "//", etc. */
    446 		while (p[0] == '/' || p[0] == '\\') {
    447 			if (p[1] == '.' &&
    448 			    p[2] == '.' &&
    449 			    (p[3] == '/' || p[3] == '\\')) {
    450 				p += 3; /* Remove "/..", leave "/" for next pass. */
    451 			} else if (p[1] == '.' &&
    452 				   (p[2] == '/' || p[2] == '\\')) {
    453 				p += 2; /* Remove "/.", leave "/" for next pass. */
    454 			} else
    455 				p += 1; /* Remove "/". */
    456 			warn_strip_leading_char(bsdtar, rp);
    457 		}
    458 	} while (rp != p);
    459 
    460 	return (p);
    461 }
    462 
    463 /*
    464  * Handle --strip-components and any future path-rewriting options.
    465  * Returns non-zero if the pathname should not be extracted.
    466  *
    467  * Note: The rewrites are applied uniformly to pathnames and hardlink
    468  * names but not to symlink bodies.  This is deliberate: Symlink
    469  * bodies are not necessarily filenames.  Even when they are, they
    470  * need to be interpreted relative to the directory containing them,
    471  * so simple rewrites like this are rarely appropriate.
    472  *
    473  * TODO: Support pax-style regex path rewrites.
    474  */
    475 int
    476 edit_pathname(struct bsdtar *bsdtar, struct archive_entry *entry)
    477 {
    478 	const char *name = archive_entry_pathname(entry);
    479 	const char *original_name = name;
    480 	const char *hardlinkname = archive_entry_hardlink(entry);
    481 	const char *original_hardlinkname = hardlinkname;
    482 #if defined(HAVE_REGEX_H) || defined(HAVE_PCREPOSIX_H) || defined(HAVE_PCRE2POSIX_H)
    483 	char *subst_name;
    484 	int r;
    485 
    486 	/* Apply user-specified substitution to pathname. */
    487 	r = apply_substitution(bsdtar, name, &subst_name, 0, 0);
    488 	if (r == -1) {
    489 		lafe_warnc(0, "Invalid substitution, skipping entry");
    490 		return 1;
    491 	}
    492 	if (r == 1) {
    493 		archive_entry_copy_pathname(entry, subst_name);
    494 		if (*subst_name == '\0') {
    495 			free(subst_name);
    496 			return -1;
    497 		} else
    498 			free(subst_name);
    499 		name = archive_entry_pathname(entry);
    500 		original_name = name;
    501 	}
    502 
    503 	/* Apply user-specified substitution to hardlink target. */
    504 	if (hardlinkname != NULL) {
    505 		r = apply_substitution(bsdtar, hardlinkname, &subst_name, 0, 1);
    506 		if (r == -1) {
    507 			lafe_warnc(0, "Invalid substitution, skipping entry");
    508 			return 1;
    509 		}
    510 		if (r == 1) {
    511 			archive_entry_copy_hardlink(entry, subst_name);
    512 			free(subst_name);
    513 		}
    514 		hardlinkname = archive_entry_hardlink(entry);
    515 		original_hardlinkname = hardlinkname;
    516 	}
    517 
    518 	/* Apply user-specified substitution to symlink body. */
    519 	if (archive_entry_symlink(entry) != NULL) {
    520 		r = apply_substitution(bsdtar, archive_entry_symlink(entry), &subst_name, 1, 0);
    521 		if (r == -1) {
    522 			lafe_warnc(0, "Invalid substitution, skipping entry");
    523 			return 1;
    524 		}
    525 		if (r == 1) {
    526 			archive_entry_copy_symlink(entry, subst_name);
    527 			free(subst_name);
    528 		}
    529 	}
    530 #endif
    531 
    532 	/* Strip leading dir names as per --strip-components option. */
    533 	if (bsdtar->strip_components > 0) {
    534 		name = strip_components(name, bsdtar->strip_components);
    535 		if (name == NULL)
    536 			return (1);
    537 
    538 		if (hardlinkname != NULL) {
    539 			hardlinkname = strip_components(hardlinkname,
    540 			    bsdtar->strip_components);
    541 			if (hardlinkname == NULL)
    542 				return (1);
    543 		}
    544 	}
    545 
    546 	if ((bsdtar->flags & OPTFLAG_ABSOLUTE_PATHS) == 0) {
    547 		/* By default, don't write or restore absolute pathnames. */
    548 		name = strip_absolute_path(bsdtar, name);
    549 		if (*name == '\0')
    550 			name = ".";
    551 
    552 		if (hardlinkname != NULL) {
    553 			hardlinkname = strip_absolute_path(bsdtar, hardlinkname);
    554 			if (*hardlinkname == '\0')
    555 				return (1);
    556 		}
    557 	} else {
    558 		/* Strip redundant leading '/' characters. */
    559 		while (name[0] == '/' && name[1] == '/')
    560 			name++;
    561 	}
    562 
    563 	/* Replace name in archive_entry. */
    564 	if (name != original_name) {
    565 		archive_entry_copy_pathname(entry, name);
    566 	}
    567 	if (hardlinkname != original_hardlinkname) {
    568 		archive_entry_copy_hardlink(entry, hardlinkname);
    569 	}
    570 	return (0);
    571 }
    572 
    573 /*
    574  * Apply --mtime and --clamp-mtime options.
    575  */
    576 void
    577 edit_mtime(struct bsdtar *bsdtar, struct archive_entry *entry)
    578 {
    579 	if (!bsdtar->has_mtime)
    580 		return;
    581 
    582 	__LA_TIME_T entry_mtime = archive_entry_mtime(entry);
    583 	if (!bsdtar->clamp_mtime || entry_mtime > bsdtar->mtime)
    584 		archive_entry_set_mtime(entry, bsdtar->mtime, 0);
    585 }
    586 
    587 /*
    588  * It would be nice to just use printf() for formatting large numbers,
    589  * but the compatibility problems are quite a headache.  Hence the
    590  * following simple utility function.
    591  */
    592 const char *
    593 tar_i64toa(int64_t n0)
    594 {
    595 	static char buff[24];
    596 	uint64_t n = n0 < 0 ? -n0 : n0;
    597 	char *p = buff + sizeof(buff);
    598 
    599 	*--p = '\0';
    600 	do {
    601 		*--p = '0' + (int)(n % 10);
    602 	} while (n /= 10);
    603 	if (n0 < 0)
    604 		*--p = '-';
    605 	return p;
    606 }
    607 
    608 /*
    609  * Like strcmp(), but try to be a little more aware of the fact that
    610  * we're comparing two paths.  Right now, it just handles leading
    611  * "./" and trailing '/' specially, so that "a/b/" == "./a/b"
    612  *
    613  * TODO: Make this better, so that "./a//b/./c/" == "a/b/c"
    614  * TODO: After this works, push it down into libarchive.
    615  * TODO: Publish the path normalization routines in libarchive so
    616  * that bsdtar can normalize paths and use fast strcmp() instead
    617  * of this.
    618  *
    619  * Note: This is currently only used within write.c, so should
    620  * not handle \ path separators.
    621  */
    622 
    623 int
    624 pathcmp(const char *a, const char *b)
    625 {
    626 	/* Skip leading './' */
    627 	if (a[0] == '.' && a[1] == '/' && a[2] != '\0')
    628 		a += 2;
    629 	if (b[0] == '.' && b[1] == '/' && b[2] != '\0')
    630 		b += 2;
    631 	/* Find the first difference, or return (0) if none. */
    632 	while (*a == *b) {
    633 		if (*a == '\0')
    634 			return (0);
    635 		a++;
    636 		b++;
    637 	}
    638 	/*
    639 	 * If one ends in '/' and the other one doesn't,
    640 	 * they're the same.
    641 	 */
    642 	if (a[0] == '/' && a[1] == '\0' && b[0] == '\0')
    643 		return (0);
    644 	if (a[0] == '\0' && b[0] == '/' && b[1] == '\0')
    645 		return (0);
    646 	/* They're really different, return the correct sign. */
    647 	return (*(const unsigned char *)a - *(const unsigned char *)b);
    648 }
    649 
    650 #define PPBUFF_SIZE 1024
    651 const char *
    652 passphrase_callback(struct archive *a, void *_client_data)
    653 {
    654 	struct bsdtar *bsdtar = (struct bsdtar *)_client_data;
    655 	(void)a; /* UNUSED */
    656 
    657 	if (bsdtar->ppbuff == NULL) {
    658 		bsdtar->ppbuff = malloc(PPBUFF_SIZE);
    659 		if (bsdtar->ppbuff == NULL)
    660 			lafe_errc(1, errno, "Out of memory");
    661 	}
    662 	return lafe_readpassphrase("Enter passphrase:",
    663 		bsdtar->ppbuff, PPBUFF_SIZE);
    664 }
    665 
    666 void
    667 passphrase_free(char *ppbuff)
    668 {
    669 	if (ppbuff != NULL) {
    670 		memset(ppbuff, 0, PPBUFF_SIZE);
    671 		free(ppbuff);
    672 	}
    673 }
    674 
    675 /*
    676  * Display information about the current file.
    677  *
    678  * The format here roughly duplicates the output of 'ls -l'.
    679  * This is based on SUSv2, where 'tar tv' is documented as
    680  * listing additional information in an "unspecified format,"
    681  * and 'pax -l' is documented as using the same format as 'ls -l'.
    682  */
    683 void
    684 list_item_verbose(struct bsdtar *bsdtar, FILE *out, struct archive_entry *entry)
    685 {
    686 	char			 tmp[100];
    687 	size_t			 w;
    688 	size_t			 sw;
    689 	const char		*p;
    690 	const char		*fmt;
    691 	time_t			 tim;
    692 	static time_t		 now;
    693 	struct tm		*ltime;
    694 #if defined(HAVE_LOCALTIME_R) || defined(HAVE_LOCALTIME_S)
    695 	struct tm		tmbuf;
    696 #endif
    697 
    698 	/*
    699 	 * We avoid collecting the entire list in memory at once by
    700 	 * listing things as we see them.  However, that also means we can't
    701 	 * just pre-compute the field widths.  Instead, we start with guesses
    702 	 * and just widen them as necessary.  These numbers are completely
    703 	 * arbitrary.
    704 	 */
    705 	if (!bsdtar->u_width) {
    706 		bsdtar->u_width = 6;
    707 		bsdtar->gs_width = 13;
    708 	}
    709 	if (!now)
    710 		time(&now);
    711 	fprintf(out, "%s %u ",
    712 	    archive_entry_strmode(entry),
    713 	    archive_entry_nlink(entry));
    714 
    715 	/* Use uname if it's present, else uid. */
    716 	p = archive_entry_uname(entry);
    717 	if ((p == NULL) || (*p == '\0')) {
    718 		snprintf(tmp, sizeof(tmp), "%lld ",
    719 		    (long long)archive_entry_uid(entry));
    720 		p = tmp;
    721 	}
    722 	w = strlen(p);
    723 	if (w > bsdtar->u_width)
    724 		bsdtar->u_width = w;
    725 	fprintf(out, "%-*s ", (int)bsdtar->u_width, p);
    726 
    727 	/* Use gname if it's present, else gid. */
    728 	p = archive_entry_gname(entry);
    729 	if (p != NULL && p[0] != '\0') {
    730 		fprintf(out, "%s", p);
    731 		w = strlen(p);
    732 	} else {
    733 		snprintf(tmp, sizeof(tmp), "%lld",
    734 		    (long long)archive_entry_gid(entry));
    735 		w = strlen(tmp);
    736 		fprintf(out, "%s", tmp);
    737 	}
    738 
    739 	/*
    740 	 * Print device number or file size, right-aligned so as to make
    741 	 * total width of group and devnum/filesize fields be gs_width.
    742 	 * If gs_width is too small, grow it.
    743 	 */
    744 	if (archive_entry_filetype(entry) == AE_IFCHR
    745 	    || archive_entry_filetype(entry) == AE_IFBLK) {
    746 		snprintf(tmp, sizeof(tmp), "%lu,%lu",
    747 		    (unsigned long)archive_entry_rdevmajor(entry),
    748 		    (unsigned long)archive_entry_rdevminor(entry));
    749 	} else {
    750 		strcpy(tmp, tar_i64toa(archive_entry_size(entry)));
    751 	}
    752 	if (w + strlen(tmp) >= bsdtar->gs_width)
    753 		bsdtar->gs_width = w+strlen(tmp)+1;
    754 	fprintf(out, "%*s", (int)(bsdtar->gs_width - w), tmp);
    755 
    756 	/* Format the time using 'ls -l' conventions. */
    757 	tim = archive_entry_mtime(entry);
    758 #define	HALF_YEAR (time_t)365 * 86400 / 2
    759 #if defined(_WIN32) && !defined(__CYGWIN__)
    760 #define	DAY_FMT  "%d"  /* Windows' strftime function does not support %e format. */
    761 #else
    762 #define	DAY_FMT  "%e"  /* Day number without leading zeros */
    763 #endif
    764 	if (tim < now - HALF_YEAR || tim > now + HALF_YEAR)
    765 		fmt = bsdtar->day_first ? DAY_FMT " %b  %Y" : "%b " DAY_FMT "  %Y";
    766 	else
    767 		fmt = bsdtar->day_first ? DAY_FMT " %b %H:%M" : "%b " DAY_FMT " %H:%M";
    768 #if defined(HAVE_LOCALTIME_S)
    769 	ltime = localtime_s(&tmbuf, &tim) ? NULL : &tmbuf;
    770 #elif defined(HAVE_LOCALTIME_R)
    771 	ltime = localtime_r(&tim, &tmbuf);
    772 #else
    773 	ltime = localtime(&tim);
    774 #endif
    775 	if (ltime)
    776 		sw = strftime(tmp, sizeof(tmp), fmt, ltime);
    777 	if (!ltime || !sw)
    778 		sprintf(tmp, "-- -- ----");
    779 	fprintf(out, " %s ", tmp);
    780 	safe_fprintf(out, "%s", archive_entry_pathname(entry));
    781 
    782 	/* Extra information for links. */
    783 	if (archive_entry_hardlink(entry)) /* Hard link */
    784 		safe_fprintf(out, " link to %s",
    785 		    archive_entry_hardlink(entry));
    786 	else if (archive_entry_symlink(entry)) /* Symbolic link */
    787 		safe_fprintf(out, " -> %s", archive_entry_symlink(entry));
    788 }
    789