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