]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - usr.bin/tar/util.c
Copy stable/8 to releng/8.2 in preparation for FreeBSD-8.2 release.
[FreeBSD/releng/8.2.git] / usr.bin / 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$");
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_STDARG_H
40 #include <stdarg.h>
41 #endif
42 #include <stdio.h>
43 #ifdef HAVE_STDLIB_H
44 #include <stdlib.h>
45 #endif
46 #ifdef HAVE_STRING_H
47 #include <string.h>
48 #endif
49 #ifdef HAVE_WCTYPE_H
50 #include <wctype.h>
51 #else
52 /* If we don't have wctype, we need to hack up some version of iswprint(). */
53 #define iswprint isprint
54 #endif
55
56 #include "bsdtar.h"
57 #include "err.h"
58
59 static size_t   bsdtar_expand_char(char *, size_t, char);
60 static const char *strip_components(const char *path, int elements);
61
62 /* TODO:  Hack up a version of mbtowc for platforms with no wide
63  * character support at all.  I think the following might suffice,
64  * but it needs careful testing.
65  * #if !HAVE_MBTOWC
66  * #define mbtowc(wcp, p, n) ((*wcp = *p), 1)
67  * #endif
68  */
69
70 /*
71  * Print a string, taking care with any non-printable characters.
72  *
73  * Note that we use a stack-allocated buffer to receive the formatted
74  * string if we can.  This is partly performance (avoiding a call to
75  * malloc()), partly out of expedience (we have to call vsnprintf()
76  * before malloc() anyway to find out how big a buffer we need; we may
77  * as well point that first call at a small local buffer in case it
78  * works), but mostly for safety (so we can use this to print messages
79  * about out-of-memory conditions).
80  */
81
82 void
83 safe_fprintf(FILE *f, const char *fmt, ...)
84 {
85         char fmtbuff_stack[256]; /* Place to format the printf() string. */
86         char outbuff[256]; /* Buffer for outgoing characters. */
87         char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
88         char *fmtbuff;  /* Pointer to fmtbuff_stack or fmtbuff_heap. */
89         int fmtbuff_length;
90         int length;
91         va_list ap;
92         const char *p;
93         unsigned i;
94         wchar_t wc;
95         char try_wc;
96
97         /* Use a stack-allocated buffer if we can, for speed and safety. */
98         fmtbuff_heap = NULL;
99         fmtbuff_length = sizeof(fmtbuff_stack);
100         fmtbuff = fmtbuff_stack;
101
102         /* Try formatting into the stack buffer. */
103         va_start(ap, fmt);
104         length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
105         va_end(ap);
106
107         /* If the result was too large, allocate a buffer on the heap. */
108         if (length >= fmtbuff_length) {
109                 fmtbuff_length = length+1;
110                 fmtbuff_heap = malloc(fmtbuff_length);
111
112                 /* Reformat the result into the heap buffer if we can. */
113                 if (fmtbuff_heap != NULL) {
114                         fmtbuff = fmtbuff_heap;
115                         va_start(ap, fmt);
116                         length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
117                         va_end(ap);
118                 } else {
119                         /* Leave fmtbuff pointing to the truncated
120                          * string in fmtbuff_stack. */
121                         length = sizeof(fmtbuff_stack) - 1;
122                 }
123         }
124
125         /* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
126          * more portable, so we use that here instead. */
127         mbtowc(NULL, NULL, 0); /* Reset the shift state. */
128
129         /* Write data, expanding unprintable characters. */
130         p = fmtbuff;
131         i = 0;
132         try_wc = 1;
133         while (*p != '\0') {
134                 int n;
135
136                 /* Convert to wide char, test if the wide
137                  * char is printable in the current locale. */
138                 if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
139                         length -= n;
140                         if (iswprint(wc) && wc != L'\\') {
141                                 /* Printable, copy the bytes through. */
142                                 while (n-- > 0)
143                                         outbuff[i++] = *p++;
144                         } else {
145                                 /* Not printable, format the bytes. */
146                                 while (n-- > 0)
147                                         i += bsdtar_expand_char(
148                                             outbuff, i, *p++);
149                         }
150                 } else {
151                         /* After any conversion failure, don't bother
152                          * trying to convert the rest. */
153                         i += bsdtar_expand_char(outbuff, i, *p++);
154                         try_wc = 0;
155                 }
156
157                 /* If our output buffer is full, dump it and keep going. */
158                 if (i > (sizeof(outbuff) - 20)) {
159                         outbuff[i++] = '\0';
160                         fprintf(f, "%s", outbuff);
161                         i = 0;
162                 }
163         }
164         outbuff[i++] = '\0';
165         fprintf(f, "%s", outbuff);
166
167         /* If we allocated a heap-based formatting buffer, free it now. */
168         if (fmtbuff_heap != NULL)
169                 free(fmtbuff_heap);
170 }
171
172 /*
173  * Render an arbitrary sequence of bytes into printable ASCII characters.
174  */
175 static size_t
176 bsdtar_expand_char(char *buff, size_t offset, char c)
177 {
178         size_t i = offset;
179
180         if (isprint((unsigned char)c) && c != '\\')
181                 buff[i++] = c;
182         else {
183                 buff[i++] = '\\';
184                 switch (c) {
185                 case '\a': buff[i++] = 'a'; break;
186                 case '\b': buff[i++] = 'b'; break;
187                 case '\f': buff[i++] = 'f'; break;
188                 case '\n': buff[i++] = 'n'; break;
189 #if '\r' != '\n'
190                 /* On some platforms, \n and \r are the same. */
191                 case '\r': buff[i++] = 'r'; break;
192 #endif
193                 case '\t': buff[i++] = 't'; break;
194                 case '\v': buff[i++] = 'v'; break;
195                 case '\\': buff[i++] = '\\'; break;
196                 default:
197                         sprintf(buff + i, "%03o", 0xFF & (int)c);
198                         i += 3;
199                 }
200         }
201
202         return (i - offset);
203 }
204
205 int
206 yes(const char *fmt, ...)
207 {
208         char buff[32];
209         char *p;
210         ssize_t l;
211
212         va_list ap;
213         va_start(ap, fmt);
214         vfprintf(stderr, fmt, ap);
215         va_end(ap);
216         fprintf(stderr, " (y/N)? ");
217         fflush(stderr);
218
219         l = read(2, buff, sizeof(buff) - 1);
220         if (l <= 0)
221                 return (0);
222         buff[l] = 0;
223
224         for (p = buff; *p != '\0'; p++) {
225                 if (isspace((unsigned char)*p))
226                         continue;
227                 switch(*p) {
228                 case 'y': case 'Y':
229                         return (1);
230                 case 'n': case 'N':
231                         return (0);
232                 default:
233                         return (0);
234                 }
235         }
236
237         return (0);
238 }
239
240 /*
241  * Read lines from file and do something with each one.  If option_null
242  * is set, lines are terminated with zero bytes; otherwise, they're
243  * terminated with newlines.
244  *
245  * This uses a self-sizing buffer to handle arbitrarily-long lines.
246  * If the "process" function returns non-zero for any line, this
247  * function will return non-zero after attempting to process all
248  * remaining lines.
249  */
250 int
251 process_lines(struct bsdtar *bsdtar, const char *pathname,
252     int (*process)(struct bsdtar *, const char *))
253 {
254         FILE *f;
255         char *buff, *buff_end, *line_start, *line_end, *p;
256         size_t buff_length, new_buff_length, bytes_read, bytes_wanted;
257         int separator;
258         int ret;
259
260         separator = bsdtar->option_null ? '\0' : '\n';
261         ret = 0;
262
263         if (strcmp(pathname, "-") == 0)
264                 f = stdin;
265         else
266                 f = fopen(pathname, "r");
267         if (f == NULL)
268                 bsdtar_errc(1, errno, "Couldn't open %s", pathname);
269         buff_length = 8192;
270         buff = malloc(buff_length);
271         if (buff == NULL)
272                 bsdtar_errc(1, ENOMEM, "Can't read %s", pathname);
273         line_start = line_end = buff_end = buff;
274         for (;;) {
275                 /* Get some more data into the buffer. */
276                 bytes_wanted = buff + buff_length - buff_end;
277                 bytes_read = fread(buff_end, 1, bytes_wanted, f);
278                 buff_end += bytes_read;
279                 /* Process all complete lines in the buffer. */
280                 while (line_end < buff_end) {
281                         if (*line_end == separator) {
282                                 *line_end = '\0';
283                                 if ((*process)(bsdtar, line_start) != 0)
284                                         ret = -1;
285                                 line_start = line_end + 1;
286                                 line_end = line_start;
287                         } else
288                                 line_end++;
289                 }
290                 if (feof(f))
291                         break;
292                 if (ferror(f))
293                         bsdtar_errc(1, errno,
294                             "Can't read %s", pathname);
295                 if (line_start > buff) {
296                         /* Move a leftover fractional line to the beginning. */
297                         memmove(buff, line_start, buff_end - line_start);
298                         buff_end -= line_start - buff;
299                         line_end -= line_start - buff;
300                         line_start = buff;
301                 } else {
302                         /* Line is too big; enlarge the buffer. */
303                         new_buff_length = buff_length * 2;
304                         if (new_buff_length <= buff_length)
305                                 bsdtar_errc(1, ENOMEM,
306                                     "Line too long in %s", pathname);
307                         buff_length = new_buff_length;
308                         p = realloc(buff, buff_length);
309                         if (p == NULL)
310                                 bsdtar_errc(1, ENOMEM,
311                                     "Line too long in %s", pathname);
312                         buff_end = p + (buff_end - buff);
313                         line_end = p + (line_end - buff);
314                         line_start = buff = p;
315                 }
316         }
317         /* At end-of-file, handle the final line. */
318         if (line_end > line_start) {
319                 *line_end = '\0';
320                 if ((*process)(bsdtar, line_start) != 0)
321                         ret = -1;
322         }
323         free(buff);
324         if (f != stdin)
325                 fclose(f);
326         return (ret);
327 }
328
329 /*-
330  * The logic here for -C <dir> attempts to avoid
331  * chdir() as long as possible.  For example:
332  * "-C /foo -C /bar file"          needs chdir("/bar") but not chdir("/foo")
333  * "-C /foo -C bar file"           needs chdir("/foo/bar")
334  * "-C /foo -C bar /file1"         does not need chdir()
335  * "-C /foo -C bar /file1 file2"   needs chdir("/foo/bar") before file2
336  *
337  * The only correct way to handle this is to record a "pending" chdir
338  * request and combine multiple requests intelligently until we
339  * need to process a non-absolute file.  set_chdir() adds the new dir
340  * to the pending list; do_chdir() actually executes any pending chdir.
341  *
342  * This way, programs that build tar command lines don't have to worry
343  * about -C with non-existent directories; such requests will only
344  * fail if the directory must be accessed.
345  */
346 void
347 set_chdir(struct bsdtar *bsdtar, const char *newdir)
348 {
349         if (newdir[0] == '/') {
350                 /* The -C /foo -C /bar case; dump first one. */
351                 free(bsdtar->pending_chdir);
352                 bsdtar->pending_chdir = NULL;
353         }
354         if (bsdtar->pending_chdir == NULL)
355                 /* Easy case: no previously-saved dir. */
356                 bsdtar->pending_chdir = strdup(newdir);
357         else {
358                 /* The -C /foo -C bar case; concatenate */
359                 char *old_pending = bsdtar->pending_chdir;
360                 size_t old_len = strlen(old_pending);
361                 bsdtar->pending_chdir = malloc(old_len + strlen(newdir) + 2);
362                 if (old_pending[old_len - 1] == '/')
363                         old_pending[old_len - 1] = '\0';
364                 if (bsdtar->pending_chdir != NULL)
365                         sprintf(bsdtar->pending_chdir, "%s/%s",
366                             old_pending, newdir);
367                 free(old_pending);
368         }
369         if (bsdtar->pending_chdir == NULL)
370                 bsdtar_errc(1, errno, "No memory");
371 }
372
373 void
374 do_chdir(struct bsdtar *bsdtar)
375 {
376         if (bsdtar->pending_chdir == NULL)
377                 return;
378
379         if (chdir(bsdtar->pending_chdir) != 0) {
380                 bsdtar_errc(1, 0, "could not chdir to '%s'\n",
381                     bsdtar->pending_chdir);
382         }
383         free(bsdtar->pending_chdir);
384         bsdtar->pending_chdir = NULL;
385 }
386
387 const char *
388 strip_components(const char *path, int elements)
389 {
390         const char *p = path;
391
392         while (elements > 0) {
393                 switch (*p++) {
394                 case '/':
395                         elements--;
396                         path = p;
397                         break;
398                 case '\0':
399                         /* Path is too short, skip it. */
400                         return (NULL);
401                 }
402         }
403
404         while (*path == '/')
405                ++path;
406         if (*path == '\0')
407                return (NULL);
408
409         return (path);
410 }
411
412 /*
413  * Handle --strip-components and any future path-rewriting options.
414  * Returns non-zero if the pathname should not be extracted.
415  *
416  * TODO: Support pax-style regex path rewrites.
417  */
418 int
419 edit_pathname(struct bsdtar *bsdtar, struct archive_entry *entry)
420 {
421         const char *name = archive_entry_pathname(entry);
422 #if HAVE_REGEX_H
423         char *subst_name;
424         int r;
425 #endif
426
427 #if HAVE_REGEX_H
428         r = apply_substitution(bsdtar, name, &subst_name, 0);
429         if (r == -1) {
430                 bsdtar_warnc(0, "Invalid substitution, skipping entry");
431                 return 1;
432         }
433         if (r == 1) {
434                 archive_entry_copy_pathname(entry, subst_name);
435                 if (*subst_name == '\0') {
436                         free(subst_name);
437                         return -1;
438                 } else
439                         free(subst_name);
440                 name = archive_entry_pathname(entry);
441         }
442
443         if (archive_entry_hardlink(entry)) {
444                 r = apply_substitution(bsdtar, archive_entry_hardlink(entry), &subst_name, 1);
445                 if (r == -1) {
446                         bsdtar_warnc(0, "Invalid substitution, skipping entry");
447                         return 1;
448                 }
449                 if (r == 1) {
450                         archive_entry_copy_hardlink(entry, subst_name);
451                         free(subst_name);
452                 }
453         }
454         if (archive_entry_symlink(entry) != NULL) {
455                 r = apply_substitution(bsdtar, archive_entry_symlink(entry), &subst_name, 1);
456                 if (r == -1) {
457                         bsdtar_warnc(0, "Invalid substitution, skipping entry");
458                         return 1;
459                 }
460                 if (r == 1) {
461                         archive_entry_copy_symlink(entry, subst_name);
462                         free(subst_name);
463                 }
464         }
465 #endif
466
467         /* Strip leading dir names as per --strip-components option. */
468         if (bsdtar->strip_components > 0) {
469                 const char *linkname = archive_entry_hardlink(entry);
470
471                 name = strip_components(name, bsdtar->strip_components);
472                 if (name == NULL)
473                         return (1);
474
475                 if (linkname != NULL) {
476                         linkname = strip_components(linkname,
477                             bsdtar->strip_components);
478                         if (linkname == NULL)
479                                 return (1);
480                         archive_entry_copy_hardlink(entry, linkname);
481                 }
482         }
483
484         /* By default, don't write or restore absolute pathnames. */
485         if (!bsdtar->option_absolute_paths) {
486                 const char *rp, *p = name;
487                 int slashonly = 1;
488
489                 /* Remove leading "//./" or "//?/" or "//?/UNC/"
490                  * (absolute path prefixes used by Windows API) */
491                 if ((p[0] == '/' || p[0] == '\\') &&
492                     (p[1] == '/' || p[1] == '\\') &&
493                     (p[2] == '.' || p[2] == '?') &&
494                     (p[3] == '/' || p[3] == '\\'))
495                 {
496                         if (p[2] == '?' &&
497                             (p[4] == 'U' || p[4] == 'u') &&
498                             (p[5] == 'N' || p[5] == 'n') &&
499                             (p[6] == 'C' || p[6] == 'c') &&
500                             (p[7] == '/' || p[7] == '\\'))
501                                 p += 8;
502                         else
503                                 p += 4;
504                         slashonly = 0;
505                 }
506                 do {
507                         rp = p;
508                         /* Remove leading drive letter from archives created
509                          * on Windows. */
510                         if (((p[0] >= 'a' && p[0] <= 'z') ||
511                              (p[0] >= 'A' && p[0] <= 'Z')) &&
512                                  p[1] == ':') {
513                                 p += 2;
514                                 slashonly = 0;
515                         }
516                         /* Remove leading "/../", "//", etc. */
517                         while (p[0] == '/' || p[0] == '\\') {
518                                 if (p[1] == '.' && p[2] == '.' &&
519                                         (p[3] == '/' || p[3] == '\\')) {
520                                         p += 3; /* Remove "/..", leave "/"
521                                                          * for next pass. */
522                                         slashonly = 0;
523                                 } else
524                                         p += 1; /* Remove "/". */
525                         }
526                 } while (rp != p);
527
528                 if (p != name && !bsdtar->warned_lead_slash) {
529                         /* Generate a warning the first time this happens. */
530                         if (slashonly)
531                                 bsdtar_warnc(0,
532                                     "Removing leading '%c' from member names",
533                                     name[0]);
534                         else
535                                 bsdtar_warnc(0,
536                                     "Removing leading drive letter from "
537                                     "member names");
538                         bsdtar->warned_lead_slash = 1;
539                 }
540
541                 /* Special case: Stripping everything yields ".". */
542                 if (*p == '\0')
543                         name = ".";
544                 else
545                         name = p;
546         } else {
547                 /* Strip redundant leading '/' characters. */
548                 while (name[0] == '/' && name[1] == '/')
549                         name++;
550         }
551
552         /* Safely replace name in archive_entry. */
553         if (name != archive_entry_pathname(entry)) {
554                 char *q = strdup(name);
555                 archive_entry_copy_pathname(entry, q);
556                 free(q);
557         }
558         return (0);
559 }
560
561 /*
562  * It would be nice to just use printf() for formatting large numbers,
563  * but the compatibility problems are quite a headache.  Hence the
564  * following simple utility function.
565  */
566 const char *
567 tar_i64toa(int64_t n0)
568 {
569         static char buff[24];
570         int64_t n = n0 < 0 ? -n0 : n0;
571         char *p = buff + sizeof(buff);
572
573         *--p = '\0';
574         do {
575                 *--p = '0' + (int)(n % 10);
576                 n /= 10;
577         } while (n > 0);
578         if (n0 < 0)
579                 *--p = '-';
580         return p;
581 }
582
583 /*
584  * Like strcmp(), but try to be a little more aware of the fact that
585  * we're comparing two paths.  Right now, it just handles leading
586  * "./" and trailing '/' specially, so that "a/b/" == "./a/b"
587  *
588  * TODO: Make this better, so that "./a//b/./c/" == "a/b/c"
589  * TODO: After this works, push it down into libarchive.
590  * TODO: Publish the path normalization routines in libarchive so
591  * that bsdtar can normalize paths and use fast strcmp() instead
592  * of this.
593  */
594
595 int
596 pathcmp(const char *a, const char *b)
597 {
598         /* Skip leading './' */
599         if (a[0] == '.' && a[1] == '/' && a[2] != '\0')
600                 a += 2;
601         if (b[0] == '.' && b[1] == '/' && b[2] != '\0')
602                 b += 2;
603         /* Find the first difference, or return (0) if none. */
604         while (*a == *b) {
605                 if (*a == '\0')
606                         return (0);
607                 a++;
608                 b++;
609         }
610         /*
611          * If one ends in '/' and the other one doesn't,
612          * they're the same.
613          */
614         if (a[0] == '/' && a[1] == '\0' && b[0] == '\0')
615                 return (0);
616         if (a[0] == '\0' && b[0] == '/' && b[1] == '\0')
617                 return (0);
618         /* They're really different, return the correct sign. */
619         return (*(const unsigned char *)a - *(const unsigned char *)b);
620 }