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