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