xref: /openbsd/bin/pax/ftree.c (revision b27f9b39)
1 /*	$OpenBSD: ftree.c,v 1.43 2024/08/15 00:47:44 guenther 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/types.h>
38 #include <sys/stat.h>
39 #include <errno.h>
40 #include <fts.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 #include "pax.h"
47 #include "extern.h"
48 
49 /*
50  * Data structure used to store the file args to be handed to fts().
51  * It keeps track of which args generated a "selected" member.
52  */
53 typedef struct ftree {
54 	char		*fname;		/* file tree name */
55 	int		refcnt;		/* had a selected (or skipped) file? */
56 	int		chflg;		/* change directory flag */
57 	struct ftree	*fow;		/* pointer to next entry on list */
58 } FTREE;
59 
60 
61 /*
62  * routines to interface with the fts library function.
63  *
64  * file args supplied to pax are stored on a single linked list (of type FTREE)
65  * and given to fts to be processed one at a time. pax "selects" files from
66  * the expansion of each arg into the corresponding file tree (if the arg is a
67  * directory, otherwise the node itself is just passed to pax). The selection
68  * is modified by the -n and -u flags. The user is informed when a specific
69  * file arg does not generate any selected files. -n keeps expanding the file
70  * tree arg until one of its files is selected, then skips to the next file
71  * arg. when the user does not supply the file trees as command line args to
72  * pax, they are read from stdin
73  */
74 
75 static FTS *ftsp = NULL;		/* current FTS handle */
76 static int ftsopts;			/* options to be used on fts_open */
77 static char *farray[2];			/* array for passing each arg to fts */
78 static FTREE *fthead = NULL;		/* head of linked list of file args */
79 static FTREE *fttail = NULL;		/* tail of linked list of file args */
80 static FTREE *ftcur = NULL;		/* current file arg being processed */
81 static FTSENT *ftent = NULL;		/* current file tree entry */
82 static int ftree_skip;			/* when set skip to next file arg */
83 
84 static int ftree_arg(void);
85 static char *getpathname(char *, int);
86 
87 /*
88  * ftree_start()
89  *	initialize the options passed to fts_open() during this run of pax
90  *	options are based on the selection of pax options by the user
91  *	fts_start() also calls fts_arg() to open the first valid file arg. We
92  *	also attempt to reset directory access times when -t (tflag) is set.
93  * Return:
94  *	0 if there is at least one valid file arg to process, -1 otherwise
95  */
96 
97 int
ftree_start(void)98 ftree_start(void)
99 {
100 	/*
101 	 * set up the operation mode of fts, open the first file arg. We must
102 	 * use FTS_NOCHDIR, as the user may have to open multiple archives and
103 	 * if fts did a chdir off into the boondocks, we may create an archive
104 	 * volume in an place where the user did not expect to.
105 	 */
106 	ftsopts = FTS_NOCHDIR;
107 
108 	/*
109 	 * optional user flags that effect file traversal
110 	 * -H command line symlink follow only (half follow)
111 	 * -L follow sylinks (logical)
112 	 * -P do not follow sylinks (physical). This is the default.
113 	 * -X do not cross over mount points
114 	 * -t preserve access times on files read.
115 	 * -n select only the first member of a file tree when a match is found
116 	 * -d do not extract subtrees rooted at a directory arg.
117 	 */
118 	if (Lflag)
119 		ftsopts |= FTS_LOGICAL;
120 	else
121 		ftsopts |= FTS_PHYSICAL;
122 	if (Hflag)
123 		ftsopts |= FTS_COMFOLLOW;
124 	if (Xflag)
125 		ftsopts |= FTS_XDEV;
126 
127 	if ((fthead == NULL) && ((farray[0] = malloc(PAXPATHLEN+2)) == NULL)) {
128 		paxwarn(1, "Unable to allocate memory for file name buffer");
129 		return(-1);
130 	}
131 
132 	if (ftree_arg() < 0)
133 		return(-1);
134 	if (tflag && (atdir_start() < 0))
135 		return(-1);
136 	return(0);
137 }
138 
139 /*
140  * ftree_add()
141  *	add the arg to the linked list of files to process. Each will be
142  *	processed by fts one at a time
143  * Return:
144  *	0 if added to the linked list, -1 if failed
145  */
146 
147 int
ftree_add(char * str,int chflg)148 ftree_add(char *str, int chflg)
149 {
150 	FTREE *ft;
151 	int len;
152 
153 	/*
154 	 * simple check for bad args
155 	 */
156 	if ((str == NULL) || (*str == '\0')) {
157 		paxwarn(0, "Invalid file name argument");
158 		return(-1);
159 	}
160 
161 	/*
162 	 * allocate FTREE node and add to the end of the linked list (args are
163 	 * processed in the same order they were passed to pax). Get rid of any
164 	 * trailing / the user may pass us. (watch out for / by itself).
165 	 */
166 	if ((ft = malloc(sizeof(FTREE))) == NULL) {
167 		paxwarn(0, "Unable to allocate memory for filename");
168 		return(-1);
169 	}
170 
171 	if (((len = strlen(str) - 1) > 0) && (str[len] == '/'))
172 		str[len] = '\0';
173 	ft->fname = str;
174 	ft->refcnt = 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
ftree_sel(ARCHD * arcn)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_skipped_newer()
221  *	file has been skipped because a newer file exists and -u/-D given
222  */
223 
224 void
ftree_skipped_newer(ARCHD * arcn)225 ftree_skipped_newer(ARCHD *arcn)
226 {
227 	/* skipped due to -u/-D, mark accordingly */
228 	if (ftcur != NULL)
229 		ftcur->refcnt = 1;
230 }
231 
232 /*
233  * ftree_chk()
234  *	called at end on pax execution. Prints all those file args that did not
235  *	have a selected member (reference count still 0)
236  */
237 
238 void
ftree_chk(void)239 ftree_chk(void)
240 {
241 	FTREE *ft;
242 	int wban = 0;
243 
244 	/*
245 	 * make sure all dir access times were reset.
246 	 */
247 	if (tflag)
248 		atdir_end();
249 
250 	/*
251 	 * walk down list and check reference count. Print out those members
252 	 * that never had a match
253 	 */
254 	for (ft = fthead; ft != NULL; ft = ft->fow) {
255 		if ((ft->refcnt > 0) || ft->chflg)
256 			continue;
257 		if (wban == 0) {
258 			paxwarn(1,"WARNING! These file names were not selected:");
259 			++wban;
260 		}
261 		(void)fprintf(stderr, "%s\n", ft->fname);
262 	}
263 }
264 
265 /*
266  * ftree_arg()
267  *	Get the next file arg for fts to process. Can be from either the linked
268  *	list or read from stdin when the user did not them as args to pax. Each
269  *	arg is processed until the first successful fts_open().
270  * Return:
271  *	0 when the next arg is ready to go, -1 if out of file args (or EOF on
272  *	stdin).
273  */
274 
275 static int
ftree_arg(void)276 ftree_arg(void)
277 {
278 
279 	/*
280 	 * close off the current file tree
281 	 */
282 	if (ftsp != NULL) {
283 		(void)fts_close(ftsp);
284 		ftsp = NULL;
285 	}
286 
287 	/*
288 	 * keep looping until we get a valid file tree to process. Stop when we
289 	 * reach the end of the list (or get an eof on stdin)
290 	 */
291 	for (;;) {
292 		if (fthead == NULL) {
293 			/*
294 			 * the user didn't supply any args, get the file trees
295 			 * to process from stdin;
296 			 */
297 			if (getpathname(farray[0], PAXPATHLEN+1) == NULL)
298 				return(-1);
299 		} else {
300 			/*
301 			 * the user supplied the file args as arguments to pax
302 			 */
303 			if (ftcur == NULL)
304 				ftcur = fthead;
305 			else if ((ftcur = ftcur->fow) == NULL)
306 				return(-1);
307 			if (ftcur->chflg) {
308 				/* First fchdir() back... */
309 				if (fchdir(cwdfd) == -1) {
310 					syswarn(1, errno,
311 					  "Can't fchdir to starting directory");
312 					return(-1);
313 				}
314 				if (chdir(ftcur->fname) == -1) {
315 					syswarn(1, errno, "Can't chdir to %s",
316 					    ftcur->fname);
317 					return(-1);
318 				}
319 				continue;
320 			} else
321 				farray[0] = ftcur->fname;
322 		}
323 
324 		/*
325 		 * watch it, fts wants the file arg stored in a array of char
326 		 * ptrs, with the last one a null. we use a two element array
327 		 * and set farray[0] to point at the buffer with the file name
328 		 * in it. We cannot pass all the file args to fts at one shot
329 		 * as we need to keep a handle on which file arg generates what
330 		 * files (the -n and -d flags need this). If the open is
331 		 * successful, return a 0.
332 		 */
333 		if ((ftsp = fts_open(farray, ftsopts, NULL)) != NULL)
334 			break;
335 	}
336 	return(0);
337 }
338 
339 /*
340  * next_file()
341  *	supplies the next file to process in the supplied archd structure.
342  * Return:
343  *	0 when contents of arcn have been set with the next file, -1 when done.
344  */
345 
346 int
next_file(ARCHD * arcn)347 next_file(ARCHD *arcn)
348 {
349 	int cnt;
350 
351 	/*
352 	 * ftree_sel() might have set the ftree_skip flag if the user has the
353 	 * -n option and a file was selected from this file arg tree. (-n says
354 	 * only one member is matched for each pattern) ftree_skip being 1
355 	 * forces us to go to the next arg now.
356 	 */
357 	if (ftree_skip) {
358 		/*
359 		 * clear and go to next arg
360 		 */
361 		ftree_skip = 0;
362 		if (ftree_arg() < 0)
363 			return(-1);
364 	}
365 
366 	/*
367 	 * loop until we get a valid file to process
368 	 */
369 	for (;;) {
370 		if ((ftent = fts_read(ftsp)) == NULL) {
371 			if (errno)
372 				syswarn(1, errno, "next_file");
373 			/*
374 			 * out of files in this tree, go to next arg, if none
375 			 * we are done
376 			 */
377 			if (ftree_arg() < 0)
378 				return(-1);
379 			continue;
380 		}
381 
382 		/*
383 		 * handle each type of fts_read() flag
384 		 */
385 		switch (ftent->fts_info) {
386 		case FTS_D:
387 		case FTS_DEFAULT:
388 		case FTS_F:
389 		case FTS_SL:
390 		case FTS_SLNONE:
391 			/*
392 			 * these are all ok
393 			 */
394 			break;
395 		case FTS_DP:
396 			/*
397 			 * already saw this directory. If the user wants file
398 			 * access times reset, we use this to restore the
399 			 * access time for this directory since this is the
400 			 * last time we will see it in this file subtree
401 			 * remember to force the time (this is -t on a read
402 			 * directory, not a created directory).
403 			 */
404 			if (!tflag)
405 				continue;
406 			do_atdir(ftent->fts_path, ftent->fts_statp->st_dev,
407 			    ftent->fts_statp->st_ino);
408 			continue;
409 		case FTS_DC:
410 			/*
411 			 * fts claims a file system cycle
412 			 */
413 			paxwarn(1,"File system cycle found at %s",ftent->fts_path);
414 			continue;
415 		case FTS_DNR:
416 			syswarn(1, ftent->fts_errno,
417 			    "Unable to read directory %s", ftent->fts_path);
418 			continue;
419 		case FTS_ERR:
420 			syswarn(1, ftent->fts_errno,
421 			    "File system traversal error");
422 			continue;
423 		case FTS_NS:
424 		case FTS_NSOK:
425 			syswarn(1, ftent->fts_errno,
426 			    "Unable to access %s", ftent->fts_path);
427 			continue;
428 		}
429 
430 		/*
431 		 * ok got a file tree node to process. copy info into arcn
432 		 * structure (initialize as required)
433 		 */
434 		arcn->skip = 0;
435 		arcn->pad = 0;
436 		arcn->ln_nlen = 0;
437 		arcn->ln_name[0] = '\0';
438 		memcpy(&arcn->sb, ftent->fts_statp, sizeof(arcn->sb));
439 
440 		/*
441 		 * file type based set up and copy into the arcn struct
442 		 * SIDE NOTE:
443 		 * we try to reset the access time on all files and directories
444 		 * we may read when the -t flag is specified. files are reset
445 		 * when we close them after copying. we reset the directories
446 		 * when we are done with their file tree (we also clean up at
447 		 * end in case we cut short a file tree traversal). However
448 		 * there is no way to reset access times on symlinks.
449 		 */
450 		switch (S_IFMT & arcn->sb.st_mode) {
451 		case S_IFDIR:
452 			arcn->type = PAX_DIR;
453 			if (!tflag)
454 				break;
455 			add_atdir(ftent->fts_path, arcn->sb.st_dev,
456 			    arcn->sb.st_ino, &arcn->sb.st_mtim,
457 			    &arcn->sb.st_atim);
458 			break;
459 		case S_IFCHR:
460 			arcn->type = PAX_CHR;
461 			break;
462 		case S_IFBLK:
463 			arcn->type = PAX_BLK;
464 			break;
465 		case S_IFREG:
466 			/*
467 			 * only regular files with have data to store on the
468 			 * archive. all others will store a zero length skip.
469 			 * the skip field is used by pax for actual data it has
470 			 * to read (or skip over).
471 			 */
472 			arcn->type = PAX_REG;
473 			arcn->skip = arcn->sb.st_size;
474 			break;
475 		case S_IFLNK:
476 			arcn->type = PAX_SLK;
477 			/*
478 			 * have to read the symlink path from the file
479 			 */
480 			if ((cnt = readlink(ftent->fts_path, arcn->ln_name,
481 			    PAXPATHLEN)) == -1) {
482 				syswarn(1, errno, "Unable to read symlink %s",
483 				    ftent->fts_path);
484 				continue;
485 			}
486 			/*
487 			 * set link name length, watch out readlink does not
488 			 * NUL terminate the link path
489 			 */
490 			arcn->ln_name[cnt] = '\0';
491 			arcn->ln_nlen = cnt;
492 			break;
493 		case S_IFSOCK:
494 			/*
495 			 * under BSD storing a socket is senseless but we will
496 			 * let the format specific write function make the
497 			 * decision of what to do with it.
498 			 */
499 			arcn->type = PAX_SCK;
500 			break;
501 		case S_IFIFO:
502 			arcn->type = PAX_FIF;
503 			break;
504 		}
505 		break;
506 	}
507 
508 	/*
509 	 * copy file name, set file name length
510 	 */
511 	arcn->nlen = strlcpy(arcn->name, ftent->fts_path, sizeof(arcn->name));
512 	if ((size_t)arcn->nlen >= sizeof(arcn->name))
513 		arcn->nlen = sizeof(arcn->name) - 1; /* XXX truncate? */
514 	arcn->org_name = ftent->fts_path;
515 	return(0);
516 }
517 
518 /*
519  * getpathname()
520  *	Reads a pathname from stdin, handling NUL- or newline-termination.
521  * Return:
522  *	NULL at end of file, otherwise the NUL-terminated buffer.
523  */
524 
525 static char *
getpathname(char * buf,int buflen)526 getpathname(char *buf, int buflen)
527 {
528 	char *bp, *ep;
529 	int ch, term;
530 
531 	if (zeroflag) {
532 		/*
533 		 * Read a NUL-terminated pathname, being especially
534 		 * paranoid about proper termination and pathname length.
535 		 */
536 		for (bp = buf, ep = buf + buflen; bp < ep; bp++) {
537 			if ((ch = getchar()) == EOF) {
538 				if (bp != buf)
539 					paxwarn(1, "Ignoring unterminated "
540 					    "pathname at EOF");
541 				return(NULL);
542 			}
543 			if ((*bp = ch) == '\0')
544 				return(buf);
545 		}
546 		/* Too long - skip this path */
547 		*--bp = '\0';
548 		term = '\0';
549 	} else {
550 		if (fgets(buf, buflen, stdin) == NULL)
551 			return(NULL);
552 		if ((bp = strchr(buf, '\n')) != NULL || feof(stdin)) {
553 			if (bp != NULL)
554 				*bp = '\0';
555 			return(buf);
556 		}
557 		/* Too long - skip this path */
558 		term = '\n';
559 	}
560 	while ((ch = getchar()) != term && ch != EOF)
561 		continue;
562 	paxwarn(1, "Ignoring too-long pathname: %s", buf);
563 	return(NULL);
564 }
565