]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - usr.bin/tar/util.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.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
50 #include "bsdtar.h"
51
52 static void     bsdtar_vwarnc(struct bsdtar *, int code,
53                     const char *fmt, va_list ap);
54 static const char *strip_components(const char *path, int elements);
55
56 /*
57  * Print a string, taking care with any non-printable characters.
58  */
59
60 void
61 safe_fprintf(FILE *f, const char *fmt, ...)
62 {
63         char *buff;
64         char *buff_heap;
65         int buff_length;
66         int length;
67         va_list ap;
68         char *p;
69         unsigned i;
70         char buff_stack[256];
71         char copy_buff[256];
72
73         /* Use a stack-allocated buffer if we can, for speed and safety. */
74         buff_heap = NULL;
75         buff_length = sizeof(buff_stack);
76         buff = buff_stack;
77
78         va_start(ap, fmt);
79         length = vsnprintf(buff, buff_length, fmt, ap);
80         va_end(ap);
81         /* If the result is too large, allocate a buffer on the heap. */
82         if (length >= buff_length) {
83                 buff_length = length+1;
84                 buff_heap = malloc(buff_length);
85                 /* Failsafe: use the truncated string if malloc fails. */
86                 if (buff_heap != NULL) {
87                         buff = buff_heap;
88                         va_start(ap, fmt);
89                         length = vsnprintf(buff, buff_length, fmt, ap);
90                         va_end(ap);
91                 }
92         }
93
94         /* Write data, expanding unprintable characters. */
95         p = buff;
96         i = 0;
97         while (*p != '\0') {
98                 unsigned char c = *p++;
99
100                 if (isprint(c) && c != '\\')
101                         copy_buff[i++] = c;
102                 else {
103                         copy_buff[i++] = '\\';
104                         switch (c) {
105                         case '\a': copy_buff[i++] = 'a'; break;
106                         case '\b': copy_buff[i++] = 'b'; break;
107                         case '\f': copy_buff[i++] = 'f'; break;
108                         case '\n': copy_buff[i++] = 'n'; break;
109 #if '\r' != '\n'
110                         /* On some platforms, \n and \r are the same. */
111                         case '\r': copy_buff[i++] = 'r'; break;
112 #endif
113                         case '\t': copy_buff[i++] = 't'; break;
114                         case '\v': copy_buff[i++] = 'v'; break;
115                         case '\\': copy_buff[i++] = '\\'; break;
116                         default:
117                                 sprintf(copy_buff + i, "%03o", c);
118                                 i += 3;
119                         }
120                 }
121
122                 /* If our temp buffer is full, dump it and keep going. */
123                 if (i > (sizeof(copy_buff) - 8)) {
124                         copy_buff[i++] = '\0';
125                         fprintf(f, "%s", copy_buff);
126                         i = 0;
127                 }
128         }
129         copy_buff[i++] = '\0';
130         fprintf(f, "%s", copy_buff);
131
132         /* If we allocated a heap-based buffer, free it now. */
133         if (buff_heap != NULL)
134                 free(buff_heap);
135 }
136
137 static void
138 bsdtar_vwarnc(struct bsdtar *bsdtar, int code, const char *fmt, va_list ap)
139 {
140         fprintf(stderr, "%s: ", bsdtar->progname);
141         vfprintf(stderr, fmt, ap);
142         if (code != 0)
143                 fprintf(stderr, ": %s", strerror(code));
144         fprintf(stderr, "\n");
145 }
146
147 void
148 bsdtar_warnc(struct bsdtar *bsdtar, int code, const char *fmt, ...)
149 {
150         va_list ap;
151
152         va_start(ap, fmt);
153         bsdtar_vwarnc(bsdtar, code, fmt, ap);
154         va_end(ap);
155 }
156
157 void
158 bsdtar_errc(struct bsdtar *bsdtar, int eval, int code, const char *fmt, ...)
159 {
160         va_list ap;
161
162         va_start(ap, fmt);
163         bsdtar_vwarnc(bsdtar, code, fmt, ap);
164         va_end(ap);
165         exit(eval);
166 }
167
168 int
169 yes(const char *fmt, ...)
170 {
171         char buff[32];
172         char *p;
173         ssize_t l;
174
175         va_list ap;
176         va_start(ap, fmt);
177         vfprintf(stderr, fmt, ap);
178         va_end(ap);
179         fprintf(stderr, " (y/N)? ");
180         fflush(stderr);
181
182         l = read(2, buff, sizeof(buff) - 1);
183         if (l <= 0)
184                 return (0);
185         buff[l] = 0;
186
187         for (p = buff; *p != '\0'; p++) {
188                 if (isspace(0xff & (int)*p))
189                         continue;
190                 switch(*p) {
191                 case 'y': case 'Y':
192                         return (1);
193                 case 'n': case 'N':
194                         return (0);
195                 default:
196                         return (0);
197                 }
198         }
199
200         return (0);
201 }
202
203 /*
204  * Read lines from file and do something with each one.  If option_null
205  * is set, lines are terminated with zero bytes; otherwise, they're
206  * terminated with newlines.
207  *
208  * This uses a self-sizing buffer to handle arbitrarily-long lines.
209  * If the "process" function returns non-zero for any line, this
210  * function will return non-zero after attempting to process all
211  * remaining lines.
212  */
213 int
214 process_lines(struct bsdtar *bsdtar, const char *pathname,
215     int (*process)(struct bsdtar *, const char *))
216 {
217         FILE *f;
218         char *buff, *buff_end, *line_start, *line_end, *p;
219         size_t buff_length, new_buff_length, bytes_read, bytes_wanted;
220         int separator;
221         int ret;
222
223         separator = bsdtar->option_null ? '\0' : '\n';
224         ret = 0;
225
226         if (strcmp(pathname, "-") == 0)
227                 f = stdin;
228         else
229                 f = fopen(pathname, "r");
230         if (f == NULL)
231                 bsdtar_errc(bsdtar, 1, errno, "Couldn't open %s", pathname);
232         buff_length = 8192;
233         buff = malloc(buff_length);
234         if (buff == NULL)
235                 bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read %s", pathname);
236         line_start = line_end = buff_end = buff;
237         for (;;) {
238                 /* Get some more data into the buffer. */
239                 bytes_wanted = buff + buff_length - buff_end;
240                 bytes_read = fread(buff_end, 1, bytes_wanted, f);
241                 buff_end += bytes_read;
242                 /* Process all complete lines in the buffer. */
243                 while (line_end < buff_end) {
244                         if (*line_end == separator) {
245                                 *line_end = '\0';
246                                 if ((*process)(bsdtar, line_start) != 0)
247                                         ret = -1;
248                                 line_start = line_end + 1;
249                                 line_end = line_start;
250                         } else
251                                 line_end++;
252                 }
253                 if (feof(f))
254                         break;
255                 if (ferror(f))
256                         bsdtar_errc(bsdtar, 1, errno,
257                             "Can't read %s", pathname);
258                 if (line_start > buff) {
259                         /* Move a leftover fractional line to the beginning. */
260                         memmove(buff, line_start, buff_end - line_start);
261                         buff_end -= line_start - buff;
262                         line_end -= line_start - buff;
263                         line_start = buff;
264                 } else {
265                         /* Line is too big; enlarge the buffer. */
266                         new_buff_length = buff_length * 2;
267                         if (new_buff_length <= buff_length)
268                                 bsdtar_errc(bsdtar, 1, ENOMEM,
269                                     "Line too long in %s", pathname);
270                         buff_length = new_buff_length;
271                         p = realloc(buff, buff_length);
272                         if (p == NULL)
273                                 bsdtar_errc(bsdtar, 1, ENOMEM,
274                                     "Line too long in %s", pathname);
275                         buff_end = p + (buff_end - buff);
276                         line_end = p + (line_end - buff);
277                         line_start = buff = p;
278                 }
279         }
280         /* At end-of-file, handle the final line. */
281         if (line_end > line_start) {
282                 *line_end = '\0';
283                 if ((*process)(bsdtar, line_start) != 0)
284                         ret = -1;
285         }
286         free(buff);
287         if (f != stdin)
288                 fclose(f);
289         return (ret);
290 }
291
292 /*-
293  * The logic here for -C <dir> attempts to avoid
294  * chdir() as long as possible.  For example:
295  * "-C /foo -C /bar file"          needs chdir("/bar") but not chdir("/foo")
296  * "-C /foo -C bar file"           needs chdir("/foo/bar")
297  * "-C /foo -C bar /file1"         does not need chdir()
298  * "-C /foo -C bar /file1 file2"   needs chdir("/foo/bar") before file2
299  *
300  * The only correct way to handle this is to record a "pending" chdir
301  * request and combine multiple requests intelligently until we
302  * need to process a non-absolute file.  set_chdir() adds the new dir
303  * to the pending list; do_chdir() actually executes any pending chdir.
304  *
305  * This way, programs that build tar command lines don't have to worry
306  * about -C with non-existent directories; such requests will only
307  * fail if the directory must be accessed.
308  */
309 void
310 set_chdir(struct bsdtar *bsdtar, const char *newdir)
311 {
312         if (newdir[0] == '/') {
313                 /* The -C /foo -C /bar case; dump first one. */
314                 free(bsdtar->pending_chdir);
315                 bsdtar->pending_chdir = NULL;
316         }
317         if (bsdtar->pending_chdir == NULL)
318                 /* Easy case: no previously-saved dir. */
319                 bsdtar->pending_chdir = strdup(newdir);
320         else {
321                 /* The -C /foo -C bar case; concatenate */
322                 char *old_pending = bsdtar->pending_chdir;
323                 size_t old_len = strlen(old_pending);
324                 bsdtar->pending_chdir = malloc(old_len + strlen(newdir) + 2);
325                 if (old_pending[old_len - 1] == '/')
326                         old_pending[old_len - 1] = '\0';
327                 if (bsdtar->pending_chdir != NULL)
328                         sprintf(bsdtar->pending_chdir, "%s/%s",
329                             old_pending, newdir);
330                 free(old_pending);
331         }
332         if (bsdtar->pending_chdir == NULL)
333                 bsdtar_errc(bsdtar, 1, errno, "No memory");
334 }
335
336 void
337 do_chdir(struct bsdtar *bsdtar)
338 {
339         if (bsdtar->pending_chdir == NULL)
340                 return;
341
342         if (chdir(bsdtar->pending_chdir) != 0) {
343                 bsdtar_errc(bsdtar, 1, 0, "could not chdir to '%s'\n",
344                     bsdtar->pending_chdir);
345         }
346         free(bsdtar->pending_chdir);
347         bsdtar->pending_chdir = NULL;
348 }
349
350 const char *
351 strip_components(const char *path, int elements)
352 {
353         const char *p = path;
354
355         while (elements > 0) {
356                 switch (*p++) {
357                 case '/':
358                         elements--;
359                         path = p;
360                         break;
361                 case '\0':
362                         /* Path is too short, skip it. */
363                         return (NULL);
364                 }
365         }
366
367         while (*path == '/')
368                ++path;
369         if (*path == '\0')
370                return (NULL);
371
372         return (path);
373 }
374
375 /*
376  * Handle --strip-components and any future path-rewriting options.
377  * Returns non-zero if the pathname should not be extracted.
378  *
379  * TODO: Support pax-style regex path rewrites.
380  */
381 int
382 edit_pathname(struct bsdtar *bsdtar, struct archive_entry *entry)
383 {
384         const char *name = archive_entry_pathname(entry);
385 #if HAVE_REGEX_H
386         char *subst_name;
387 #endif
388         int r;
389
390 #if HAVE_REGEX_H
391         r = apply_substitution(bsdtar, name, &subst_name, 0);
392         if (r == -1) {
393                 bsdtar_warnc(bsdtar, 0, "Invalid substituion, skipping entry");
394                 return 1;
395         }
396         if (r == 1) {
397                 archive_entry_copy_pathname(entry, subst_name);
398                 if (*subst_name == '\0') {
399                         free(subst_name);
400                         return -1;
401                 } else
402                         free(subst_name);
403                 name = archive_entry_pathname(entry);
404         }
405
406         if (archive_entry_hardlink(entry)) {
407                 r = apply_substitution(bsdtar, archive_entry_hardlink(entry), &subst_name, 1);
408                 if (r == -1) {
409                         bsdtar_warnc(bsdtar, 0, "Invalid substituion, skipping entry");
410                         return 1;
411                 }
412                 if (r == 1) {
413                         archive_entry_copy_hardlink(entry, subst_name);
414                         free(subst_name);
415                 }
416         }
417         if (archive_entry_symlink(entry) != NULL) {
418                 r = apply_substitution(bsdtar, archive_entry_symlink(entry), &subst_name, 1);
419                 if (r == -1) {
420                         bsdtar_warnc(bsdtar, 0, "Invalid substituion, skipping entry");
421                         return 1;
422                 }
423                 if (r == 1) {
424                         archive_entry_copy_symlink(entry, subst_name);
425                         free(subst_name);
426                 }
427         }
428 #endif
429
430         /* Strip leading dir names as per --strip-components option. */
431         if (bsdtar->strip_components > 0) {
432                 const char *linkname = archive_entry_hardlink(entry);
433
434                 name = strip_components(name, bsdtar->strip_components);
435                 if (name == NULL)
436                         return (1);
437
438                 if (linkname != NULL) {
439                         linkname = strip_components(linkname,
440                             bsdtar->strip_components);
441                         if (linkname == NULL)
442                                 return (1);
443                         archive_entry_copy_hardlink(entry, linkname);
444                 }
445         }
446
447         /* Strip redundant leading '/' characters. */
448         while (name[0] == '/' && name[1] == '/')
449                 name++;
450
451         /* Strip leading '/' unless user has asked us not to. */
452         if (name[0] == '/' && !bsdtar->option_absolute_paths) {
453                 /* Generate a warning the first time this happens. */
454                 if (!bsdtar->warned_lead_slash) {
455                         bsdtar_warnc(bsdtar, 0,
456                             "Removing leading '/' from member names");
457                         bsdtar->warned_lead_slash = 1;
458                 }
459                 name++;
460                 /* Special case: Stripping leading '/' from "/" yields ".". */
461                 if (*name == '\0')
462                         name = ".";
463         }
464
465         /* Safely replace name in archive_entry. */
466         if (name != archive_entry_pathname(entry)) {
467                 char *q = strdup(name);
468                 archive_entry_copy_pathname(entry, q);
469                 free(q);
470         }
471         return (0);
472 }
473
474 /*
475  * Like strcmp(), but try to be a little more aware of the fact that
476  * we're comparing two paths.  Right now, it just handles leading
477  * "./" and trailing '/' specially, so that "a/b/" == "./a/b"
478  *
479  * TODO: Make this better, so that "./a//b/./c/" == "a/b/c"
480  * TODO: After this works, push it down into libarchive.
481  * TODO: Publish the path normalization routines in libarchive so
482  * that bsdtar can normalize paths and use fast strcmp() instead
483  * of this.
484  */
485
486 int
487 pathcmp(const char *a, const char *b)
488 {
489         /* Skip leading './' */
490         if (a[0] == '.' && a[1] == '/' && a[2] != '\0')
491                 a += 2;
492         if (b[0] == '.' && b[1] == '/' && b[2] != '\0')
493                 b += 2;
494         /* Find the first difference, or return (0) if none. */
495         while (*a == *b) {
496                 if (*a == '\0')
497                         return (0);
498                 a++;
499                 b++;
500         }
501         /*
502          * If one ends in '/' and the other one doesn't,
503          * they're the same.
504          */
505         if (a[0] == '/' && a[1] == '\0' && b[0] == '\0')
506                 return (0);
507         if (a[0] == '\0' && b[0] == '/' && b[1] == '\0')
508                 return (0);
509         /* They're really different, return the correct sign. */
510         return (*(const unsigned char *)a - *(const unsigned char *)b);
511 }