re-mark 1.29b-2 as not yet uploaded (merge madness!)
[debian/tar] / src / names.c
1 /* Various processing of names.
2
3    Copyright 1988, 1992, 1994, 1996-2001, 2003-2007, 2009, 2013-2016
4    Free Software Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify it
7    under the terms of the GNU General Public License as published by the
8    Free Software Foundation; either version 3, or (at your option) any later
9    version.
10
11    This program is distributed in the hope that it will be useful, but
12    WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
14    Public License for more details.
15
16    You should have received a copy of the GNU General Public License along
17    with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #include <system.h>
20
21 #include <fnmatch.h>
22 #include <hash.h>
23 #include <quotearg.h>
24 #include <wordsplit.h>
25 #include <argp.h>
26
27 #include "common.h"
28 \f
29 static void name_add_option (int option, const char *arg);
30 static void name_add_dir (const char *name);
31 static void name_add_file (const char *name);
32 \f
33 enum
34   {
35     EXCLUDE_BACKUPS_OPTION = 256,
36     EXCLUDE_CACHES_OPTION,
37     EXCLUDE_CACHES_UNDER_OPTION,
38     EXCLUDE_CACHES_ALL_OPTION,
39     EXCLUDE_OPTION,
40     EXCLUDE_IGNORE_OPTION,
41     EXCLUDE_IGNORE_RECURSIVE_OPTION,
42     EXCLUDE_TAG_OPTION,
43     EXCLUDE_TAG_UNDER_OPTION,
44     EXCLUDE_TAG_ALL_OPTION,
45     EXCLUDE_VCS_OPTION,
46     EXCLUDE_VCS_IGNORES_OPTION,
47     IGNORE_CASE_OPTION,
48     NO_IGNORE_CASE_OPTION,
49     ANCHORED_OPTION,
50     NO_ANCHORED_OPTION,
51     RECURSION_OPTION,
52     NO_RECURSION_OPTION,
53     UNQUOTE_OPTION,
54     NO_UNQUOTE_OPTION,
55     NO_VERBATIM_FILES_FROM_OPTION,
56     NO_WILDCARDS_MATCH_SLASH_OPTION,
57     NO_WILDCARDS_OPTION,
58     NULL_OPTION,
59     NO_NULL_OPTION,
60     VERBATIM_FILES_FROM_OPTION,
61     WILDCARDS_MATCH_SLASH_OPTION,
62     WILDCARDS_OPTION
63   };
64
65 static struct argp_option names_options[] = {
66 #define GRID 100
67   {NULL, 0, NULL, 0,
68    N_("Local file name selection:"), GRID },
69
70   {"add-file", ARGP_KEY_ARG, N_("FILE"), 0,
71    N_("add given FILE to the archive (useful if its name starts with a dash)"), GRID+1 },
72   {"directory", 'C', N_("DIR"), 0,
73    N_("change to directory DIR"), GRID+1 },
74   {"files-from", 'T', N_("FILE"), 0,
75    N_("get names to extract or create from FILE"), GRID+1 },
76   {"null", NULL_OPTION, 0, 0,
77    N_("-T reads null-terminated names; implies --verbatim-files-from"),
78       GRID+1 },
79   {"no-null", NO_NULL_OPTION, 0, 0,
80    N_("disable the effect of the previous --null option"), GRID+1 },
81   {"unquote", UNQUOTE_OPTION, 0, 0,
82    N_("unquote input file or member names (default)"), GRID+1 },
83   {"no-unquote", NO_UNQUOTE_OPTION, 0, 0,
84    N_("do not unquote input file or member names"), GRID+1 },
85   {"verbatim-files-from", VERBATIM_FILES_FROM_OPTION, 0, 0,
86    N_("-T reads file names verbatim (no option handling)"), GRID+1 },
87   {"no-verbatim-files-from", NO_VERBATIM_FILES_FROM_OPTION, 0, 0,
88    N_("-T treats file names starting with dash as options (default)"),
89       GRID+1 },
90   {"exclude", EXCLUDE_OPTION, N_("PATTERN"), 0,
91    N_("exclude files, given as a PATTERN"), GRID+1 },
92   {"exclude-from", 'X', N_("FILE"), 0,
93    N_("exclude patterns listed in FILE"), GRID+1 },
94   {"exclude-caches", EXCLUDE_CACHES_OPTION, 0, 0,
95    N_("exclude contents of directories containing CACHEDIR.TAG, "
96       "except for the tag file itself"), GRID+1 },
97   {"exclude-caches-under", EXCLUDE_CACHES_UNDER_OPTION, 0, 0,
98    N_("exclude everything under directories containing CACHEDIR.TAG"),
99    GRID+1 },
100   {"exclude-caches-all", EXCLUDE_CACHES_ALL_OPTION, 0, 0,
101    N_("exclude directories containing CACHEDIR.TAG"), GRID+1 },
102   {"exclude-tag", EXCLUDE_TAG_OPTION, N_("FILE"), 0,
103    N_("exclude contents of directories containing FILE, except"
104       " for FILE itself"), GRID+1 },
105   {"exclude-ignore", EXCLUDE_IGNORE_OPTION, N_("FILE"), 0,
106     N_("read exclude patterns for each directory from FILE, if it exists"),
107    GRID+1 },
108   {"exclude-ignore-recursive", EXCLUDE_IGNORE_RECURSIVE_OPTION, N_("FILE"), 0,
109     N_("read exclude patterns for each directory and its subdirectories "
110        "from FILE, if it exists"), GRID+1 },
111   {"exclude-tag-under", EXCLUDE_TAG_UNDER_OPTION, N_("FILE"), 0,
112    N_("exclude everything under directories containing FILE"), GRID+1 },
113   {"exclude-tag-all", EXCLUDE_TAG_ALL_OPTION, N_("FILE"), 0,
114    N_("exclude directories containing FILE"), GRID+1 },
115   {"exclude-vcs", EXCLUDE_VCS_OPTION, NULL, 0,
116    N_("exclude version control system directories"), GRID+1 },
117   {"exclude-vcs-ignores", EXCLUDE_VCS_IGNORES_OPTION, NULL, 0,
118    N_("read exclude patterns from the VCS ignore files"), GRID+1 },
119   {"exclude-backups", EXCLUDE_BACKUPS_OPTION, NULL, 0,
120    N_("exclude backup and lock files"), GRID+1 },
121   {"recursion", RECURSION_OPTION, 0, 0,
122    N_("recurse into directories (default)"), GRID+1 },
123   {"no-recursion", NO_RECURSION_OPTION, 0, 0,
124    N_("avoid descending automatically in directories"), GRID+1 },
125 #undef GRID
126
127 #define GRID 120
128   {NULL, 0, NULL, 0,
129    N_("File name matching options (affect both exclude and include patterns):"),
130    GRID },
131   {"anchored", ANCHORED_OPTION, 0, 0,
132    N_("patterns match file name start"), GRID+1 },
133   {"no-anchored", NO_ANCHORED_OPTION, 0, 0,
134    N_("patterns match after any '/' (default for exclusion)"), GRID+1 },
135   {"ignore-case", IGNORE_CASE_OPTION, 0, 0,
136    N_("ignore case"), GRID+1 },
137   {"no-ignore-case", NO_IGNORE_CASE_OPTION, 0, 0,
138    N_("case sensitive matching (default)"), GRID+1 },
139   {"wildcards", WILDCARDS_OPTION, 0, 0,
140    N_("use wildcards (default for exclusion)"), GRID+1 },
141   {"no-wildcards", NO_WILDCARDS_OPTION, 0, 0,
142    N_("verbatim string matching"), GRID+1 },
143   {"wildcards-match-slash", WILDCARDS_MATCH_SLASH_OPTION, 0, 0,
144    N_("wildcards match '/' (default for exclusion)"), GRID+1 },
145   {"no-wildcards-match-slash", NO_WILDCARDS_MATCH_SLASH_OPTION, 0, 0,
146    N_("wildcards do not match '/'"), GRID+1 },
147 #undef GRID
148   
149   {NULL}
150 };
151
152 static bool
153 is_file_selection_option (int key)
154 {
155   struct argp_option *p;
156
157   for (p = names_options;
158        !(p->name == NULL && p->key == 0 && p->doc == NULL); p++)
159     if (p->key == key)
160       return true;
161   return false;
162 }  
163 \f
164 /* Either NL or NUL, as decided by the --null option.  */
165 static char filename_terminator = '\n';
166 /* Treat file names read from -T input verbatim */
167 static bool verbatim_files_from_option;
168
169 static error_t
170 names_parse_opt (int key, char *arg, struct argp_state *state)
171 {
172   switch (key)
173     {
174     case 'C':
175       name_add_dir (arg);
176       break;
177
178     case 'T':
179       name_add_file (arg);
180       /* Indicate we've been given -T option. This is for backward
181          compatibility only, so that `tar cfT archive /dev/null will
182          succeed */
183       files_from_option = true;
184       break;
185
186     default:
187       if (is_file_selection_option (key))
188         name_add_option (key, arg);
189       else
190         return ARGP_ERR_UNKNOWN;
191     }
192   return 0;
193 }
194 \f
195 /* Wildcard matching settings */
196 enum wildcards
197   {
198     default_wildcards, /* For exclusion == enable_wildcards,
199                           for inclusion == disable_wildcards */
200     disable_wildcards,
201     enable_wildcards
202   };
203
204 static enum wildcards wildcards = default_wildcards;
205   /* Wildcard settings (--wildcards/--no-wildcards) */
206 static int matching_flags = 0;
207   /* exclude_fnmatch options */
208 static int include_anchored = EXCLUDE_ANCHORED;
209   /* Pattern anchoring options used for file inclusion */
210   
211 #define EXCLUDE_OPTIONS                                         \
212   (((wildcards != disable_wildcards) ? EXCLUDE_WILDCARDS : 0)   \
213   | matching_flags                                              \
214   | recursion_option)
215
216 #define INCLUDE_OPTIONS                                             \
217   (((wildcards == enable_wildcards) ? EXCLUDE_WILDCARDS : 0)        \
218   | include_anchored                                                \
219   | matching_flags                                                  \
220   | recursion_option)
221 \f
222 static char const * const vcs_file_table[] = {
223   /* CVS: */
224   "CVS",
225   ".cvsignore",
226   /* RCS: */
227   "RCS",
228   /* SCCS: */
229   "SCCS",
230   /* SVN: */
231   ".svn",
232   /* git: */
233   ".git",
234   ".gitignore",
235   ".gitattributes",
236   ".gitmodules",
237   /* Arch: */
238   ".arch-ids",
239   "{arch}",
240   "=RELEASE-ID",
241   "=meta-update",
242   "=update",
243   /* Bazaar */
244   ".bzr",
245   ".bzrignore",
246   ".bzrtags",
247   /* Mercurial */
248   ".hg",
249   ".hgignore",
250   ".hgtags",
251   /* darcs */
252   "_darcs",
253   NULL
254 };
255
256 static char const * const backup_file_table[] = {
257   ".#*",
258   "*~",
259   "#*#",
260   NULL
261 };
262
263 static void
264 add_exclude_array (char const * const * fv, int opts)
265 {
266   int i;
267
268   for (i = 0; fv[i]; i++)
269     add_exclude (excluded, fv[i], opts);
270 }
271 \f
272 static void
273 handle_file_selection_option (int key, const char *arg)
274 {
275   switch (key)
276     {
277     case EXCLUDE_BACKUPS_OPTION:
278       add_exclude_array (backup_file_table, EXCLUDE_WILDCARDS);
279       break;
280
281     case EXCLUDE_OPTION:
282       add_exclude (excluded, arg, EXCLUDE_OPTIONS);
283       break;
284
285     case EXCLUDE_CACHES_OPTION:
286       add_exclusion_tag ("CACHEDIR.TAG", exclusion_tag_contents,
287                          cachedir_file_p);
288       break;
289
290     case EXCLUDE_CACHES_UNDER_OPTION:
291       add_exclusion_tag ("CACHEDIR.TAG", exclusion_tag_under,
292                          cachedir_file_p);
293       break;
294
295     case EXCLUDE_CACHES_ALL_OPTION:
296       add_exclusion_tag ("CACHEDIR.TAG", exclusion_tag_all,
297                          cachedir_file_p);
298       break;
299
300     case EXCLUDE_IGNORE_OPTION:
301       excfile_add (arg, EXCL_NON_RECURSIVE);
302       break;
303
304     case EXCLUDE_IGNORE_RECURSIVE_OPTION:
305       excfile_add (arg, EXCL_RECURSIVE);
306       break;
307
308     case EXCLUDE_TAG_OPTION:
309       add_exclusion_tag (arg, exclusion_tag_contents, NULL);
310       break;
311
312     case EXCLUDE_TAG_UNDER_OPTION:
313       add_exclusion_tag (arg, exclusion_tag_under, NULL);
314       break;
315
316     case EXCLUDE_TAG_ALL_OPTION:
317       add_exclusion_tag (arg, exclusion_tag_all, NULL);
318       break;
319
320     case EXCLUDE_VCS_OPTION:
321       add_exclude_array (vcs_file_table, 0);
322       break;
323
324     case EXCLUDE_VCS_IGNORES_OPTION:
325       exclude_vcs_ignores ();
326       break;
327
328     case RECURSION_OPTION:
329       recursion_option = FNM_LEADING_DIR;
330       break;
331
332     case NO_RECURSION_OPTION:
333       recursion_option = 0;
334       break;
335
336     case UNQUOTE_OPTION:
337       unquote_option = true;
338       break;
339
340     case NO_UNQUOTE_OPTION:
341       unquote_option = false;
342       break;
343
344     case NULL_OPTION:
345       filename_terminator = '\0';
346       verbatim_files_from_option = true;
347       break;
348
349     case NO_NULL_OPTION:
350       filename_terminator = '\n';
351       verbatim_files_from_option = false;
352       break;
353
354     case 'X':
355       if (add_exclude_file (add_exclude, excluded, arg, EXCLUDE_OPTIONS, '\n')
356           != 0)
357         {
358           int e = errno;
359           FATAL_ERROR ((0, e, "%s", quotearg_colon (arg)));
360         }
361       break;
362
363     case ANCHORED_OPTION:
364       matching_flags |= EXCLUDE_ANCHORED;
365       break;
366
367     case NO_ANCHORED_OPTION:
368       include_anchored = 0; /* Clear the default for comman line args */
369       matching_flags &= ~ EXCLUDE_ANCHORED;
370       break;
371
372     case IGNORE_CASE_OPTION:
373       matching_flags |= FNM_CASEFOLD;
374       break;
375
376     case NO_IGNORE_CASE_OPTION:
377       matching_flags &= ~ FNM_CASEFOLD;
378       break;
379
380     case WILDCARDS_OPTION:
381       wildcards = enable_wildcards;
382       break;
383
384     case NO_WILDCARDS_OPTION:
385       wildcards = disable_wildcards;
386       break;
387
388     case WILDCARDS_MATCH_SLASH_OPTION:
389       matching_flags &= ~ FNM_FILE_NAME;
390       break;
391
392     case NO_WILDCARDS_MATCH_SLASH_OPTION:
393       matching_flags |= FNM_FILE_NAME;
394       break;
395
396     case VERBATIM_FILES_FROM_OPTION:
397       verbatim_files_from_option = true;
398       break;
399
400     case NO_VERBATIM_FILES_FROM_OPTION:
401       verbatim_files_from_option = false;
402       break;
403
404     default:
405       FATAL_ERROR ((0, 0, "unhandled positional option %d", key));
406     }
407 }
408
409 static struct argp names_argp = {
410   names_options,
411   names_parse_opt,
412   NULL,
413   NULL,
414   NULL,
415   NULL,
416   NULL
417 };
418
419 struct argp_child names_argp_children[] = {
420   { &names_argp, 0, "", 0 },
421   { NULL }
422 };
423 \f
424 /* User and group names.  */
425
426 /* Make sure you link with the proper libraries if you are running the
427    Yellow Peril (thanks for the good laugh, Ian J.!), or, euh... NIS.
428    This code should also be modified for non-UNIX systems to do something
429    reasonable.  */
430
431 static char *cached_uname;
432 static char *cached_gname;
433
434 static uid_t cached_uid;        /* valid only if cached_uname is not empty */
435 static gid_t cached_gid;        /* valid only if cached_gname is not empty */
436
437 /* These variables are valid only if nonempty.  */
438 static char *cached_no_such_uname;
439 static char *cached_no_such_gname;
440
441 /* These variables are valid only if nonzero.  It's not worth optimizing
442    the case for weird systems where 0 is not a valid uid or gid.  */
443 static uid_t cached_no_such_uid;
444 static gid_t cached_no_such_gid;
445
446 /* Given UID, find the corresponding UNAME.  */
447 void
448 uid_to_uname (uid_t uid, char **uname)
449 {
450   struct passwd *passwd;
451
452   if (uid != 0 && uid == cached_no_such_uid)
453     {
454       *uname = xstrdup ("");
455       return;
456     }
457
458   if (!cached_uname || uid != cached_uid)
459     {
460       passwd = getpwuid (uid);
461       if (passwd)
462         {
463           cached_uid = uid;
464           assign_string (&cached_uname, passwd->pw_name);
465         }
466       else
467         {
468           cached_no_such_uid = uid;
469           *uname = xstrdup ("");
470           return;
471         }
472     }
473   *uname = xstrdup (cached_uname);
474 }
475
476 /* Given GID, find the corresponding GNAME.  */
477 void
478 gid_to_gname (gid_t gid, char **gname)
479 {
480   struct group *group;
481
482   if (gid != 0 && gid == cached_no_such_gid)
483     {
484       *gname = xstrdup ("");
485       return;
486     }
487
488   if (!cached_gname || gid != cached_gid)
489     {
490       group = getgrgid (gid);
491       if (group)
492         {
493           cached_gid = gid;
494           assign_string (&cached_gname, group->gr_name);
495         }
496       else
497         {
498           cached_no_such_gid = gid;
499           *gname = xstrdup ("");
500           return;
501         }
502     }
503   *gname = xstrdup (cached_gname);
504 }
505
506 /* Given UNAME, set the corresponding UID and return 1, or else, return 0.  */
507 int
508 uname_to_uid (char const *uname, uid_t *uidp)
509 {
510   struct passwd *passwd;
511
512   if (cached_no_such_uname
513       && strcmp (uname, cached_no_such_uname) == 0)
514     return 0;
515
516   if (!cached_uname
517       || uname[0] != cached_uname[0]
518       || strcmp (uname, cached_uname) != 0)
519     {
520       passwd = getpwnam (uname);
521       if (passwd)
522         {
523           cached_uid = passwd->pw_uid;
524           assign_string (&cached_uname, passwd->pw_name);
525         }
526       else
527         {
528           assign_string (&cached_no_such_uname, uname);
529           return 0;
530         }
531     }
532   *uidp = cached_uid;
533   return 1;
534 }
535
536 /* Given GNAME, set the corresponding GID and return 1, or else, return 0.  */
537 int
538 gname_to_gid (char const *gname, gid_t *gidp)
539 {
540   struct group *group;
541
542   if (cached_no_such_gname
543       && strcmp (gname, cached_no_such_gname) == 0)
544     return 0;
545
546   if (!cached_gname
547       || gname[0] != cached_gname[0]
548       || strcmp (gname, cached_gname) != 0)
549     {
550       group = getgrnam (gname);
551       if (group)
552         {
553           cached_gid = group->gr_gid;
554           assign_string (&cached_gname, gname);
555         }
556       else
557         {
558           assign_string (&cached_no_such_gname, gname);
559           return 0;
560         }
561     }
562   *gidp = cached_gid;
563   return 1;
564 }
565
566 \f
567 static struct name *
568 make_name (const char *file_name)
569 {
570   struct name *p = xzalloc (sizeof (*p));
571   if (!file_name)
572     file_name = "";
573   p->name = xstrdup (file_name);
574   p->length = strlen (p->name);
575   return p;
576 }
577
578 static void
579 free_name (struct name *p)
580 {
581   if (p)
582     {
583       free (p->name);
584       free (p->caname);
585       free (p);
586     }
587 }
588
589 \f
590 /* Names from the command call.  */
591
592 static struct name *namelist;   /* first name in list, if any */
593 static struct name *nametail;   /* end of name list */
594
595 /* File name arguments are processed in two stages: first a
596    name element list (see below) is filled, then the names from it
597    are moved into the namelist.
598
599    This awkward process is needed only to implement --same-order option,
600    which is meant to help process large archives on machines with
601    limited memory.  With this option on, namelist contains at most one
602    entry, which diminishes the memory consumption.
603
604    However, I very much doubt if we still need this -- Sergey */
605
606 /* A name_list element contains entries of three types: */
607
608 enum nelt_type
609   {
610     NELT_NAME,   /* File name */
611     NELT_CHDIR,  /* Change directory request */
612     NELT_FILE,   /* Read file names from that file */
613     NELT_NOOP,   /* No operation */
614     NELT_OPTION  /* Filename-selection option */
615   };
616
617 struct name_elt        /* A name_array element. */
618 {
619   struct name_elt *next, *prev;
620   enum nelt_type type; /* Element type, see NELT_* constants above */
621   union
622   {
623     const char *name;  /* File or directory name */
624     struct             /* File, if type == NELT_FILE */
625     {
626       const char *name;/* File name */
627       size_t line;     /* Input line number */
628       int term;        /* File name terminator in the list */
629       bool verbatim;   /* Verbatim handling of file names: no white-space
630                           trimming, no option processing */
631       FILE *fp;
632     } file;
633     struct
634     {
635       int option;
636       char const *arg;
637     } opt; /* NELT_OPTION */
638   } v;
639 };
640
641 static struct name_elt *name_head;  /* store a list of names */
642 size_t name_count;                  /* how many of the entries are names? */
643
644 static struct name_elt *
645 name_elt_alloc (void)
646 {
647   struct name_elt *elt;
648
649   elt = xmalloc (sizeof (*elt));
650   if (!name_head)
651     {
652       name_head = elt;
653       name_head->prev = name_head->next = NULL;
654       name_head->type = NELT_NOOP;
655       elt = xmalloc (sizeof (*elt));
656     }
657
658   elt->prev = name_head->prev;
659   if (name_head->prev)
660     name_head->prev->next = elt;
661   elt->next = name_head;
662   name_head->prev = elt;
663   return elt;
664 }
665
666 static void
667 name_list_adjust (void)
668 {
669   if (name_head)
670     while (name_head->prev)
671       name_head = name_head->prev;
672 }
673
674 static void
675 name_list_advance (void)
676 {
677   struct name_elt *elt = name_head;
678   name_head = elt->next;
679   if (name_head)
680     name_head->prev = NULL;
681   free (elt);
682 }
683
684
685 /* Add to name_array the file NAME with fnmatch options MATFLAGS */
686 void
687 name_add_name (const char *name)
688 {
689   struct name_elt *ep = name_elt_alloc ();
690
691   ep->type = NELT_NAME;
692   ep->v.name = name;
693   name_count++;
694 }
695
696 static void
697 name_add_option (int option, const char *arg)
698 {
699   struct name_elt *elt = name_elt_alloc ();
700   elt->type = NELT_OPTION;
701   elt->v.opt.option = option;
702   elt->v.opt.arg = arg;
703 }
704
705 /* Add to name_array a chdir request for the directory NAME */
706 static void
707 name_add_dir (const char *name)
708 {
709   struct name_elt *ep = name_elt_alloc ();
710   ep->type = NELT_CHDIR;
711   ep->v.name = name;
712 }
713
714 static void
715 name_add_file (const char *name)
716 {
717   struct name_elt *ep = name_elt_alloc ();
718
719   ep->type = NELT_FILE;
720   ep->v.file.name = name;
721   ep->v.file.line = 0;
722   ep->v.file.fp = NULL;
723 }
724 \f
725 /* Names from external name file.  */
726
727 static char *name_buffer;       /* buffer to hold the current file name */
728 static size_t name_buffer_length; /* allocated length of name_buffer */
729
730 /* Set up to gather file names for tar.  They can either come from a
731    file or were saved from decoding arguments.  */
732 void
733 name_init (void)
734 {
735   name_buffer = xmalloc (NAME_FIELD_SIZE + 2);
736   name_buffer_length = NAME_FIELD_SIZE;
737   name_list_adjust ();
738 }
739
740 void
741 name_term (void)
742 {
743   free (name_buffer);
744 }
745 \f
746 /* Prevent recursive inclusion of the same file */
747 struct file_id_list
748 {
749   struct file_id_list *next;
750   ino_t ino;
751   dev_t dev;
752   const char *from_file;
753 };
754
755 static struct file_id_list *file_id_list;
756
757 /* Return the name of the file from which the file names and options
758    are being read.
759 */
760 static const char *
761 file_list_name (void)
762 {
763   struct name_elt *elt;
764
765   for (elt = name_head; elt; elt = elt->next)
766     if (elt->type == NELT_FILE && elt->v.file.fp)
767       return elt->v.file.name;
768   return _("command line");
769 }
770
771 static int
772 add_file_id (const char *filename)
773 {
774   struct file_id_list *p;
775   struct stat st;
776   const char *reading_from;
777
778   if (stat (filename, &st))
779     stat_fatal (filename);
780   reading_from = file_list_name ();
781   for (p = file_id_list; p; p = p->next)
782     if (p->ino == st.st_ino && p->dev == st.st_dev)
783       {
784         int oldc = set_char_quoting (NULL, ':', 1);
785         ERROR ((0, 0,
786                 _("%s: file list requested from %s already read from %s"),
787                 quotearg_n (0, filename),
788                 reading_from, p->from_file));
789         set_char_quoting (NULL, ':', oldc);
790         return 1;
791       }
792   p = xmalloc (sizeof *p);
793   p->next = file_id_list;
794   p->ino = st.st_ino;
795   p->dev = st.st_dev;
796   p->from_file = reading_from;
797   file_id_list = p;
798   return 0;
799 }
800
801 /* Chop trailing slashes.  */
802 static void
803 chopslash (char *str)
804 {
805   char *p = str + strlen (str) - 1;
806   while (p > str && ISSLASH (*p))
807     *p-- = '\0';
808 }
809 \f
810 enum read_file_list_state  /* Result of reading file name from the list file */
811   {
812     file_list_success,     /* OK, name read successfully */
813     file_list_end,         /* End of list file */
814     file_list_zero,        /* Zero separator encountered where it should not */
815     file_list_skip         /* Empty (zero-length) entry encountered, skip it */
816   };
817
818 /* Read from FP a sequence of characters up to TERM and put them
819    into STK.
820  */
821 static enum read_file_list_state
822 read_name_from_file (struct name_elt *ent)
823 {
824   int c;
825   size_t counter = 0;
826   FILE *fp = ent->v.file.fp;
827   int term = ent->v.file.term;
828
829   ++ent->v.file.line;
830   for (c = getc (fp); c != EOF && c != term; c = getc (fp))
831     {
832       if (counter == name_buffer_length)
833         name_buffer = x2realloc (name_buffer, &name_buffer_length);
834       name_buffer[counter++] = c;
835       if (c == 0)
836         {
837           /* We have read a zero separator. The file possibly is
838              zero-separated */
839           return file_list_zero;
840         }
841     }
842
843   if (counter == 0 && c != EOF)
844     return file_list_skip;
845
846   if (counter == name_buffer_length)
847     name_buffer = x2realloc (name_buffer, &name_buffer_length);
848   name_buffer[counter] = 0;
849   chopslash (name_buffer);
850   return (counter == 0 && c == EOF) ? file_list_end : file_list_success;
851 }
852
853 static int
854 handle_option (const char *str, struct name_elt const *ent)
855 {
856   struct wordsplit ws;
857   int i;
858   struct option_locus loc;
859   
860   while (*str && isspace (*str))
861     ++str;
862   if (*str != '-')
863     return 1;
864
865   ws.ws_offs = 1;
866   if (wordsplit (str, &ws, WRDSF_DEFFLAGS|WRDSF_DOOFFS))
867     FATAL_ERROR ((0, 0, _("cannot split string '%s': %s"),
868                   str, wordsplit_strerror (&ws)));
869   ws.ws_wordv[0] = (char *) program_name;
870   loc.source = OPTS_FILE;
871   loc.name = ent->v.file.name;
872   loc.line = ent->v.file.line;
873   more_options (ws.ws_wordc+ws.ws_offs, ws.ws_wordv, &loc);
874   for (i = 0; i < ws.ws_wordc+ws.ws_offs; i++)
875     ws.ws_wordv[i] = NULL;
876
877   wordsplit_free (&ws);
878   return 0;
879 }
880
881 static int
882 read_next_name (struct name_elt *ent, struct name_elt *ret)
883 {
884   if (!ent->v.file.fp)
885     {
886       if (!strcmp (ent->v.file.name, "-"))
887         {
888           request_stdin ("-T");
889           ent->v.file.fp = stdin;
890         }
891       else
892         {
893           if (add_file_id (ent->v.file.name))
894             {
895               name_list_advance ();
896               return 1;
897             }
898           if ((ent->v.file.fp = fopen (ent->v.file.name, "r")) == NULL)
899             open_fatal (ent->v.file.name);
900         }
901       ent->v.file.term = filename_terminator;
902       ent->v.file.verbatim = verbatim_files_from_option;
903     }
904
905   while (1)
906     {
907       switch (read_name_from_file (ent))
908         {
909         case file_list_skip:
910           continue;
911
912         case file_list_zero:
913           WARNOPT (WARN_FILENAME_WITH_NULS,
914                    (0, 0, N_("%s: file name read contains nul character"),
915                     quotearg_colon (ent->v.file.name)));
916           ent->v.file.term = 0;
917           /* fall through */
918         case file_list_success:
919           if (unquote_option)
920             unquote_string (name_buffer);
921           if (!ent->v.file.verbatim && handle_option (name_buffer, ent) == 0)
922             {
923               name_list_adjust ();
924               return 1;
925             }
926           ret->type = NELT_NAME;
927           ret->v.name = name_buffer;
928           return 0;
929
930         case file_list_end:
931           if (strcmp (ent->v.file.name, "-"))
932             fclose (ent->v.file.fp);
933           ent->v.file.fp = NULL;
934           name_list_advance ();
935           return 1;
936         }
937     }
938 }
939 \f
940 static void
941 copy_name (struct name_elt *ep)
942 {
943   const char *source;
944   size_t source_len;
945
946   source = ep->v.name;
947   source_len = strlen (source);
948   if (name_buffer_length < source_len)
949     {
950       do
951         {
952           name_buffer_length *= 2;
953           if (! name_buffer_length)
954             xalloc_die ();
955         }
956       while (name_buffer_length < source_len);
957
958       free (name_buffer);
959       name_buffer = xmalloc(name_buffer_length + 2);
960     }
961   strcpy (name_buffer, source);
962   chopslash (name_buffer);
963 }
964
965 \f
966 /* Get the next NELT_NAME element from name_array.  Result is in
967    static storage and can't be relied upon across two calls.
968
969    If CHANGE_DIRS is true, treat any entries of type NELT_CHDIR as
970    the request to change to the given directory.
971
972 */
973 static struct name_elt *
974 name_next_elt (int change_dirs)
975 {
976   static struct name_elt entry;
977   struct name_elt *ep;
978
979   while ((ep = name_head) != NULL)
980     {
981       switch (ep->type)
982         {
983         case NELT_NOOP:
984           name_list_advance ();
985           break;
986
987         case NELT_FILE:
988           if (read_next_name (ep, &entry) == 0)
989             return &entry;
990           continue;
991
992         case NELT_CHDIR:
993           if (change_dirs)
994             {
995               chdir_do (chdir_arg (xstrdup (ep->v.name)));
996               name_list_advance ();
997               break;
998             }
999           /* fall through */
1000         case NELT_NAME:
1001           copy_name (ep);
1002           if (unquote_option)
1003             unquote_string (name_buffer);
1004           entry.type = ep->type;
1005           entry.v.name = name_buffer;
1006           name_list_advance ();
1007           return &entry;
1008
1009         case NELT_OPTION:
1010           handle_file_selection_option (ep->v.opt.option, ep->v.opt.arg);
1011           name_list_advance ();
1012           continue;
1013         }
1014     }
1015
1016   return NULL;
1017 }
1018
1019 const char *
1020 name_next (int change_dirs)
1021 {
1022   struct name_elt *nelt = name_next_elt (change_dirs);
1023   return nelt ? nelt->v.name : NULL;
1024 }
1025
1026 /* Gather names in a list for scanning.  Could hash them later if we
1027    really care.
1028
1029    If the names are already sorted to match the archive, we just read
1030    them one by one.  name_gather reads the first one, and it is called
1031    by name_match as appropriate to read the next ones.  At EOF, the
1032    last name read is just left in the buffer.  This option lets users
1033    of small machines extract an arbitrary number of files by doing
1034    "tar t" and editing down the list of files.  */
1035
1036 void
1037 name_gather (void)
1038 {
1039   /* Buffer able to hold a single name.  */
1040   static struct name *buffer = NULL;
1041
1042   struct name_elt *ep;
1043
1044   if (same_order_option)
1045     {
1046       static int change_dir;
1047
1048       while ((ep = name_next_elt (0)) && ep->type == NELT_CHDIR)
1049         change_dir = chdir_arg (xstrdup (ep->v.name));
1050
1051       if (ep)
1052         {
1053           free_name (buffer);
1054           buffer = make_name (ep->v.name);
1055           buffer->change_dir = change_dir;
1056           buffer->next = 0;
1057           buffer->found_count = 0;
1058           buffer->matching_flags = INCLUDE_OPTIONS;
1059           buffer->directory = NULL;
1060           buffer->parent = NULL;
1061           buffer->cmdline = true;
1062
1063           namelist = nametail = buffer;
1064         }
1065       else if (change_dir)
1066         addname (0, change_dir, false, NULL);
1067     }
1068   else
1069     {
1070       /* Non sorted names -- read them all in.  */
1071       int change_dir = 0;
1072
1073       for (;;)
1074         {
1075           int change_dir0 = change_dir;
1076           while ((ep = name_next_elt (0)) && ep->type == NELT_CHDIR)
1077             change_dir = chdir_arg (xstrdup (ep->v.name));
1078
1079           if (ep)
1080             addname (ep->v.name, change_dir, true, NULL);
1081           else
1082             {
1083               if (change_dir != change_dir0)
1084                 addname (NULL, change_dir, false, NULL);
1085               break;
1086             }
1087         }
1088     }
1089 }
1090
1091 /*  Add a name to the namelist.  */
1092 struct name *
1093 addname (char const *string, int change_dir, bool cmdline, struct name *parent)
1094 {
1095   struct name *name = make_name (string);
1096
1097   name->prev = nametail;
1098   name->next = NULL;
1099   name->found_count = 0;
1100   name->matching_flags = INCLUDE_OPTIONS;
1101   name->change_dir = change_dir;
1102   name->directory = NULL;
1103   name->parent = parent;
1104   name->cmdline = cmdline;
1105
1106   if (nametail)
1107     nametail->next = name;
1108   else
1109     namelist = name;
1110   nametail = name;
1111   return name;
1112 }
1113
1114 /* Find a match for FILE_NAME (whose string length is LENGTH) in the name
1115    list.  */
1116 static struct name *
1117 namelist_match (char const *file_name, size_t length)
1118 {
1119   struct name *p;
1120
1121   for (p = namelist; p; p = p->next)
1122     {
1123       if (p->name[0]
1124           && exclude_fnmatch (p->name, file_name, p->matching_flags))
1125         return p;
1126     }
1127
1128   return NULL;
1129 }
1130
1131 void
1132 remname (struct name *name)
1133 {
1134   struct name *p;
1135
1136   if ((p = name->prev) != NULL)
1137     p->next = name->next;
1138   else
1139     namelist = name->next;
1140
1141   if ((p = name->next) != NULL)
1142     p->prev = name->prev;
1143   else
1144     nametail = name->prev;
1145 }
1146
1147 /* Return true if and only if name FILE_NAME (from an archive) matches any
1148    name from the namelist.  */
1149 bool
1150 name_match (const char *file_name)
1151 {
1152   size_t length = strlen (file_name);
1153
1154   while (1)
1155     {
1156       struct name *cursor = namelist;
1157
1158       if (!cursor)
1159         return true;
1160
1161       if (cursor->name[0] == 0)
1162         {
1163           chdir_do (cursor->change_dir);
1164           namelist = NULL;
1165           nametail = NULL;
1166           return true;
1167         }
1168
1169       cursor = namelist_match (file_name, length);
1170       if (cursor)
1171         {
1172           if (!(ISSLASH (file_name[cursor->length]) && recursion_option)
1173               || cursor->found_count == 0)
1174             cursor->found_count++; /* remember it matched */
1175           if (starting_file_option)
1176             {
1177               free (namelist);
1178               namelist = NULL;
1179               nametail = NULL;
1180             }
1181           chdir_do (cursor->change_dir);
1182
1183           /* We got a match.  */
1184           return ISFOUND (cursor);
1185         }
1186
1187       /* Filename from archive not found in namelist.  If we have the whole
1188          namelist here, just return 0.  Otherwise, read the next name in and
1189          compare it.  If this was the last name, namelist->found_count will
1190          remain on.  If not, we loop to compare the newly read name.  */
1191
1192       if (same_order_option && namelist->found_count)
1193         {
1194           name_gather ();       /* read one more */
1195           if (namelist->found_count)
1196             return false;
1197         }
1198       else
1199         return false;
1200     }
1201 }
1202
1203 /* Returns true if all names from the namelist were processed.
1204    P is the stat_info of the most recently processed entry.
1205    The decision is postponed until the next entry is read if:
1206
1207    1) P ended with a slash (i.e. it was a directory)
1208    2) P matches any entry from the namelist *and* represents a subdirectory
1209    or a file lying under this entry (in the terms of directory structure).
1210
1211    This is necessary to handle contents of directories. */
1212 bool
1213 all_names_found (struct tar_stat_info *p)
1214 {
1215   struct name const *cursor;
1216   size_t len;
1217
1218   if (!p->file_name || occurrence_option == 0 || p->had_trailing_slash)
1219     return false;
1220   len = strlen (p->file_name);
1221   for (cursor = namelist; cursor; cursor = cursor->next)
1222     {
1223       if ((cursor->name[0] && !WASFOUND (cursor))
1224           || (len >= cursor->length && ISSLASH (p->file_name[cursor->length])))
1225         return false;
1226     }
1227   return true;
1228 }
1229
1230 static int
1231 regex_usage_warning (const char *name)
1232 {
1233   static int warned_once = 0;
1234
1235   /* Warn about implicit use of the wildcards in command line arguments.
1236      (Default for tar prior to 1.15.91, but changed afterwards) */
1237   if (wildcards == default_wildcards
1238       && fnmatch_pattern_has_wildcards (name, 0))
1239     {
1240       warned_once = 1;
1241       WARN ((0, 0,
1242              _("Pattern matching characters used in file names")));
1243       WARN ((0, 0,
1244              _("Use --wildcards to enable pattern matching,"
1245                " or --no-wildcards to suppress this warning")));
1246     }
1247   return warned_once;
1248 }
1249
1250 /* Print the names of things in the namelist that were not matched.  */
1251 void
1252 names_notfound (void)
1253 {
1254   struct name const *cursor;
1255
1256   for (cursor = namelist; cursor; cursor = cursor->next)
1257     if (!WASFOUND (cursor) && cursor->name[0])
1258       {
1259         regex_usage_warning (cursor->name);
1260         ERROR ((0, 0,
1261                 (cursor->found_count == 0) ?
1262                      _("%s: Not found in archive") :
1263                      _("%s: Required occurrence not found in archive"),
1264                 quotearg_colon (cursor->name)));
1265       }
1266
1267   /* Don't bother freeing the name list; we're about to exit.  */
1268   namelist = NULL;
1269   nametail = NULL;
1270
1271   if (same_order_option)
1272     {
1273       const char *name;
1274
1275       while ((name = name_next (1)) != NULL)
1276         {
1277           regex_usage_warning (name);
1278           ERROR ((0, 0, _("%s: Not found in archive"),
1279                   quotearg_colon (name)));
1280         }
1281     }
1282 }
1283
1284 void
1285 label_notfound (void)
1286 {
1287   struct name const *cursor;
1288
1289   if (!namelist)
1290     return;
1291
1292   for (cursor = namelist; cursor; cursor = cursor->next)
1293     if (WASFOUND (cursor))
1294       return;
1295
1296   if (verbose_option)
1297     error (0, 0, _("Archive label mismatch"));
1298   set_exit_status (TAREXIT_DIFFERS);
1299
1300   for (cursor = namelist; cursor; cursor = cursor->next)
1301     {
1302       if (regex_usage_warning (cursor->name))
1303         break;
1304     }
1305
1306   /* Don't bother freeing the name list; we're about to exit.  */
1307   namelist = NULL;
1308   nametail = NULL;
1309
1310   if (same_order_option)
1311     {
1312       const char *name;
1313
1314       while ((name = name_next (1)) != NULL
1315              && regex_usage_warning (name) == 0)
1316         ;
1317     }
1318 }
1319 \f
1320 /* Sorting name lists.  */
1321
1322 /* Sort *singly* linked LIST of names, of given LENGTH, using COMPARE
1323    to order names.  Return the sorted list.  Note that after calling
1324    this function, the 'prev' links in list elements are messed up.
1325
1326    Apart from the type 'struct name' and the definition of SUCCESSOR,
1327    this is a generic list-sorting function, but it's too painful to
1328    make it both generic and portable
1329    in C.  */
1330
1331 static struct name *
1332 merge_sort_sll (struct name *list, int length,
1333                 int (*compare) (struct name const*, struct name const*))
1334 {
1335   struct name *first_list;
1336   struct name *second_list;
1337   int first_length;
1338   int second_length;
1339   struct name *result;
1340   struct name **merge_point;
1341   struct name *cursor;
1342   int counter;
1343
1344 # define SUCCESSOR(name) ((name)->next)
1345
1346   if (length == 1)
1347     return list;
1348
1349   if (length == 2)
1350     {
1351       if ((*compare) (list, SUCCESSOR (list)) > 0)
1352         {
1353           result = SUCCESSOR (list);
1354           SUCCESSOR (result) = list;
1355           SUCCESSOR (list) = 0;
1356           return result;
1357         }
1358       return list;
1359     }
1360
1361   first_list = list;
1362   first_length = (length + 1) / 2;
1363   second_length = length / 2;
1364   for (cursor = list, counter = first_length - 1;
1365        counter;
1366        cursor = SUCCESSOR (cursor), counter--)
1367     continue;
1368   second_list = SUCCESSOR (cursor);
1369   SUCCESSOR (cursor) = 0;
1370
1371   first_list = merge_sort_sll (first_list, first_length, compare);
1372   second_list = merge_sort_sll (second_list, second_length, compare);
1373
1374   merge_point = &result;
1375   while (first_list && second_list)
1376     if ((*compare) (first_list, second_list) < 0)
1377       {
1378         cursor = SUCCESSOR (first_list);
1379         *merge_point = first_list;
1380         merge_point = &SUCCESSOR (first_list);
1381         first_list = cursor;
1382       }
1383     else
1384       {
1385         cursor = SUCCESSOR (second_list);
1386         *merge_point = second_list;
1387         merge_point = &SUCCESSOR (second_list);
1388         second_list = cursor;
1389       }
1390   if (first_list)
1391     *merge_point = first_list;
1392   else
1393     *merge_point = second_list;
1394
1395   return result;
1396
1397 #undef SUCCESSOR
1398 }
1399
1400 /* Sort doubly linked LIST of names, of given LENGTH, using COMPARE
1401    to order names.  Return the sorted list.  */
1402 static struct name *
1403 merge_sort (struct name *list, int length,
1404             int (*compare) (struct name const*, struct name const*))
1405 {
1406   struct name *head, *p, *prev;
1407   head = merge_sort_sll (list, length, compare);
1408   /* Fixup prev pointers */
1409   for (prev = NULL, p = head; p; prev = p, p = p->next)
1410     p->prev = prev;
1411   return head;
1412 }
1413
1414 /* A comparison function for sorting names.  Put found names last;
1415    break ties by string comparison.  */
1416
1417 static int
1418 compare_names_found (struct name const *n1, struct name const *n2)
1419 {
1420   int found_diff = WASFOUND (n2) - WASFOUND (n1);
1421   return found_diff ? found_diff : strcmp (n1->name, n2->name);
1422 }
1423
1424 /* Simple comparison by names. */
1425 static int
1426 compare_names (struct name const *n1, struct name const *n2)
1427 {
1428   return strcmp (n1->name, n2->name);
1429 }
1430
1431 \f
1432 /* Add all the dirs under ST to the namelist NAME, descending the
1433    directory hierarchy recursively.  */
1434
1435 static void
1436 add_hierarchy_to_namelist (struct tar_stat_info *st, struct name *name)
1437 {
1438   const char *buffer;
1439
1440   name->directory = scan_directory (st);
1441   buffer = directory_contents (name->directory);
1442   if (buffer)
1443     {
1444       struct name *child_head = NULL, *child_tail = NULL;
1445       size_t name_length = name->length;
1446       size_t allocated_length = (name_length >= NAME_FIELD_SIZE
1447                                  ? name_length + NAME_FIELD_SIZE
1448                                  : NAME_FIELD_SIZE);
1449       char *namebuf = xmalloc (allocated_length + 1);
1450                                 /* FIXME: + 2 above?  */
1451       const char *string;
1452       size_t string_length;
1453       int change_dir = name->change_dir;
1454
1455       strcpy (namebuf, name->name);
1456       if (! ISSLASH (namebuf[name_length - 1]))
1457         {
1458           namebuf[name_length++] = '/';
1459           namebuf[name_length] = '\0';
1460         }
1461
1462       for (string = buffer; *string; string += string_length + 1)
1463         {
1464           string_length = strlen (string);
1465           if (*string == 'D')
1466             {
1467               struct name *np;
1468               struct tar_stat_info subdir;
1469               int subfd;
1470
1471               if (allocated_length <= name_length + string_length)
1472                 {
1473                   do
1474                     {
1475                       allocated_length *= 2;
1476                       if (! allocated_length)
1477                         xalloc_die ();
1478                     }
1479                   while (allocated_length <= name_length + string_length);
1480
1481                   namebuf = xrealloc (namebuf, allocated_length + 1);
1482                 }
1483               strcpy (namebuf + name_length, string + 1);
1484               np = addname (namebuf, change_dir, false, name);
1485               if (!child_head)
1486                 child_head = np;
1487               else
1488                 child_tail->sibling = np;
1489               child_tail = np;
1490
1491               tar_stat_init (&subdir);
1492               subdir.parent = st;
1493               if (st->fd < 0)
1494                 {
1495                   subfd = -1;
1496                   errno = - st->fd;
1497                 }
1498               else
1499                 subfd = subfile_open (st, string + 1,
1500                                       open_read_flags | O_DIRECTORY);
1501               if (subfd < 0)
1502                 open_diag (namebuf);
1503               else
1504                 {
1505                   subdir.fd = subfd;
1506                   if (fstat (subfd, &subdir.stat) != 0)
1507                     stat_diag (namebuf);
1508                   else if (! (O_DIRECTORY || S_ISDIR (subdir.stat.st_mode)))
1509                     {
1510                       errno = ENOTDIR;
1511                       open_diag (namebuf);
1512                     }
1513                   else
1514                     {
1515                       subdir.orig_file_name = xstrdup (namebuf);
1516                       add_hierarchy_to_namelist (&subdir, np);
1517                       restore_parent_fd (&subdir);
1518                     }
1519                 }
1520
1521               tar_stat_destroy (&subdir);
1522             }
1523         }
1524
1525       free (namebuf);
1526       name->child = child_head;
1527     }
1528 }
1529 \f
1530 /* Auxiliary functions for hashed table of struct name's. */
1531
1532 static size_t
1533 name_hash (void const *entry, size_t n_buckets)
1534 {
1535   struct name const *name = entry;
1536   return hash_string (name->caname, n_buckets);
1537 }
1538
1539 /* Compare two directories for equality of their names. */
1540 static bool
1541 name_compare (void const *entry1, void const *entry2)
1542 {
1543   struct name const *name1 = entry1;
1544   struct name const *name2 = entry2;
1545   return strcmp (name1->caname, name2->caname) == 0;
1546 }
1547
1548 \f
1549 /* Rebase 'name' member of CHILD and all its siblings to
1550    the new PARENT. */
1551 static void
1552 rebase_child_list (struct name *child, struct name *parent)
1553 {
1554   size_t old_prefix_len = child->parent->length;
1555   size_t new_prefix_len = parent->length;
1556   char *new_prefix = parent->name;
1557
1558   for (; child; child = child->sibling)
1559     {
1560       size_t size = child->length - old_prefix_len + new_prefix_len;
1561       char *newp = xmalloc (size + 1);
1562       strcpy (newp, new_prefix);
1563       strcat (newp, child->name + old_prefix_len);
1564       free (child->name);
1565       child->name = newp;
1566       child->length = size;
1567
1568       rebase_directory (child->directory,
1569                         child->parent->name, old_prefix_len,
1570                         new_prefix, new_prefix_len);
1571     }
1572 }
1573
1574 /* Collect all the names from argv[] (or whatever), expand them into a
1575    directory tree, and sort them.  This gets only subdirectories, not
1576    all files.  */
1577
1578 void
1579 collect_and_sort_names (void)
1580 {
1581   struct name *name;
1582   struct name *next_name, *prev_name = NULL;
1583   int num_names;
1584   Hash_table *nametab;
1585
1586   name_gather ();
1587
1588   if (!namelist)
1589     addname (".", 0, false, NULL);
1590
1591   if (listed_incremental_option)
1592     {
1593       switch (chdir_count ())
1594         {
1595         case 0:
1596           break;
1597
1598         case 1:
1599           if (namelist->change_dir == 0)
1600             USAGE_ERROR ((0, 0,
1601                           _("Using -C option inside file list is not "
1602                             "allowed with --listed-incremental")));
1603           break;
1604
1605         default:
1606           USAGE_ERROR ((0, 0,
1607                         _("Only one -C option is allowed with "
1608                           "--listed-incremental")));
1609         }
1610
1611       read_directory_file ();
1612     }
1613
1614   num_names = 0;
1615   for (name = namelist; name; name = name->next, num_names++)
1616     {
1617       struct tar_stat_info st;
1618
1619       if (name->found_count || name->directory)
1620         continue;
1621       if (name->matching_flags & EXCLUDE_WILDCARDS)
1622         /* NOTE: EXCLUDE_ANCHORED is not relevant here */
1623         /* FIXME: just skip regexps for now */
1624         continue;
1625       chdir_do (name->change_dir);
1626
1627       if (name->name[0] == 0)
1628         continue;
1629
1630       tar_stat_init (&st);
1631
1632       if (deref_stat (name->name, &st.stat) != 0)
1633         {
1634           stat_diag (name->name);
1635           continue;
1636         }
1637       if (S_ISDIR (st.stat.st_mode))
1638         {
1639           int dir_fd = openat (chdir_fd, name->name,
1640                                open_read_flags | O_DIRECTORY);
1641           if (dir_fd < 0)
1642             open_diag (name->name);
1643           else
1644             {
1645               st.fd = dir_fd;
1646               if (fstat (dir_fd, &st.stat) != 0)
1647                 stat_diag (name->name);
1648               else if (O_DIRECTORY || S_ISDIR (st.stat.st_mode))
1649                 {
1650                   st.orig_file_name = xstrdup (name->name);
1651                   name->found_count++;
1652                   add_hierarchy_to_namelist (&st, name);
1653                 }
1654             }
1655         }
1656
1657       tar_stat_destroy (&st);
1658     }
1659
1660   namelist = merge_sort (namelist, num_names, compare_names);
1661
1662   num_names = 0;
1663   nametab = hash_initialize (0, 0, name_hash, name_compare, NULL);
1664   for (name = namelist; name; name = next_name)
1665     {
1666       next_name = name->next;
1667       name->caname = normalize_filename (name->change_dir, name->name);
1668       if (prev_name)
1669         {
1670           struct name *p = hash_lookup (nametab, name);
1671           if (p)
1672             {
1673               /* Keep the one listed in the command line */
1674               if (!name->parent)
1675                 {
1676                   if (p->child)
1677                     rebase_child_list (p->child, name);
1678                   hash_delete (nametab, name);
1679                   /* FIXME: remove_directory (p->caname); ? */
1680                   remname (p);
1681                   free_name (p);
1682                   num_names--;
1683                 }
1684               else
1685                 {
1686                   if (name->child)
1687                     rebase_child_list (name->child, p);
1688                   /* FIXME: remove_directory (name->caname); ? */
1689                   remname (name);
1690                   free_name (name);
1691                   continue;
1692                 }
1693             }
1694         }
1695       name->found_count = 0;
1696       if (!hash_insert (nametab, name))
1697         xalloc_die ();
1698       prev_name = name;
1699       num_names++;
1700     }
1701   nametail = prev_name;
1702   hash_free (nametab);
1703
1704   namelist = merge_sort (namelist, num_names, compare_names_found);
1705
1706   if (listed_incremental_option)
1707     {
1708       for (name = namelist; name && name->name[0] == 0; name++)
1709         ;
1710       if (name)
1711         append_incremental_renames (name->directory);
1712     }
1713 }
1714
1715 /* This is like name_match, except that
1716     1. It returns a pointer to the name it matched, and doesn't set FOUND
1717     in structure. The caller will have to do that if it wants to.
1718     2. If the namelist is empty, it returns null, unlike name_match, which
1719     returns TRUE. */
1720 struct name *
1721 name_scan (const char *file_name)
1722 {
1723   size_t length = strlen (file_name);
1724
1725   while (1)
1726     {
1727       struct name *cursor = namelist_match (file_name, length);
1728       if (cursor)
1729         return cursor;
1730
1731       /* Filename from archive not found in namelist.  If we have the whole
1732          namelist here, just return 0.  Otherwise, read the next name in and
1733          compare it.  If this was the last name, namelist->found_count will
1734          remain on.  If not, we loop to compare the newly read name.  */
1735
1736       if (same_order_option && namelist && namelist->found_count)
1737         {
1738           name_gather ();       /* read one more */
1739           if (namelist->found_count)
1740             return 0;
1741         }
1742       else
1743         return 0;
1744     }
1745 }
1746
1747 /* This returns a name from the namelist which doesn't have ->found
1748    set.  It sets ->found before returning, so successive calls will
1749    find and return all the non-found names in the namelist.  */
1750 struct name *gnu_list_name;
1751
1752 struct name const *
1753 name_from_list (void)
1754 {
1755   if (!gnu_list_name)
1756     gnu_list_name = namelist;
1757   while (gnu_list_name
1758          && (gnu_list_name->found_count || gnu_list_name->name[0] == 0))
1759     gnu_list_name = gnu_list_name->next;
1760   if (gnu_list_name)
1761     {
1762       gnu_list_name->found_count++;
1763       chdir_do (gnu_list_name->change_dir);
1764       return gnu_list_name;
1765     }
1766   return NULL;
1767 }
1768
1769 void
1770 blank_name_list (void)
1771 {
1772   struct name *name;
1773
1774   gnu_list_name = 0;
1775   for (name = namelist; name; name = name->next)
1776     name->found_count = 0;
1777 }
1778
1779 /* Yield a newly allocated file name consisting of DIR_NAME concatenated to
1780    NAME, with an intervening slash if DIR_NAME does not already end in one. */
1781 char *
1782 make_file_name (const char *directory_name, const char *name)
1783 {
1784   size_t dirlen = strlen (directory_name);
1785   size_t namelen = strlen (name) + 1;
1786   int slash = dirlen && ! ISSLASH (directory_name[dirlen - 1]);
1787   char *buffer = xmalloc (dirlen + slash + namelen);
1788   memcpy (buffer, directory_name, dirlen);
1789   buffer[dirlen] = '/';
1790   memcpy (buffer + dirlen + slash, name, namelen);
1791   return buffer;
1792 }
1793
1794 \f
1795
1796 /* Return the size of the prefix of FILE_NAME that is removed after
1797    stripping NUM leading file name components.  NUM must be
1798    positive.  */
1799
1800 size_t
1801 stripped_prefix_len (char const *file_name, size_t num)
1802 {
1803   char const *p = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
1804   while (ISSLASH (*p))
1805     p++;
1806   while (*p)
1807     {
1808       bool slash = ISSLASH (*p);
1809       p++;
1810       if (slash)
1811         {
1812           if (--num == 0)
1813             return p - file_name;
1814           while (ISSLASH (*p))
1815             p++;
1816         }
1817     }
1818   return -1;
1819 }
1820 \f
1821 /* Return nonzero if NAME contains ".." as a file name component.  */
1822 bool
1823 contains_dot_dot (char const *name)
1824 {
1825   char const *p = name + FILE_SYSTEM_PREFIX_LEN (name);
1826
1827   for (;; p++)
1828     {
1829       if (p[0] == '.' && p[1] == '.' && (ISSLASH (p[2]) || !p[2]))
1830         return 1;
1831
1832       while (! ISSLASH (*p))
1833         {
1834           if (! *p++)
1835             return 0;
1836         }
1837     }
1838 }