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