95d0db5d470a5dad76cfcf5392df57ade20be5dc
[dragonfly.git] / contrib / libarchive / tar / util.c
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: src/usr.bin/tar/util.c,v 1.23 2008/12/15 06:00:25 kientzle Exp $");
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         if (length >= fmtbuff_length) {
119                 fmtbuff_length = length+1;
120                 fmtbuff_heap = malloc(fmtbuff_length);
121
122                 /* Reformat the result into the heap buffer if we can. */
123                 if (fmtbuff_heap != NULL) {
124                         fmtbuff = fmtbuff_heap;
125                         va_start(ap, fmt);
126                         length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
127                         va_end(ap);
128                 } else {
129                         /* Leave fmtbuff pointing to the truncated
130                          * string in fmtbuff_stack. */
131                         length = sizeof(fmtbuff_stack) - 1;
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         n = mbtowc(NULL, NULL, 1); /* Reset the shift state. */
138
139         /* Write data, expanding unprintable characters. */
140         p = fmtbuff;
141         i = 0;
142         try_wc = 1;
143         while (*p != '\0') {
144
145                 /* Convert to wide char, test if the wide
146                  * char is printable in the current locale. */
147                 if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
148                         length -= n;
149                         if (iswprint(wc) && wc != L'\\') {
150                                 /* Printable, copy the bytes through. */
151                                 while (n-- > 0)
152                                         outbuff[i++] = *p++;
153                         } else {
154                                 /* Not printable, format the bytes. */
155                                 while (n-- > 0)
156                                         i += (unsigned)bsdtar_expand_char(
157                                             outbuff, i, *p++);
158                         }
159                 } else {
160                         /* After any conversion failure, don't bother
161                          * trying to convert the rest. */
162                         i += (unsigned)bsdtar_expand_char(outbuff, i, *p++);
163                         try_wc = 0;
164                 }
165
166                 /* If our output buffer is full, dump it and keep going. */
167                 if (i > (sizeof(outbuff) - 20)) {
168                         outbuff[i] = '\0';
169                         fprintf(f, "%s", outbuff);
170                         i = 0;
171                 }
172         }
173         outbuff[i] = '\0';
174         fprintf(f, "%s", outbuff);
175
176         /* If we allocated a heap-based formatting buffer, free it now. */
177         if (fmtbuff_heap != NULL)
178                 free(fmtbuff_heap);
179 }
180
181 /*
182  * Render an arbitrary sequence of bytes into printable ASCII characters.
183  */
184 static size_t
185 bsdtar_expand_char(char *buff, size_t offset, char c)
186 {
187         size_t i = offset;
188
189         if (isprint((unsigned char)c) && c != '\\')
190                 buff[i++] = c;
191         else {
192                 buff[i++] = '\\';
193                 switch (c) {
194                 case '\a': buff[i++] = 'a'; break;
195                 case '\b': buff[i++] = 'b'; break;
196                 case '\f': buff[i++] = 'f'; break;
197                 case '\n': buff[i++] = 'n'; break;
198 #if '\r' != '\n'
199                 /* On some platforms, \n and \r are the same. */
200                 case '\r': buff[i++] = 'r'; break;
201 #endif
202                 case '\t': buff[i++] = 't'; break;
203                 case '\v': buff[i++] = 'v'; break;
204                 case '\\': buff[i++] = '\\'; break;
205                 default:
206                         sprintf(buff + i, "%03o", 0xFF & (int)c);
207                         i += 3;
208                 }
209         }
210
211         return (i - offset);
212 }
213
214 int
215 yes(const char *fmt, ...)
216 {
217         char buff[32];
218         char *p;
219         ssize_t l;
220
221         va_list ap;
222         va_start(ap, fmt);
223         vfprintf(stderr, fmt, ap);
224         va_end(ap);
225         fprintf(stderr, " (y/N)? ");
226         fflush(stderr);
227
228         l = read(2, buff, sizeof(buff) - 1);
229         if (l < 0) {
230           fprintf(stderr, "Keyboard read failed\n");
231           exit(1);
232         }
233         if (l == 0)
234                 return (0);
235         buff[l] = 0;
236
237         for (p = buff; *p != '\0'; p++) {
238                 if (isspace((unsigned char)*p))
239                         continue;
240                 switch(*p) {
241                 case 'y': case 'Y':
242                         return (1);
243                 case 'n': case 'N':
244                         return (0);
245                 default:
246                         return (0);
247                 }
248         }
249
250         return (0);
251 }
252
253 /*-
254  * The logic here for -C <dir> attempts to avoid
255  * chdir() as long as possible.  For example:
256  * "-C /foo -C /bar file"          needs chdir("/bar") but not chdir("/foo")
257  * "-C /foo -C bar file"           needs chdir("/foo/bar")
258  * "-C /foo -C bar /file1"         does not need chdir()
259  * "-C /foo -C bar /file1 file2"   needs chdir("/foo/bar") before file2
260  *
261  * The only correct way to handle this is to record a "pending" chdir
262  * request and combine multiple requests intelligently until we
263  * need to process a non-absolute file.  set_chdir() adds the new dir
264  * to the pending list; do_chdir() actually executes any pending chdir.
265  *
266  * This way, programs that build tar command lines don't have to worry
267  * about -C with non-existent directories; such requests will only
268  * fail if the directory must be accessed.
269  *
270  */
271 void
272 set_chdir(struct bsdtar *bsdtar, const char *newdir)
273 {
274 #if defined(_WIN32) && !defined(__CYGWIN__)
275         if (newdir[0] == '/' || newdir[0] == '\\' ||
276             /* Detect this type, for example, "C:\" or "C:/" */
277             (((newdir[0] >= 'a' && newdir[0] <= 'z') ||
278               (newdir[0] >= 'A' && newdir[0] <= 'Z')) &&
279             newdir[1] == ':' && (newdir[2] == '/' || newdir[2] == '\\'))) {
280 #else
281         if (newdir[0] == '/') {
282 #endif
283                 /* The -C /foo -C /bar case; dump first one. */
284                 free(bsdtar->pending_chdir);
285                 bsdtar->pending_chdir = NULL;
286         }
287         if (bsdtar->pending_chdir == NULL)
288                 /* Easy case: no previously-saved dir. */
289                 bsdtar->pending_chdir = strdup(newdir);
290         else {
291                 /* The -C /foo -C bar case; concatenate */
292                 char *old_pending = bsdtar->pending_chdir;
293                 size_t old_len = strlen(old_pending);
294                 bsdtar->pending_chdir = malloc(old_len + strlen(newdir) + 2);
295                 if (old_pending[old_len - 1] == '/')
296                         old_pending[old_len - 1] = '\0';
297                 if (bsdtar->pending_chdir != NULL)
298                         sprintf(bsdtar->pending_chdir, "%s/%s",
299                             old_pending, newdir);
300                 free(old_pending);
301         }
302         if (bsdtar->pending_chdir == NULL)
303                 lafe_errc(1, errno, "No memory");
304 }
305
306 void
307 do_chdir(struct bsdtar *bsdtar)
308 {
309         if (bsdtar->pending_chdir == NULL)
310                 return;
311
312         if (chdir(bsdtar->pending_chdir) != 0) {
313                 lafe_errc(1, 0, "could not chdir to '%s'\n",
314                     bsdtar->pending_chdir);
315         }
316         free(bsdtar->pending_chdir);
317         bsdtar->pending_chdir = NULL;
318 }
319
320 static const char *
321 strip_components(const char *p, int elements)
322 {
323         /* Skip as many elements as necessary. */
324         while (elements > 0) {
325                 switch (*p++) {
326                 case '/':
327 #if defined(_WIN32) && !defined(__CYGWIN__)
328                 case '\\': /* Support \ path sep on Windows ONLY. */
329 #endif
330                         elements--;
331                         break;
332                 case '\0':
333                         /* Path is too short, skip it. */
334                         return (NULL);
335                 }
336         }
337
338         /* Skip any / characters.  This handles short paths that have
339          * additional / termination.  This also handles the case where
340          * the logic above stops in the middle of a duplicate //
341          * sequence (which would otherwise get converted to an
342          * absolute path). */
343         for (;;) {
344                 switch (*p) {
345                 case '/':
346 #if defined(_WIN32) && !defined(__CYGWIN__)
347                 case '\\': /* Support \ path sep on Windows ONLY. */
348 #endif
349                         ++p;
350                         break;
351                 case '\0':
352                         return (NULL);
353                 default:
354                         return (p);
355                 }
356         }
357 }
358
359 /*
360  * Handle --strip-components and any future path-rewriting options.
361  * Returns non-zero if the pathname should not be extracted.
362  *
363  * TODO: Support pax-style regex path rewrites.
364  */
365 int
366 edit_pathname(struct bsdtar *bsdtar, struct archive_entry *entry)
367 {
368         const char *name = archive_entry_pathname(entry);
369 #if HAVE_REGEX_H
370         char *subst_name;
371         int r;
372
373         r = apply_substitution(bsdtar, name, &subst_name, 0, 0);
374         if (r == -1) {
375                 lafe_warnc(0, "Invalid substitution, skipping entry");
376                 return 1;
377         }
378         if (r == 1) {
379                 archive_entry_copy_pathname(entry, subst_name);
380                 if (*subst_name == '\0') {
381                         free(subst_name);
382                         return -1;
383                 } else
384                         free(subst_name);
385                 name = archive_entry_pathname(entry);
386         }
387
388         if (archive_entry_hardlink(entry)) {
389                 r = apply_substitution(bsdtar, archive_entry_hardlink(entry), &subst_name, 0, 1);
390                 if (r == -1) {
391                         lafe_warnc(0, "Invalid substitution, skipping entry");
392                         return 1;
393                 }
394                 if (r == 1) {
395                         archive_entry_copy_hardlink(entry, subst_name);
396                         free(subst_name);
397                 }
398         }
399         if (archive_entry_symlink(entry) != NULL) {
400                 r = apply_substitution(bsdtar, archive_entry_symlink(entry), &subst_name, 1, 0);
401                 if (r == -1) {
402                         lafe_warnc(0, "Invalid substitution, skipping entry");
403                         return 1;
404                 }
405                 if (r == 1) {
406                         archive_entry_copy_symlink(entry, subst_name);
407                         free(subst_name);
408                 }
409         }
410 #endif
411
412         /* Strip leading dir names as per --strip-components option. */
413         if (bsdtar->strip_components > 0) {
414                 const char *linkname = archive_entry_hardlink(entry);
415
416                 name = strip_components(name, bsdtar->strip_components);
417                 if (name == NULL)
418                         return (1);
419
420                 if (linkname != NULL) {
421                         linkname = strip_components(linkname,
422                             bsdtar->strip_components);
423                         if (linkname == NULL)
424                                 return (1);
425                         archive_entry_copy_hardlink(entry, linkname);
426                 }
427         }
428
429         /* By default, don't write or restore absolute pathnames. */
430         if (!bsdtar->option_absolute_paths) {
431                 const char *rp, *p = name;
432                 int slashonly = 1;
433
434                 /* Remove leading "//./" or "//?/" or "//?/UNC/"
435                  * (absolute path prefixes used by Windows API) */
436                 if ((p[0] == '/' || p[0] == '\\') &&
437                     (p[1] == '/' || p[1] == '\\') &&
438                     (p[2] == '.' || p[2] == '?') &&
439                     (p[3] == '/' || p[3] == '\\'))
440                 {
441                         if (p[2] == '?' &&
442                             (p[4] == 'U' || p[4] == 'u') &&
443                             (p[5] == 'N' || p[5] == 'n') &&
444                             (p[6] == 'C' || p[6] == 'c') &&
445                             (p[7] == '/' || p[7] == '\\'))
446                                 p += 8;
447                         else
448                                 p += 4;
449                         slashonly = 0;
450                 }
451                 do {
452                         rp = p;
453                         /* Remove leading drive letter from archives created
454                          * on Windows. */
455                         if (((p[0] >= 'a' && p[0] <= 'z') ||
456                              (p[0] >= 'A' && p[0] <= 'Z')) &&
457                                  p[1] == ':') {
458                                 p += 2;
459                                 slashonly = 0;
460                         }
461                         /* Remove leading "/../", "//", etc. */
462                         while (p[0] == '/' || p[0] == '\\') {
463                                 if (p[1] == '.' && p[2] == '.' &&
464                                         (p[3] == '/' || p[3] == '\\')) {
465                                         p += 3; /* Remove "/..", leave "/"
466                                                          * for next pass. */
467                                         slashonly = 0;
468                                 } else
469                                         p += 1; /* Remove "/". */
470                         }
471                 } while (rp != p);
472
473                 if (p != name && !bsdtar->warned_lead_slash) {
474                         /* Generate a warning the first time this happens. */
475                         if (slashonly)
476                                 lafe_warnc(0,
477                                     "Removing leading '%c' from member names",
478                                     name[0]);
479                         else
480                                 lafe_warnc(0,
481                                     "Removing leading drive letter from "
482                                     "member names");
483                         bsdtar->warned_lead_slash = 1;
484                 }
485
486                 /* Special case: Stripping everything yields ".". */
487                 if (*p == '\0')
488                         name = ".";
489                 else
490                         name = p;
491         } else {
492                 /* Strip redundant leading '/' characters. */
493                 while (name[0] == '/' && name[1] == '/')
494                         name++;
495         }
496
497         /* Safely replace name in archive_entry. */
498         if (name != archive_entry_pathname(entry)) {
499                 char *q = strdup(name);
500                 archive_entry_copy_pathname(entry, q);
501                 free(q);
502         }
503         return (0);
504 }
505
506 /*
507  * It would be nice to just use printf() for formatting large numbers,
508  * but the compatibility problems are quite a headache.  Hence the
509  * following simple utility function.
510  */
511 const char *
512 tar_i64toa(int64_t n0)
513 {
514         static char buff[24];
515         uint64_t n = n0 < 0 ? -n0 : n0;
516         char *p = buff + sizeof(buff);
517
518         *--p = '\0';
519         do {
520                 *--p = '0' + (int)(n % 10);
521         } while (n /= 10);
522         if (n0 < 0)
523                 *--p = '-';
524         return p;
525 }
526
527 /*
528  * Like strcmp(), but try to be a little more aware of the fact that
529  * we're comparing two paths.  Right now, it just handles leading
530  * "./" and trailing '/' specially, so that "a/b/" == "./a/b"
531  *
532  * TODO: Make this better, so that "./a//b/./c/" == "a/b/c"
533  * TODO: After this works, push it down into libarchive.
534  * TODO: Publish the path normalization routines in libarchive so
535  * that bsdtar can normalize paths and use fast strcmp() instead
536  * of this.
537  *
538  * Note: This is currently only used within write.c, so should
539  * not handle \ path separators.
540  */
541
542 int
543 pathcmp(const char *a, const char *b)
544 {
545         /* Skip leading './' */
546         if (a[0] == '.' && a[1] == '/' && a[2] != '\0')
547                 a += 2;
548         if (b[0] == '.' && b[1] == '/' && b[2] != '\0')
549                 b += 2;
550         /* Find the first difference, or return (0) if none. */
551         while (*a == *b) {
552                 if (*a == '\0')
553                         return (0);
554                 a++;
555                 b++;
556         }
557         /*
558          * If one ends in '/' and the other one doesn't,
559          * they're the same.
560          */
561         if (a[0] == '/' && a[1] == '\0' && b[0] == '\0')
562                 return (0);
563         if (a[0] == '\0' && b[0] == '/' && b[1] == '\0')
564                 return (0);
565         /* They're really different, return the correct sign. */
566         return (*(const unsigned char *)a - *(const unsigned char *)b);
567 }