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