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