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