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