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