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