Import initial version of 1:1 pthread library.
[dragonfly.git] / contrib / bsdtar / util.c
1 /*-
2  * Copyright (c) 2003-2004 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  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "bsdtar_platform.h"
28 __FBSDID("$FreeBSD: src/usr.bin/tar/util.c,v 1.11 2004/08/08 05:50:10 kientzle Exp $");
29
30 #include <sys/stat.h>
31 #include <sys/types.h>  /* Linux doesn't define mode_t, etc. in sys/stat.h. */
32 #include <archive_entry.h>
33 #include <ctype.h>
34 #include <errno.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 #include "bsdtar.h"
41
42 static void     bsdtar_vwarnc(struct bsdtar *, int code,
43                     const char *fmt, va_list ap);
44
45 /*
46  * Print a string, taking care with any non-printable characters.
47  */
48
49 void
50 safe_fprintf(FILE *f, const char *fmt, ...)
51 {
52         char *buff;
53         char *buff_heap;
54         int buff_length;
55         int length;
56         va_list ap;
57         char *p;
58         unsigned i;
59         char buff_stack[256];
60         char copy_buff[256];
61
62         /* Use a stack-allocated buffer if we can, for speed and safety. */
63         buff_heap = NULL;
64         buff_length = sizeof(buff_stack);
65         buff = buff_stack;
66
67         va_start(ap, fmt);
68         length = vsnprintf(buff, buff_length, fmt, ap);
69         va_end(ap);
70         /* If the result is too large, allocate a buffer on the heap. */
71         if (length >= buff_length) {
72                 buff_length = length+1;
73                 buff_heap = malloc(buff_length);
74                 /* Failsafe: use the truncated string if malloc fails. */
75                 if (buff_heap != NULL) {
76                         buff = buff_heap;
77                         va_start(ap, fmt);
78                         length = vsnprintf(buff, buff_length, fmt, ap);
79                         va_end(ap);
80                 }
81         }
82
83         /* Write data, expanding unprintable characters. */
84         p = buff;
85         i = 0;
86         while (*p != '\0') {
87                 unsigned char c = *p++;
88
89                 if (isprint(c) && c != '\\')
90                         copy_buff[i++] = c;
91                 else {
92                         copy_buff[i++] = '\\';
93                         switch (c) {
94                         case '\a': copy_buff[i++] = 'a'; break;
95                         case '\b': copy_buff[i++] = 'b'; break;
96                         case '\f': copy_buff[i++] = 'f'; break;
97                         case '\n': copy_buff[i++] = 'n'; break;
98 #if '\r' != '\n'
99                         /* On some platforms, \n and \r are the same. */
100                         case '\r': copy_buff[i++] = 'r'; break;
101 #endif
102                         case '\t': copy_buff[i++] = 't'; break;
103                         case '\v': copy_buff[i++] = 'v'; break;
104                         case '\\': copy_buff[i++] = '\\'; break;
105                         default:
106                                 sprintf(copy_buff + i, "%03o", c);
107                                 i += 3;
108                         }
109                 }
110
111                 /* If our temp buffer is full, dump it and keep going. */
112                 if (i > (sizeof(copy_buff) - 8)) {
113                         copy_buff[i++] = '\0';
114                         fprintf(f, "%s", copy_buff);
115                         i = 0;
116                 }
117         }
118         copy_buff[i++] = '\0';
119         fprintf(f, "%s", copy_buff);
120
121         /* If we allocated a heap-based buffer, free it now. */
122         if (buff_heap != NULL)
123                 free(buff_heap);
124 }
125
126 static void
127 bsdtar_vwarnc(struct bsdtar *bsdtar, int code, const char *fmt, va_list ap)
128 {
129         fprintf(stderr, "%s: ", bsdtar->progname);
130         vfprintf(stderr, fmt, ap);
131         if (code != 0)
132                 fprintf(stderr, ": %s", strerror(code));
133         fprintf(stderr, "\n");
134 }
135
136 void
137 bsdtar_warnc(struct bsdtar *bsdtar, int code, const char *fmt, ...)
138 {
139         va_list ap;
140
141         va_start(ap, fmt);
142         bsdtar_vwarnc(bsdtar, code, fmt, ap);
143         va_end(ap);
144 }
145
146 void
147 bsdtar_errc(struct bsdtar *bsdtar, int eval, 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         exit(eval);
155 }
156
157 int
158 yes(const char *fmt, ...)
159 {
160         char buff[32];
161         char *p;
162         ssize_t l;
163
164         va_list ap;
165         va_start(ap, fmt);
166         vfprintf(stderr, fmt, ap);
167         va_end(ap);
168         fprintf(stderr, " (y/N)? ");
169         fflush(stderr);
170
171         l = read(2, buff, sizeof(buff));
172         if (l <= 0)
173                 return (0);
174         buff[l] = 0;
175
176         for (p = buff; *p != '\0'; p++) {
177                 if (isspace(0xff & (int)*p))
178                         continue;
179                 switch(*p) {
180                 case 'y': case 'Y':
181                         return (1);
182                 case 'n': case 'N':
183                         return (0);
184                 default:
185                         return (0);
186                 }
187         }
188
189         return (0);
190 }
191
192 void
193 bsdtar_strmode(struct archive_entry *entry, char *bp)
194 {
195         static const char *perms = "?rwxrwxrwx ";
196         static const mode_t permbits[] =
197             { S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, S_IWGRP, S_IXGRP,
198               S_IROTH, S_IWOTH, S_IXOTH };
199         mode_t mode;
200         int i;
201
202         /* Fill in a default string, then selectively override. */
203         strcpy(bp, perms);
204
205         mode = archive_entry_mode(entry);
206         switch (mode & S_IFMT) {
207         case S_IFREG:  bp[0] = '-'; break;
208         case S_IFBLK:  bp[0] = 'b'; break;
209         case S_IFCHR:  bp[0] = 'c'; break;
210         case S_IFDIR:  bp[0] = 'd'; break;
211         case S_IFLNK:  bp[0] = 'l'; break;
212         case S_IFSOCK: bp[0] = 's'; break;
213 #ifdef S_IFIFO
214         case S_IFIFO:  bp[0] = 'p'; break;
215 #endif
216 #ifdef S_IFWHT
217         case S_IFWHT:  bp[0] = 'w'; break;
218 #endif
219         }
220
221         for (i = 0; i < 9; i++)
222                 if (!(mode & permbits[i]))
223                         bp[i+1] = '-';
224
225         if (mode & S_ISUID) {
226                 if (mode & S_IXUSR) bp[3] = 's';
227                 else bp[3] = 'S';
228         }
229         if (mode & S_ISGID) {
230                 if (mode & S_IXGRP) bp[6] = 's';
231                 else bp[6] = 'S';
232         }
233         if (mode & S_ISVTX) {
234                 if (mode & S_IXOTH) bp[9] = 't';
235                 else bp[9] = 'T';
236         }
237         if (archive_entry_acl_count(entry, ARCHIVE_ENTRY_ACL_TYPE_ACCESS))
238                 bp[10] = '+';
239 }
240
241
242 /*
243  * Read lines from file and do something with each one.  If option_null
244  * is set, lines are terminated with zero bytes; otherwise, they're
245  * terminated with newlines.
246  *
247  * This uses a self-sizing buffer to handle arbitrarily-long lines.
248  * If the "process" function returns non-zero for any line, this
249  * function will return non-zero after attempting to process all
250  * remaining lines.
251  */
252 int
253 process_lines(struct bsdtar *bsdtar, const char *pathname,
254     int (*process)(struct bsdtar *, const char *))
255 {
256         FILE *f;
257         char *buff, *buff_end, *line_start, *line_end, *p;
258         size_t buff_length, bytes_read, bytes_wanted;
259         int separator;
260         int ret;
261
262         separator = bsdtar->option_null ? '\0' : '\n';
263         ret = 0;
264
265         if (strcmp(pathname, "-") == 0)
266                 f = stdin;
267         else
268                 f = fopen(pathname, "r");
269         if (f == NULL)
270                 bsdtar_errc(bsdtar, 1, errno, "Couldn't open %s", pathname);
271         buff_length = 8192;
272         buff = malloc(buff_length);
273         if (buff == NULL)
274                 bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read %s", pathname);
275         line_start = line_end = buff_end = buff;
276         for (;;) {
277                 /* Get some more data into the buffer. */
278                 bytes_wanted = buff + buff_length - buff_end;
279                 bytes_read = fread(buff_end, 1, bytes_wanted, f);
280                 buff_end += bytes_read;
281                 /* Process all complete lines in the buffer. */
282                 while (line_end < buff_end) {
283                         if (*line_end == separator) {
284                                 *line_end = '\0';
285                                 if ((*process)(bsdtar, line_start) != 0)
286                                         ret = -1;
287                                 line_start = line_end + 1;
288                                 line_end = line_start;
289                         } else
290                                 line_end++;
291                 }
292                 if (feof(f))
293                         break;
294                 if (ferror(f))
295                         bsdtar_errc(bsdtar, 1, errno,
296                             "Can't read %s", pathname);
297                 if (line_start > buff) {
298                         /* Move a leftover fractional line to the beginning. */
299                         memmove(buff, line_start, buff_end - line_start);
300                         buff_end -= line_start - buff;
301                         line_end -= line_start - buff;
302                         line_start = buff;
303                 } else {
304                         /* Line is too big; enlarge the buffer. */
305                         p = realloc(buff, buff_length *= 2);
306                         if (p == NULL)
307                                 bsdtar_errc(bsdtar, 1, ENOMEM,
308                                     "Line too long in %s", pathname);
309                         buff_end = p + (buff_end - buff);
310                         line_end = p + (line_end - buff);
311                         line_start = buff = p;
312                 }
313         }
314         /* At end-of-file, handle the final line. */
315         if (line_end > line_start) {
316                 *line_end = '\0';
317                 if ((*process)(bsdtar, line_start) != 0)
318                         ret = -1;
319         }
320         free(buff);
321         if (f != stdin)
322                 fclose(f);
323         return (ret);
324 }
325
326 /*-
327  * The logic here for -C <dir> attempts to avoid
328  * chdir() as long as possible.  For example:
329  * "-C /foo -C /bar file"          needs chdir("/bar") but not chdir("/foo")
330  * "-C /foo -C bar file"           needs chdir("/foo/bar")
331  * "-C /foo -C bar /file1"         does not need chdir()
332  * "-C /foo -C bar /file1 file2"   needs chdir("/foo/bar") before file2
333  *
334  * The only correct way to handle this is to record a "pending" chdir
335  * request and combine multiple requests intelligently until we
336  * need to process a non-absolute file.  set_chdir() adds the new dir
337  * to the pending list; do_chdir() actually executes any pending chdir.
338  *
339  * This way, programs that build tar command lines don't have to worry
340  * about -C with non-existent directories; such requests will only
341  * fail if the directory must be accessed.
342  */
343 void
344 set_chdir(struct bsdtar *bsdtar, const char *newdir)
345 {
346         if (newdir[0] == '/') {
347                 /* The -C /foo -C /bar case; dump first one. */
348                 free(bsdtar->pending_chdir);
349                 bsdtar->pending_chdir = NULL;
350         }
351         if (bsdtar->pending_chdir == NULL)
352                 /* Easy case: no previously-saved dir. */
353                 bsdtar->pending_chdir = strdup(newdir);
354         else {
355                 /* The -C /foo -C bar case; concatenate */
356                 char *old_pending = bsdtar->pending_chdir;
357                 size_t old_len = strlen(old_pending);
358                 bsdtar->pending_chdir = malloc(old_len + strlen(newdir) + 2);
359                 if (old_pending[old_len - 1] == '/')
360                         old_pending[old_len - 1] = '\0';
361                 if (bsdtar->pending_chdir != NULL)
362                         sprintf(bsdtar->pending_chdir, "%s/%s",
363                             old_pending, newdir);
364                 free(old_pending);
365         }
366         if (bsdtar->pending_chdir == NULL)
367                 bsdtar_errc(bsdtar, 1, errno, "No memory");
368 }
369
370 void
371 do_chdir(struct bsdtar *bsdtar)
372 {
373         if (bsdtar->pending_chdir == NULL)
374                 return;
375
376         if (chdir(bsdtar->pending_chdir) != 0) {
377                 bsdtar_errc(bsdtar, 1, 0, "could not chdir to '%s'\n",
378                     bsdtar->pending_chdir);
379         }
380         free(bsdtar->pending_chdir);
381         bsdtar->pending_chdir = NULL;
382 }