file_cmds-287.11.1.tar.gz
[apple/file_cmds.git] / pax / ftree.c
1 /* $OpenBSD: ftree.c,v 1.28 2008/05/06 06:54:28 henning Exp $ */
2 /* $NetBSD: ftree.c,v 1.4 1995/03/21 09:07:21 cgd Exp $ */
3
4 /*-
5 * Copyright (c) 1992 Keith Muller.
6 * Copyright (c) 1992, 1993
7 * The Regents of the University of California. All rights reserved.
8 *
9 * This code is derived from software contributed to Berkeley by
10 * Keith Muller of the University of California, San Diego.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37 #include <sys/cdefs.h>
38 #ifndef lint
39 #if 0
40 static const char sccsid[] = "@(#)ftree.c 8.2 (Berkeley) 4/18/94";
41 #else
42 __used static const char rcsid[] = "$OpenBSD: ftree.c,v 1.28 2008/05/06 06:54:28 henning Exp $";
43 #endif
44 #endif /* not lint */
45
46 #include <sys/types.h>
47 #include <sys/time.h>
48 #include <sys/stat.h>
49 #include <sys/param.h>
50 #include <unistd.h>
51 #include <string.h>
52 #include <stdio.h>
53 #include <errno.h>
54 #include <stdlib.h>
55 #include <fts.h>
56 #include "pax.h"
57 #include "ftree.h"
58 #include "extern.h"
59
60 /*
61 * routines to interface with the fts library function.
62 *
63 * file args supplied to pax are stored on a single linked list (of type FTREE)
64 * and given to fts to be processed one at a time. pax "selects" files from
65 * the expansion of each arg into the corresponding file tree (if the arg is a
66 * directory, otherwise the node itself is just passed to pax). The selection
67 * is modified by the -n and -u flags. The user is informed when a specific
68 * file arg does not generate any selected files. -n keeps expanding the file
69 * tree arg until one of its files is selected, then skips to the next file
70 * arg. when the user does not supply the file trees as command line args to
71 * pax, they are read from stdin
72 */
73
74 static FTS *ftsp = NULL; /* current FTS handle */
75 static int ftsopts; /* options to be used on fts_open */
76 static char *farray[2]; /* array for passing each arg to fts */
77 static FTREE *fthead = NULL; /* head of linked list of file args */
78 static FTREE *fttail = NULL; /* tail of linked list of file args */
79 static FTREE *ftcur = NULL; /* current file arg being processed */
80 static FTSENT *ftent = NULL; /* current file tree entry */
81 static int ftree_skip; /* when set skip to next file arg */
82
83 static int ftree_arg(void);
84 static char *getpathname(char *, int);
85
86 /*
87 * ftree_start()
88 * initialize the options passed to fts_open() during this run of pax
89 * options are based on the selection of pax options by the user
90 * fts_start() also calls fts_arg() to open the first valid file arg. We
91 * also attempt to reset directory access times when -t (tflag) is set.
92 * Return:
93 * 0 if there is at least one valid file arg to process, -1 otherwise
94 */
95
96 int
97 ftree_start(void)
98 {
99 /*
100 * set up the operation mode of fts, open the first file arg. We must
101 * use FTS_NOCHDIR, as the user may have to open multiple archives and
102 * if fts did a chdir off into the boondocks, we may create an archive
103 * volume in an place where the user did not expect to.
104 */
105 ftsopts = FTS_NOCHDIR;
106
107 /*
108 * optional user flags that effect file traversal
109 * -H command line symlink follow only (half follow)
110 * -L follow sylinks (logical)
111 * -P do not follow sylinks (physical). This is the default.
112 * -X do not cross over mount points
113 * -t preserve access times on files read.
114 * -n select only the first member of a file tree when a match is found
115 * -d do not extract subtrees rooted at a directory arg.
116 */
117 if (Lflag)
118 ftsopts |= FTS_LOGICAL;
119 else
120 ftsopts |= FTS_PHYSICAL;
121 if (Hflag)
122 ftsopts |= FTS_COMFOLLOW;
123 if (Xflag)
124 ftsopts |= FTS_XDEV;
125
126 if ((fthead == NULL) && ((farray[0] = malloc(PAXPATHLEN+2)) == NULL)) {
127 paxwarn(1, "Unable to allocate memory for file name buffer");
128 return(-1);
129 }
130
131 if (ftree_arg() < 0)
132 return(-1);
133 if (tflag && (atdir_start() < 0))
134 return(-1);
135 return(0);
136 }
137
138 /*
139 * ftree_add()
140 * add the arg to the linked list of files to process. Each will be
141 * processed by fts one at a time
142 * Return:
143 * 0 if added to the linked list, -1 if failed
144 */
145
146 int
147 ftree_add(char *str, int chflg)
148 {
149 FTREE *ft;
150 int len;
151
152 /*
153 * simple check for bad args
154 */
155 if ((str == NULL) || (*str == '\0')) {
156 paxwarn(0, "Invalid file name argument");
157 return(-1);
158 }
159
160 /*
161 * allocate FTREE node and add to the end of the linked list (args are
162 * processed in the same order they were passed to pax). Get rid of any
163 * trailing / the user may pass us. (watch out for / by itself).
164 */
165 if ((ft = (FTREE *)malloc(sizeof(FTREE))) == NULL) {
166 paxwarn(0, "Unable to allocate memory for filename");
167 return(-1);
168 }
169
170 if (((len = strlen(str) - 1) > 0) && (str[len] == '/'))
171 str[len] = '\0';
172 ft->fname = str;
173 ft->refcnt = 0;
174 ft->newercnt = 0;
175 ft->chflg = chflg;
176 ft->fow = NULL;
177 if (fthead == NULL) {
178 fttail = fthead = ft;
179 return(0);
180 }
181 fttail->fow = ft;
182 fttail = ft;
183 return(0);
184 }
185
186 /*
187 * ftree_sel()
188 * this entry has been selected by pax. bump up reference count and handle
189 * -n and -d processing.
190 */
191
192 void
193 ftree_sel(ARCHD *arcn)
194 {
195 /*
196 * set reference bit for this pattern. This linked list is only used
197 * when file trees are supplied pax as args. The list is not used when
198 * the trees are read from stdin.
199 */
200 if (ftcur != NULL)
201 ftcur->refcnt = 1;
202
203 /*
204 * if -n we are done with this arg, force a skip to the next arg when
205 * pax asks for the next file in next_file().
206 * if -d we tell fts only to match the directory (if the arg is a dir)
207 * and not the entire file tree rooted at that point.
208 */
209 if (nflag)
210 ftree_skip = 1;
211
212 if (!dflag || (arcn->type != PAX_DIR))
213 return;
214
215 if (ftent != NULL)
216 (void)fts_set(ftsp, ftent, FTS_SKIP);
217 }
218
219 /*
220 * ftree_notsel()
221 * this entry has not been selected by pax.
222 */
223
224 void
225 ftree_notsel()
226 {
227 if (ftent != NULL)
228 (void)fts_set(ftsp, ftent, FTS_SKIP);
229 }
230
231 /*
232 * ftree_skipped_newer()
233 * file has been skipped because a newer file exists and -u/-D given
234 */
235
236 void
237 ftree_skipped_newer(ARCHD *arcn)
238 {
239 /* skipped due to -u/-D, mark accordingly */
240 if (ftcur != NULL)
241 ftcur->newercnt = 1;
242 }
243
244 /*
245 * ftree_chk()
246 * called at end on pax execution. Prints all those file args that did not
247 * have a selected member (reference count still 0)
248 */
249
250 void
251 ftree_chk(void)
252 {
253 FTREE *ft;
254 int wban = 0;
255
256 /*
257 * make sure all dir access times were reset.
258 */
259 if (tflag)
260 atdir_end();
261
262 /*
263 * walk down list and check reference count. Print out those members
264 * that never had a match
265 */
266 for (ft = fthead; ft != NULL; ft = ft->fow) {
267 if ((ft->refcnt > 0) || ft->newercnt > 0 || ft->chflg)
268 continue;
269 if (wban == 0) {
270 paxwarn(1,"WARNING! These file names were not selected:");
271 ++wban;
272 }
273 (void)fprintf(stderr, "%s\n", ft->fname);
274 }
275 }
276
277 /*
278 * ftree_arg()
279 * Get the next file arg for fts to process. Can be from either the linked
280 * list or read from stdin when the user did not them as args to pax. Each
281 * arg is processed until the first successful fts_open().
282 * Return:
283 * 0 when the next arg is ready to go, -1 if out of file args (or EOF on
284 * stdin).
285 */
286
287 static int
288 ftree_arg(void)
289 {
290
291 /*
292 * close off the current file tree
293 */
294 if (ftsp != NULL) {
295 (void)fts_close(ftsp);
296 ftsp = NULL;
297 }
298
299 /*
300 * keep looping until we get a valid file tree to process. Stop when we
301 * reach the end of the list (or get an eof on stdin)
302 */
303 for (;;) {
304 if (fthead == NULL) {
305 /*
306 * the user didn't supply any args, get the file trees
307 * to process from stdin;
308 */
309 if (getpathname(farray[0], PAXPATHLEN+1) == NULL)
310 return(-1);
311 } else {
312 /*
313 * the user supplied the file args as arguments to pax
314 */
315 if (ftcur == NULL)
316 ftcur = fthead;
317 else if ((ftcur = ftcur->fow) == NULL)
318 return(-1);
319 if (ftcur->chflg) {
320 /* First fchdir() back... */
321 if (fdochdir(cwdfd) < 0) {
322 syswarn(1, errno,
323 "Can't fchdir to starting directory");
324 return(-1);
325 }
326 if (dochdir(ftcur->fname) < 0) {
327 syswarn(1, errno, "Can't chdir to %s",
328 ftcur->fname);
329 return(-1);
330 }
331 continue;
332 } else
333 farray[0] = ftcur->fname;
334 }
335
336 /*
337 * watch it, fts wants the file arg stored in a array of char
338 * ptrs, with the last one a null. we use a two element array
339 * and set farray[0] to point at the buffer with the file name
340 * in it. We cannot pass all the file args to fts at one shot
341 * as we need to keep a handle on which file arg generates what
342 * files (the -n and -d flags need this). If the open is
343 * successful, return a 0.
344 */
345 if ((ftsp = fts_open(farray, ftsopts, NULL)) != NULL)
346 break;
347 }
348 return(0);
349 }
350
351 /*
352 * next_file()
353 * supplies the next file to process in the supplied archd structure.
354 * Return:
355 * 0 when contents of arcn have been set with the next file, -1 when done.
356 */
357
358 int
359 next_file(ARCHD *arcn)
360 {
361 int cnt;
362 time_t atime;
363 time_t mtime;
364
365 /*
366 * ftree_sel() might have set the ftree_skip flag if the user has the
367 * -n option and a file was selected from this file arg tree. (-n says
368 * only one member is matched for each pattern) ftree_skip being 1
369 * forces us to go to the next arg now.
370 */
371 if (ftree_skip) {
372 /*
373 * clear and go to next arg
374 */
375 ftree_skip = 0;
376 if (ftree_arg() < 0)
377 return(-1);
378 }
379
380 /*
381 * loop until we get a valid file to process
382 */
383 for (;;) {
384 if ((ftent = fts_read(ftsp)) == NULL) {
385 if (errno)
386 syswarn(1, errno, "next_file");
387 /*
388 * out of files in this tree, go to next arg, if none
389 * we are done
390 */
391 if (ftree_arg() < 0)
392 return(-1);
393 continue;
394 }
395
396 /*
397 * handle each type of fts_read() flag
398 */
399 switch (ftent->fts_info) {
400 case FTS_D:
401 case FTS_DEFAULT:
402 case FTS_F:
403 case FTS_SL:
404 /*
405 * these are all ok
406 */
407 break;
408 case FTS_SLNONE: /* was same as above cases except Unix
409 conformance requires this error check */
410 if (Hflag || Lflag) { /* -H or -L was specified */
411 if (ftent->fts_errno)
412 paxwarn(1, "%s: %s",
413 ftent->fts_name, strerror(ftent->fts_errno));
414 }
415 break;
416 case FTS_DP:
417 /*
418 * already saw this directory. If the user wants file
419 * access times reset, we use this to restore the
420 * access time for this directory since this is the
421 * last time we will see it in this file subtree
422 * remember to force the time (this is -t on a read
423 * directory, not a created directory).
424 */
425 if (!tflag || (get_atdir(ftent->fts_statp->st_dev,
426 ftent->fts_statp->st_ino, &mtime, &atime) < 0))
427 continue;
428 set_ftime(ftent->fts_path, mtime, atime, 1);
429 continue;
430 case FTS_DC:
431 /*
432 * fts claims a file system cycle
433 */
434 paxwarn(1,"File system cycle found at %s",ftent->fts_path);
435 continue;
436 case FTS_DNR:
437 syswarn(1, ftent->fts_errno,
438 "Unable to read directory %s", ftent->fts_path);
439 continue;
440 case FTS_ERR:
441 syswarn(1, ftent->fts_errno,
442 "File system traversal error");
443 continue;
444 case FTS_NS:
445 case FTS_NSOK:
446 syswarn(1, ftent->fts_errno,
447 "Unable to access %s", ftent->fts_path);
448 continue;
449 }
450
451 /*
452 * ok got a file tree node to process. copy info into arcn
453 * structure (initialize as required)
454 */
455 arcn->skip = 0;
456 arcn->pad = 0;
457 arcn->ln_nlen = 0;
458 arcn->ln_name[0] = '\0';
459 memcpy(&arcn->sb, ftent->fts_statp, sizeof(arcn->sb));
460
461 /*
462 * file type based set up and copy into the arcn struct
463 * SIDE NOTE:
464 * we try to reset the access time on all files and directories
465 * we may read when the -t flag is specified. files are reset
466 * when we close them after copying. we reset the directories
467 * when we are done with their file tree (we also clean up at
468 * end in case we cut short a file tree traversal). However
469 * there is no way to reset access times on symlinks.
470 */
471 switch (S_IFMT & arcn->sb.st_mode) {
472 case S_IFDIR:
473 arcn->type = PAX_DIR;
474 if (!tflag)
475 break;
476 add_atdir(ftent->fts_path, arcn->sb.st_dev,
477 arcn->sb.st_ino, arcn->sb.st_mtime,
478 arcn->sb.st_atime);
479 break;
480 case S_IFCHR:
481 arcn->type = PAX_CHR;
482 break;
483 case S_IFBLK:
484 arcn->type = PAX_BLK;
485 break;
486 case S_IFREG:
487 /*
488 * only regular files with have data to store on the
489 * archive. all others will store a zero length skip.
490 * the skip field is used by pax for actual data it has
491 * to read (or skip over).
492 */
493 arcn->type = PAX_REG;
494 arcn->skip = arcn->sb.st_size;
495 break;
496 case S_IFLNK:
497 arcn->type = PAX_SLK;
498 /*
499 * have to read the symlink path from the file
500 */
501 if ((cnt = readlink(ftent->fts_path, arcn->ln_name,
502 PAXPATHLEN)) < 0) {
503 syswarn(1, errno, "Unable to read symlink %s",
504 ftent->fts_path);
505 continue;
506 }
507 /*
508 * set link name length, watch out readlink does not
509 * always NUL terminate the link path
510 */
511 arcn->ln_name[cnt] = '\0';
512 arcn->ln_nlen = cnt;
513 break;
514 case S_IFSOCK:
515 /*
516 * under BSD storing a socket is senseless but we will
517 * let the format specific write function make the
518 * decision of what to do with it.
519 */
520 arcn->type = PAX_SCK;
521 break;
522 case S_IFIFO:
523 arcn->type = PAX_FIF;
524 break;
525 }
526 break;
527 }
528
529 /*
530 * copy file name, set file name length
531 */
532 arcn->nlen = strlcpy(arcn->name, ftent->fts_path, sizeof(arcn->name));
533 if (arcn->nlen >= sizeof(arcn->name))
534 arcn->nlen = sizeof(arcn->name) - 1; /* XXX truncate? */
535 arcn->org_name = ftent->fts_path;
536 return(0);
537 }
538
539 /*
540 * getpathname()
541 * Reads a pathname from stdin, handling NUL- or newline-termination.
542 * Return:
543 * NULL at end of file, otherwise the NUL-terminated buffer.
544 */
545
546 static char *
547 getpathname(char *buf, int buflen)
548 {
549 char *bp, *ep;
550 int ch, term;
551
552 if (zeroflag) {
553 /*
554 * Read a NUL-terminated pathname, being especially
555 * paranoid about proper termination and pathname length.
556 */
557 for (bp = buf, ep = buf + buflen; bp < ep; bp++) {
558 if ((ch = getchar()) == EOF) {
559 if (bp != buf)
560 paxwarn(1, "Ignoring unterminated "
561 "pathname at EOF");
562 return(NULL);
563 }
564 if ((*bp = ch) == '\0')
565 return(buf);
566 }
567 /* Too long - skip this path */
568 *--bp = '\0';
569 term = '\0';
570 } else {
571 if (fgets(buf, buflen, stdin) == NULL)
572 return(NULL);
573 if ((bp = strchr(buf, '\n')) != NULL || feof(stdin)) {
574 if (bp != NULL)
575 *bp = '\0';
576 return(buf);
577 }
578 /* Too long - skip this path */
579 term = '\n';
580 }
581 while ((ch = getchar()) != term && ch != EOF)
582 ;
583 paxwarn(1, "Ignoring too-long pathname: %s", buf);
584 return(NULL);
585 }