Import upstream version 1.27
[debian/tar] / src / names.c
1 /* Various processing of names.
2
3    Copyright 1988, 1992, 1994, 1996-2001, 2003-2007, 2009, 2013 Free
4    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 /* User and group names.  */
30
31 /* Make sure you link with the proper libraries if you are running the
32    Yellow Peril (thanks for the good laugh, Ian J.!), or, euh... NIS.
33    This code should also be modified for non-UNIX systems to do something
34    reasonable.  */
35
36 static char *cached_uname;
37 static char *cached_gname;
38
39 static uid_t cached_uid;        /* valid only if cached_uname is not empty */
40 static gid_t cached_gid;        /* valid only if cached_gname is not empty */
41
42 /* These variables are valid only if nonempty.  */
43 static char *cached_no_such_uname;
44 static char *cached_no_such_gname;
45
46 /* These variables are valid only if nonzero.  It's not worth optimizing
47    the case for weird systems where 0 is not a valid uid or gid.  */
48 static uid_t cached_no_such_uid;
49 static gid_t cached_no_such_gid;
50
51 /* Given UID, find the corresponding UNAME.  */
52 void
53 uid_to_uname (uid_t uid, char **uname)
54 {
55   struct passwd *passwd;
56
57   if (uid != 0 && uid == cached_no_such_uid)
58     {
59       *uname = xstrdup ("");
60       return;
61     }
62
63   if (!cached_uname || uid != cached_uid)
64     {
65       passwd = getpwuid (uid);
66       if (passwd)
67         {
68           cached_uid = uid;
69           assign_string (&cached_uname, passwd->pw_name);
70         }
71       else
72         {
73           cached_no_such_uid = uid;
74           *uname = xstrdup ("");
75           return;
76         }
77     }
78   *uname = xstrdup (cached_uname);
79 }
80
81 /* Given GID, find the corresponding GNAME.  */
82 void
83 gid_to_gname (gid_t gid, char **gname)
84 {
85   struct group *group;
86
87   if (gid != 0 && gid == cached_no_such_gid)
88     {
89       *gname = xstrdup ("");
90       return;
91     }
92
93   if (!cached_gname || gid != cached_gid)
94     {
95       group = getgrgid (gid);
96       if (group)
97         {
98           cached_gid = gid;
99           assign_string (&cached_gname, group->gr_name);
100         }
101       else
102         {
103           cached_no_such_gid = gid;
104           *gname = xstrdup ("");
105           return;
106         }
107     }
108   *gname = xstrdup (cached_gname);
109 }
110
111 /* Given UNAME, set the corresponding UID and return 1, or else, return 0.  */
112 int
113 uname_to_uid (char const *uname, uid_t *uidp)
114 {
115   struct passwd *passwd;
116
117   if (cached_no_such_uname
118       && strcmp (uname, cached_no_such_uname) == 0)
119     return 0;
120
121   if (!cached_uname
122       || uname[0] != cached_uname[0]
123       || strcmp (uname, cached_uname) != 0)
124     {
125       passwd = getpwnam (uname);
126       if (passwd)
127         {
128           cached_uid = passwd->pw_uid;
129           assign_string (&cached_uname, passwd->pw_name);
130         }
131       else
132         {
133           assign_string (&cached_no_such_uname, uname);
134           return 0;
135         }
136     }
137   *uidp = cached_uid;
138   return 1;
139 }
140
141 /* Given GNAME, set the corresponding GID and return 1, or else, return 0.  */
142 int
143 gname_to_gid (char const *gname, gid_t *gidp)
144 {
145   struct group *group;
146
147   if (cached_no_such_gname
148       && strcmp (gname, cached_no_such_gname) == 0)
149     return 0;
150
151   if (!cached_gname
152       || gname[0] != cached_gname[0]
153       || strcmp (gname, cached_gname) != 0)
154     {
155       group = getgrnam (gname);
156       if (group)
157         {
158           cached_gid = group->gr_gid;
159           assign_string (&cached_gname, gname);
160         }
161       else
162         {
163           assign_string (&cached_no_such_gname, gname);
164           return 0;
165         }
166     }
167   *gidp = cached_gid;
168   return 1;
169 }
170
171 \f
172 static struct name *
173 make_name (const char *file_name)
174 {
175   struct name *p = xzalloc (sizeof (*p));
176   if (!file_name)
177     file_name = "";
178   p->name = xstrdup (file_name);
179   p->length = strlen (p->name);
180   return p;
181 }
182
183 static void
184 free_name (struct name *p)
185 {
186   if (p)
187     {
188       free (p->name);
189       free (p->caname);
190       free (p);
191     }
192 }
193
194 \f
195 /* Names from the command call.  */
196
197 static struct name *namelist;   /* first name in list, if any */
198 static struct name *nametail;   /* end of name list */
199
200 /* File name arguments are processed in two stages: first a
201    name element list (see below) is filled, then the names from it
202    are moved into the namelist.
203
204    This awkward process is needed only to implement --same-order option,
205    which is meant to help process large archives on machines with
206    limited memory.  With this option on, namelist contains at most one
207    entry, which diminishes the memory consumption.
208
209    However, I very much doubt if we still need this -- Sergey */
210
211 /* A name_list element contains entries of three types: */
212
213 #define NELT_NAME  0   /* File name */
214 #define NELT_CHDIR 1   /* Change directory request */
215 #define NELT_FMASK 2   /* Change fnmatch options request */
216 #define NELT_FILE  3   /* Read file names from that file */
217 #define NELT_NOOP  4   /* No operation */
218
219 struct name_elt        /* A name_array element. */
220 {
221   struct name_elt *next, *prev;
222   char type;           /* Element type, see NELT_* constants above */
223   union
224   {
225     const char *name;  /* File or directory name */
226     int matching_flags;/* fnmatch options if type == NELT_FMASK */
227     struct             /* File, if type == NELT_FILE */
228     {
229       const char *name;/* File name */
230       int term;        /* File name terminator in the list */
231       FILE *fp;
232     } file;
233   } v;
234 };
235
236 static struct name_elt *name_head;  /* store a list of names */
237 size_t name_count;                  /* how many of the entries are names? */
238
239 static struct name_elt *
240 name_elt_alloc (void)
241 {
242   struct name_elt *elt;
243
244   elt = xmalloc (sizeof (*elt));
245   if (!name_head)
246     {
247       name_head = elt;
248       name_head->prev = name_head->next = NULL;
249       name_head->type = NELT_NOOP;
250       elt = xmalloc (sizeof (*elt));
251     }
252
253   elt->prev = name_head->prev;
254   if (name_head->prev)
255     name_head->prev->next = elt;
256   elt->next = name_head;
257   name_head->prev = elt;
258   return elt;
259 }
260
261 static void
262 name_list_adjust (void)
263 {
264   if (name_head)
265     while (name_head->prev)
266       name_head = name_head->prev;
267 }
268
269 static void
270 name_list_advance (void)
271 {
272   struct name_elt *elt = name_head;
273   name_head = elt->next;
274   if (name_head)
275     name_head->prev = NULL;
276   free (elt);
277 }
278
279 /* Add to name_array the file NAME with fnmatch options MATCHING_FLAGS */
280 void
281 name_add_name (const char *name, int matching_flags)
282 {
283   static int prev_flags = 0; /* FIXME: Or EXCLUDE_ANCHORED? */
284   struct name_elt *ep = name_elt_alloc ();
285
286   if (prev_flags != matching_flags)
287     {
288       ep->type = NELT_FMASK;
289       ep->v.matching_flags = matching_flags;
290       prev_flags = matching_flags;
291       ep = name_elt_alloc ();
292     }
293   ep->type = NELT_NAME;
294   ep->v.name = name;
295   name_count++;
296 }
297
298 /* Add to name_array a chdir request for the directory NAME */
299 void
300 name_add_dir (const char *name)
301 {
302   struct name_elt *ep = name_elt_alloc ();
303   ep->type = NELT_CHDIR;
304   ep->v.name = name;
305 }
306
307 void
308 name_add_file (const char *name, int term)
309 {
310   struct name_elt *ep = name_elt_alloc ();
311   ep->type = NELT_FILE;
312   ep->v.file.name = name;
313   ep->v.file.term = term;
314   ep->v.file.fp = NULL;
315 }
316 \f
317 /* Names from external name file.  */
318
319 static char *name_buffer;       /* buffer to hold the current file name */
320 static size_t name_buffer_length; /* allocated length of name_buffer */
321
322 /* Set up to gather file names for tar.  They can either come from a
323    file or were saved from decoding arguments.  */
324 void
325 name_init (void)
326 {
327   name_buffer = xmalloc (NAME_FIELD_SIZE + 2);
328   name_buffer_length = NAME_FIELD_SIZE;
329   name_list_adjust ();
330 }
331
332 void
333 name_term (void)
334 {
335   free (name_buffer);
336 }
337 \f
338 /* Prevent recursive inclusion of the same file */
339 struct file_id_list
340 {
341   struct file_id_list *next;
342   ino_t ino;
343   dev_t dev;
344   const char *from_file;
345 };
346
347 static struct file_id_list *file_id_list;
348
349 /* Return the name of the file from which the file names and options
350    are being read.
351 */
352 static const char *
353 file_list_name (void)
354 {
355   struct name_elt *elt;
356
357   for (elt = name_head; elt; elt = elt->next)
358     if (elt->type == NELT_FILE && elt->v.file.fp)
359       return elt->v.file.name;
360   return _("command line");
361 }
362
363 static int
364 add_file_id (const char *filename)
365 {
366   struct file_id_list *p;
367   struct stat st;
368   const char *reading_from;
369
370   if (stat (filename, &st))
371     stat_fatal (filename);
372   reading_from = file_list_name ();
373   for (p = file_id_list; p; p = p->next)
374     if (p->ino == st.st_ino && p->dev == st.st_dev)
375       {
376         int oldc = set_char_quoting (NULL, ':', 1);
377         ERROR ((0, 0,
378                 _("%s: file list requested from %s already read from %s"),
379                 quotearg_n (0, filename),
380                 reading_from, p->from_file));
381         set_char_quoting (NULL, ':', oldc);
382         return 1;
383       }
384   p = xmalloc (sizeof *p);
385   p->next = file_id_list;
386   p->ino = st.st_ino;
387   p->dev = st.st_dev;
388   p->from_file = reading_from;
389   file_id_list = p;
390   return 0;
391 }
392 \f
393 enum read_file_list_state  /* Result of reading file name from the list file */
394   {
395     file_list_success,     /* OK, name read successfully */
396     file_list_end,         /* End of list file */
397     file_list_zero,        /* Zero separator encountered where it should not */
398     file_list_skip         /* Empty (zero-length) entry encountered, skip it */
399   };
400
401 /* Read from FP a sequence of characters up to TERM and put them
402    into STK.
403  */
404 static enum read_file_list_state
405 read_name_from_file (struct name_elt *ent)
406 {
407   int c;
408   size_t counter = 0;
409   FILE *fp = ent->v.file.fp;
410   int term = ent->v.file.term;
411
412   for (c = getc (fp); c != EOF && c != term; c = getc (fp))
413     {
414       if (counter == name_buffer_length)
415         name_buffer = x2realloc (name_buffer, &name_buffer_length);
416       name_buffer[counter++] = c;
417       if (c == 0)
418         {
419           /* We have read a zero separator. The file possibly is
420              zero-separated */
421           return file_list_zero;
422         }
423     }
424
425   if (counter == 0 && c != EOF)
426     return file_list_skip;
427
428   if (counter == name_buffer_length)
429     name_buffer = x2realloc (name_buffer, &name_buffer_length);
430   name_buffer[counter] = 0;
431
432   return (counter == 0 && c == EOF) ? file_list_end : file_list_success;
433 }
434
435 static int
436 handle_option (const char *str)
437 {
438   struct wordsplit ws;
439   int i;
440
441   while (*str && isspace (*str))
442     ;
443   if (*str != '-')
444     return 1;
445
446   ws.ws_offs = 1;
447   if (wordsplit (str, &ws, WRDSF_DEFFLAGS|WRDSF_DOOFFS))
448     FATAL_ERROR ((0, 0, _("cannot split string '%s': %s"),
449                   str, wordsplit_strerror (&ws)));
450   ws.ws_wordv[0] = program_invocation_short_name;
451   more_options (ws.ws_wordc+ws.ws_offs, ws.ws_wordv);
452   for (i = 0; i < ws.ws_wordc+ws.ws_offs; i++)
453     ws.ws_wordv[i] = NULL;
454
455   wordsplit_free (&ws);
456   return 0;
457 }
458
459 static int
460 read_next_name (struct name_elt *ent, struct name_elt *ret)
461 {
462   if (!ent->v.file.fp)
463     {
464       if (!strcmp (ent->v.file.name, "-"))
465         {
466           request_stdin ("-T");
467           ent->v.file.fp = stdin;
468         }
469       else
470         {
471           if (add_file_id (ent->v.file.name))
472             {
473               name_list_advance ();
474               return 1;
475             }
476           if ((ent->v.file.fp = fopen (ent->v.file.name, "r")) == NULL)
477             open_fatal (ent->v.file.name);
478         }
479     }
480
481   while (1)
482     {
483       switch (read_name_from_file (ent))
484         {
485         case file_list_skip:
486           continue;
487
488         case file_list_zero:
489           WARNOPT (WARN_FILENAME_WITH_NULS,
490                    (0, 0, N_("%s: file name read contains nul character"),
491                     quotearg_colon (ent->v.file.name)));
492           ent->v.file.term = 0;
493           /* fall through */
494         case file_list_success:
495           if (handle_option (name_buffer) == 0)
496             {
497               name_list_adjust ();
498               return 1;
499             }
500           ret->type = NELT_NAME;
501           ret->v.name = name_buffer;
502           return 0;
503
504         case file_list_end:
505           if (strcmp (ent->v.file.name, "-"))
506             fclose (ent->v.file.fp);
507           ent->v.file.fp = NULL;
508           name_list_advance ();
509           return 1;
510         }
511     }
512 }
513 \f
514 static void
515 copy_name (struct name_elt *ep)
516 {
517   const char *source;
518   size_t source_len;
519   char *cursor;
520
521   source = ep->v.name;
522   source_len = strlen (source);
523   if (name_buffer_length < source_len)
524     {
525       do
526         {
527           name_buffer_length *= 2;
528           if (! name_buffer_length)
529             xalloc_die ();
530         }
531       while (name_buffer_length < source_len);
532
533       free (name_buffer);
534       name_buffer = xmalloc(name_buffer_length + 2);
535     }
536   strcpy (name_buffer, source);
537
538   /* Zap trailing slashes.  */
539   cursor = name_buffer + strlen (name_buffer) - 1;
540   while (cursor > name_buffer && ISSLASH (*cursor))
541     *cursor-- = '\0';
542 }
543
544 \f
545 static int matching_flags; /* exclude_fnmatch options */
546
547 /* Get the next NELT_NAME element from name_array.  Result is in
548    static storage and can't be relied upon across two calls.
549
550    If CHANGE_DIRS is true, treat any entries of type NELT_CHDIR as
551    the request to change to the given directory.
552
553    Entries of type NELT_FMASK cause updates of the matching_flags
554    value. */
555 static struct name_elt *
556 name_next_elt (int change_dirs)
557 {
558   static struct name_elt entry;
559   struct name_elt *ep;
560
561   while ((ep = name_head) != NULL)
562     {
563       switch (ep->type)
564         {
565         case NELT_NOOP:
566           name_list_advance ();
567           break;
568
569         case NELT_FMASK:
570           matching_flags = ep->v.matching_flags;
571           name_list_advance ();
572           continue;
573
574         case NELT_FILE:
575           if (read_next_name (ep, &entry) == 0)
576             return &entry;
577           continue;
578
579         case NELT_CHDIR:
580           if (change_dirs)
581             {
582               chdir_do (chdir_arg (xstrdup (ep->v.name)));
583               name_list_advance ();
584               break;
585             }
586           /* fall through */
587         case NELT_NAME:
588           copy_name (ep);
589           if (unquote_option)
590             unquote_string (name_buffer);
591           entry.type = ep->type;
592           entry.v.name = name_buffer;
593           name_list_advance ();
594           return &entry;
595         }
596     }
597
598   return NULL;
599 }
600
601 const char *
602 name_next (int change_dirs)
603 {
604   struct name_elt *nelt = name_next_elt (change_dirs);
605   return nelt ? nelt->v.name : NULL;
606 }
607
608 /* Gather names in a list for scanning.  Could hash them later if we
609    really care.
610
611    If the names are already sorted to match the archive, we just read
612    them one by one.  name_gather reads the first one, and it is called
613    by name_match as appropriate to read the next ones.  At EOF, the
614    last name read is just left in the buffer.  This option lets users
615    of small machines extract an arbitrary number of files by doing
616    "tar t" and editing down the list of files.  */
617
618 void
619 name_gather (void)
620 {
621   /* Buffer able to hold a single name.  */
622   static struct name *buffer = NULL;
623
624   struct name_elt *ep;
625
626   if (same_order_option)
627     {
628       static int change_dir;
629
630       while ((ep = name_next_elt (0)) && ep->type == NELT_CHDIR)
631         change_dir = chdir_arg (xstrdup (ep->v.name));
632
633       if (ep)
634         {
635           free_name (buffer);
636           buffer = make_name (ep->v.name);
637           buffer->change_dir = change_dir;
638           buffer->next = 0;
639           buffer->found_count = 0;
640           buffer->matching_flags = matching_flags;
641           buffer->directory = NULL;
642           buffer->parent = NULL;
643           buffer->cmdline = true;
644
645           namelist = nametail = buffer;
646         }
647       else if (change_dir)
648         addname (0, change_dir, false, NULL);
649     }
650   else
651     {
652       /* Non sorted names -- read them all in.  */
653       int change_dir = 0;
654
655       for (;;)
656         {
657           int change_dir0 = change_dir;
658           while ((ep = name_next_elt (0)) && ep->type == NELT_CHDIR)
659             change_dir = chdir_arg (xstrdup (ep->v.name));
660
661           if (ep)
662             addname (ep->v.name, change_dir, true, NULL);
663           else
664             {
665               if (change_dir != change_dir0)
666                 addname (NULL, change_dir, false, NULL);
667               break;
668             }
669         }
670     }
671 }
672
673 /*  Add a name to the namelist.  */
674 struct name *
675 addname (char const *string, int change_dir, bool cmdline, struct name *parent)
676 {
677   struct name *name = make_name (string);
678
679   name->prev = nametail;
680   name->next = NULL;
681   name->found_count = 0;
682   name->matching_flags = matching_flags;
683   name->change_dir = change_dir;
684   name->directory = NULL;
685   name->parent = parent;
686   name->cmdline = cmdline;
687
688   if (nametail)
689     nametail->next = name;
690   else
691     namelist = name;
692   nametail = name;
693   return name;
694 }
695
696 /* Find a match for FILE_NAME (whose string length is LENGTH) in the name
697    list.  */
698 static struct name *
699 namelist_match (char const *file_name, size_t length)
700 {
701   struct name *p;
702
703   for (p = namelist; p; p = p->next)
704     {
705       if (p->name[0]
706           && exclude_fnmatch (p->name, file_name, p->matching_flags))
707         return p;
708     }
709
710   return NULL;
711 }
712
713 void
714 remname (struct name *name)
715 {
716   struct name *p;
717
718   if ((p = name->prev) != NULL)
719     p->next = name->next;
720   else
721     namelist = name->next;
722
723   if ((p = name->next) != NULL)
724     p->prev = name->prev;
725   else
726     nametail = name->prev;
727 }
728
729 /* Return true if and only if name FILE_NAME (from an archive) matches any
730    name from the namelist.  */
731 bool
732 name_match (const char *file_name)
733 {
734   size_t length = strlen (file_name);
735
736   while (1)
737     {
738       struct name *cursor = namelist;
739
740       if (!cursor)
741         return true;
742
743       if (cursor->name[0] == 0)
744         {
745           chdir_do (cursor->change_dir);
746           namelist = NULL;
747           nametail = NULL;
748           return true;
749         }
750
751       cursor = namelist_match (file_name, length);
752       if (cursor)
753         {
754           if (!(ISSLASH (file_name[cursor->length]) && recursion_option)
755               || cursor->found_count == 0)
756             cursor->found_count++; /* remember it matched */
757           if (starting_file_option)
758             {
759               free (namelist);
760               namelist = NULL;
761               nametail = NULL;
762             }
763           chdir_do (cursor->change_dir);
764
765           /* We got a match.  */
766           return ISFOUND (cursor);
767         }
768
769       /* Filename from archive not found in namelist.  If we have the whole
770          namelist here, just return 0.  Otherwise, read the next name in and
771          compare it.  If this was the last name, namelist->found_count will
772          remain on.  If not, we loop to compare the newly read name.  */
773
774       if (same_order_option && namelist->found_count)
775         {
776           name_gather ();       /* read one more */
777           if (namelist->found_count)
778             return false;
779         }
780       else
781         return false;
782     }
783 }
784
785 /* Returns true if all names from the namelist were processed.
786    P is the stat_info of the most recently processed entry.
787    The decision is postponed until the next entry is read if:
788
789    1) P ended with a slash (i.e. it was a directory)
790    2) P matches any entry from the namelist *and* represents a subdirectory
791    or a file lying under this entry (in the terms of directory structure).
792
793    This is necessary to handle contents of directories. */
794 bool
795 all_names_found (struct tar_stat_info *p)
796 {
797   struct name const *cursor;
798   size_t len;
799
800   if (!p->file_name || occurrence_option == 0 || p->had_trailing_slash)
801     return false;
802   len = strlen (p->file_name);
803   for (cursor = namelist; cursor; cursor = cursor->next)
804     {
805       if ((cursor->name[0] && !WASFOUND (cursor))
806           || (len >= cursor->length && ISSLASH (p->file_name[cursor->length])))
807         return false;
808     }
809   return true;
810 }
811
812 static int
813 regex_usage_warning (const char *name)
814 {
815   static int warned_once = 0;
816
817   if (warn_regex_usage && fnmatch_pattern_has_wildcards (name, 0))
818     {
819       warned_once = 1;
820       WARN ((0, 0,
821              _("Pattern matching characters used in file names")));
822       WARN ((0, 0,
823              _("Use --wildcards to enable pattern matching,"
824                " or --no-wildcards to suppress this warning")));
825     }
826   return warned_once;
827 }
828
829 /* Print the names of things in the namelist that were not matched.  */
830 void
831 names_notfound (void)
832 {
833   struct name const *cursor;
834
835   for (cursor = namelist; cursor; cursor = cursor->next)
836     if (!WASFOUND (cursor) && cursor->name[0])
837       {
838         regex_usage_warning (cursor->name);
839         ERROR ((0, 0,
840                 (cursor->found_count == 0) ?
841                      _("%s: Not found in archive") :
842                      _("%s: Required occurrence not found in archive"),
843                 quotearg_colon (cursor->name)));
844       }
845
846   /* Don't bother freeing the name list; we're about to exit.  */
847   namelist = NULL;
848   nametail = NULL;
849
850   if (same_order_option)
851     {
852       const char *name;
853
854       while ((name = name_next (1)) != NULL)
855         {
856           regex_usage_warning (name);
857           ERROR ((0, 0, _("%s: Not found in archive"),
858                   quotearg_colon (name)));
859         }
860     }
861 }
862
863 void
864 label_notfound (void)
865 {
866   struct name const *cursor;
867
868   if (!namelist)
869     return;
870
871   for (cursor = namelist; cursor; cursor = cursor->next)
872     if (WASFOUND (cursor))
873       return;
874
875   if (verbose_option)
876     error (0, 0, _("Archive label mismatch"));
877   set_exit_status (TAREXIT_DIFFERS);
878
879   for (cursor = namelist; cursor; cursor = cursor->next)
880     {
881       if (regex_usage_warning (cursor->name))
882         break;
883     }
884
885   /* Don't bother freeing the name list; we're about to exit.  */
886   namelist = NULL;
887   nametail = NULL;
888
889   if (same_order_option)
890     {
891       const char *name;
892
893       while ((name = name_next (1)) != NULL
894              && regex_usage_warning (name) == 0)
895         ;
896     }
897 }
898 \f
899 /* Sorting name lists.  */
900
901 /* Sort *singly* linked LIST of names, of given LENGTH, using COMPARE
902    to order names.  Return the sorted list.  Note that after calling
903    this function, the 'prev' links in list elements are messed up.
904
905    Apart from the type 'struct name' and the definition of SUCCESSOR,
906    this is a generic list-sorting function, but it's too painful to
907    make it both generic and portable
908    in C.  */
909
910 static struct name *
911 merge_sort_sll (struct name *list, int length,
912                 int (*compare) (struct name const*, struct name const*))
913 {
914   struct name *first_list;
915   struct name *second_list;
916   int first_length;
917   int second_length;
918   struct name *result;
919   struct name **merge_point;
920   struct name *cursor;
921   int counter;
922
923 # define SUCCESSOR(name) ((name)->next)
924
925   if (length == 1)
926     return list;
927
928   if (length == 2)
929     {
930       if ((*compare) (list, SUCCESSOR (list)) > 0)
931         {
932           result = SUCCESSOR (list);
933           SUCCESSOR (result) = list;
934           SUCCESSOR (list) = 0;
935           return result;
936         }
937       return list;
938     }
939
940   first_list = list;
941   first_length = (length + 1) / 2;
942   second_length = length / 2;
943   for (cursor = list, counter = first_length - 1;
944        counter;
945        cursor = SUCCESSOR (cursor), counter--)
946     continue;
947   second_list = SUCCESSOR (cursor);
948   SUCCESSOR (cursor) = 0;
949
950   first_list = merge_sort_sll (first_list, first_length, compare);
951   second_list = merge_sort_sll (second_list, second_length, compare);
952
953   merge_point = &result;
954   while (first_list && second_list)
955     if ((*compare) (first_list, second_list) < 0)
956       {
957         cursor = SUCCESSOR (first_list);
958         *merge_point = first_list;
959         merge_point = &SUCCESSOR (first_list);
960         first_list = cursor;
961       }
962     else
963       {
964         cursor = SUCCESSOR (second_list);
965         *merge_point = second_list;
966         merge_point = &SUCCESSOR (second_list);
967         second_list = cursor;
968       }
969   if (first_list)
970     *merge_point = first_list;
971   else
972     *merge_point = second_list;
973
974   return result;
975
976 #undef SUCCESSOR
977 }
978
979 /* Sort doubly linked LIST of names, of given LENGTH, using COMPARE
980    to order names.  Return the sorted list.  */
981 static struct name *
982 merge_sort (struct name *list, int length,
983             int (*compare) (struct name const*, struct name const*))
984 {
985   struct name *head, *p, *prev;
986   head = merge_sort_sll (list, length, compare);
987   /* Fixup prev pointers */
988   for (prev = NULL, p = head; p; prev = p, p = p->next)
989     p->prev = prev;
990   return head;
991 }
992
993 /* A comparison function for sorting names.  Put found names last;
994    break ties by string comparison.  */
995
996 static int
997 compare_names_found (struct name const *n1, struct name const *n2)
998 {
999   int found_diff = WASFOUND (n2) - WASFOUND (n1);
1000   return found_diff ? found_diff : strcmp (n1->name, n2->name);
1001 }
1002
1003 /* Simple comparison by names. */
1004 static int
1005 compare_names (struct name const *n1, struct name const *n2)
1006 {
1007   return strcmp (n1->name, n2->name);
1008 }
1009
1010 \f
1011 /* Add all the dirs under ST to the namelist NAME, descending the
1012    directory hierarchy recursively.  */
1013
1014 static void
1015 add_hierarchy_to_namelist (struct tar_stat_info *st, struct name *name)
1016 {
1017   const char *buffer;
1018
1019   name->directory = scan_directory (st);
1020   buffer = directory_contents (name->directory);
1021   if (buffer)
1022     {
1023       struct name *child_head = NULL, *child_tail = NULL;
1024       size_t name_length = name->length;
1025       size_t allocated_length = (name_length >= NAME_FIELD_SIZE
1026                                  ? name_length + NAME_FIELD_SIZE
1027                                  : NAME_FIELD_SIZE);
1028       char *namebuf = xmalloc (allocated_length + 1);
1029                                 /* FIXME: + 2 above?  */
1030       const char *string;
1031       size_t string_length;
1032       int change_dir = name->change_dir;
1033
1034       strcpy (namebuf, name->name);
1035       if (! ISSLASH (namebuf[name_length - 1]))
1036         {
1037           namebuf[name_length++] = '/';
1038           namebuf[name_length] = '\0';
1039         }
1040
1041       for (string = buffer; *string; string += string_length + 1)
1042         {
1043           string_length = strlen (string);
1044           if (*string == 'D')
1045             {
1046               struct name *np;
1047               struct tar_stat_info subdir;
1048               int subfd;
1049
1050               if (allocated_length <= name_length + string_length)
1051                 {
1052                   do
1053                     {
1054                       allocated_length *= 2;
1055                       if (! allocated_length)
1056                         xalloc_die ();
1057                     }
1058                   while (allocated_length <= name_length + string_length);
1059
1060                   namebuf = xrealloc (namebuf, allocated_length + 1);
1061                 }
1062               strcpy (namebuf + name_length, string + 1);
1063               np = addname (namebuf, change_dir, false, name);
1064               if (!child_head)
1065                 child_head = np;
1066               else
1067                 child_tail->sibling = np;
1068               child_tail = np;
1069
1070               tar_stat_init (&subdir);
1071               subdir.parent = st;
1072               if (st->fd < 0)
1073                 {
1074                   subfd = -1;
1075                   errno = - st->fd;
1076                 }
1077               else
1078                 subfd = subfile_open (st, string + 1,
1079                                       open_read_flags | O_DIRECTORY);
1080               if (subfd < 0)
1081                 open_diag (namebuf);
1082               else
1083                 {
1084                   subdir.fd = subfd;
1085                   if (fstat (subfd, &subdir.stat) != 0)
1086                     stat_diag (namebuf);
1087                   else if (! (O_DIRECTORY || S_ISDIR (subdir.stat.st_mode)))
1088                     {
1089                       errno = ENOTDIR;
1090                       open_diag (namebuf);
1091                     }
1092                   else
1093                     {
1094                       subdir.orig_file_name = xstrdup (namebuf);
1095                       add_hierarchy_to_namelist (&subdir, np);
1096                       restore_parent_fd (&subdir);
1097                     }
1098                 }
1099
1100               tar_stat_destroy (&subdir);
1101             }
1102         }
1103
1104       free (namebuf);
1105       name->child = child_head;
1106     }
1107 }
1108 \f
1109 /* Auxiliary functions for hashed table of struct name's. */
1110
1111 static size_t
1112 name_hash (void const *entry, size_t n_buckets)
1113 {
1114   struct name const *name = entry;
1115   return hash_string (name->caname, n_buckets);
1116 }
1117
1118 /* Compare two directories for equality of their names. */
1119 static bool
1120 name_compare (void const *entry1, void const *entry2)
1121 {
1122   struct name const *name1 = entry1;
1123   struct name const *name2 = entry2;
1124   return strcmp (name1->caname, name2->caname) == 0;
1125 }
1126
1127 \f
1128 /* Rebase 'name' member of CHILD and all its siblings to
1129    the new PARENT. */
1130 static void
1131 rebase_child_list (struct name *child, struct name *parent)
1132 {
1133   size_t old_prefix_len = child->parent->length;
1134   size_t new_prefix_len = parent->length;
1135   char *new_prefix = parent->name;
1136
1137   for (; child; child = child->sibling)
1138     {
1139       size_t size = child->length - old_prefix_len + new_prefix_len;
1140       char *newp = xmalloc (size + 1);
1141       strcpy (newp, new_prefix);
1142       strcat (newp, child->name + old_prefix_len);
1143       free (child->name);
1144       child->name = newp;
1145       child->length = size;
1146
1147       rebase_directory (child->directory,
1148                         child->parent->name, old_prefix_len,
1149                         new_prefix, new_prefix_len);
1150     }
1151 }
1152
1153 /* Collect all the names from argv[] (or whatever), expand them into a
1154    directory tree, and sort them.  This gets only subdirectories, not
1155    all files.  */
1156
1157 void
1158 collect_and_sort_names (void)
1159 {
1160   struct name *name;
1161   struct name *next_name, *prev_name = NULL;
1162   int num_names;
1163   Hash_table *nametab;
1164
1165   name_gather ();
1166
1167   if (!namelist)
1168     addname (".", 0, false, NULL);
1169
1170   if (listed_incremental_option)
1171     {
1172       switch (chdir_count ())
1173         {
1174         case 0:
1175           break;
1176
1177         case 1:
1178           if (namelist->change_dir == 0)
1179             USAGE_ERROR ((0, 0,
1180                           _("Using -C option inside file list is not "
1181                             "allowed with --listed-incremental")));
1182           break;
1183
1184         default:
1185           USAGE_ERROR ((0, 0,
1186                         _("Only one -C option is allowed with "
1187                           "--listed-incremental")));
1188         }
1189
1190       read_directory_file ();
1191     }
1192
1193   num_names = 0;
1194   for (name = namelist; name; name = name->next, num_names++)
1195     {
1196       struct tar_stat_info st;
1197
1198       if (name->found_count || name->directory)
1199         continue;
1200       if (name->matching_flags & EXCLUDE_WILDCARDS)
1201         /* NOTE: EXCLUDE_ANCHORED is not relevant here */
1202         /* FIXME: just skip regexps for now */
1203         continue;
1204       chdir_do (name->change_dir);
1205
1206       if (name->name[0] == 0)
1207         continue;
1208
1209       tar_stat_init (&st);
1210
1211       if (deref_stat (name->name, &st.stat) != 0)
1212         {
1213           stat_diag (name->name);
1214           continue;
1215         }
1216       if (S_ISDIR (st.stat.st_mode))
1217         {
1218           int dir_fd = openat (chdir_fd, name->name,
1219                                open_read_flags | O_DIRECTORY);
1220           if (dir_fd < 0)
1221             open_diag (name->name);
1222           else
1223             {
1224               st.fd = dir_fd;
1225               if (fstat (dir_fd, &st.stat) != 0)
1226                 stat_diag (name->name);
1227               else if (O_DIRECTORY || S_ISDIR (st.stat.st_mode))
1228                 {
1229                   st.orig_file_name = xstrdup (name->name);
1230                   name->found_count++;
1231                   add_hierarchy_to_namelist (&st, name);
1232                 }
1233             }
1234         }
1235
1236       tar_stat_destroy (&st);
1237     }
1238
1239   namelist = merge_sort (namelist, num_names, compare_names);
1240
1241   num_names = 0;
1242   nametab = hash_initialize (0, 0, name_hash, name_compare, NULL);
1243   for (name = namelist; name; name = next_name)
1244     {
1245       next_name = name->next;
1246       name->caname = normalize_filename (name->change_dir, name->name);
1247       if (prev_name)
1248         {
1249           struct name *p = hash_lookup (nametab, name);
1250           if (p)
1251             {
1252               /* Keep the one listed in the command line */
1253               if (!name->parent)
1254                 {
1255                   if (p->child)
1256                     rebase_child_list (p->child, name);
1257                   hash_delete (nametab, name);
1258                   /* FIXME: remove_directory (p->caname); ? */
1259                   remname (p);
1260                   free_name (p);
1261                   num_names--;
1262                 }
1263               else
1264                 {
1265                   if (name->child)
1266                     rebase_child_list (name->child, p);
1267                   /* FIXME: remove_directory (name->caname); ? */
1268                   remname (name);
1269                   free_name (name);
1270                   continue;
1271                 }
1272             }
1273         }
1274       name->found_count = 0;
1275       if (!hash_insert (nametab, name))
1276         xalloc_die ();
1277       prev_name = name;
1278       num_names++;
1279     }
1280   nametail = prev_name;
1281   hash_free (nametab);
1282
1283   namelist = merge_sort (namelist, num_names, compare_names_found);
1284
1285   if (listed_incremental_option)
1286     {
1287       for (name = namelist; name && name->name[0] == 0; name++)
1288         ;
1289       if (name)
1290         append_incremental_renames (name->directory);
1291     }
1292 }
1293
1294 /* This is like name_match, except that
1295     1. It returns a pointer to the name it matched, and doesn't set FOUND
1296     in structure. The caller will have to do that if it wants to.
1297     2. If the namelist is empty, it returns null, unlike name_match, which
1298     returns TRUE. */
1299 struct name *
1300 name_scan (const char *file_name)
1301 {
1302   size_t length = strlen (file_name);
1303
1304   while (1)
1305     {
1306       struct name *cursor = namelist_match (file_name, length);
1307       if (cursor)
1308         return cursor;
1309
1310       /* Filename from archive not found in namelist.  If we have the whole
1311          namelist here, just return 0.  Otherwise, read the next name in and
1312          compare it.  If this was the last name, namelist->found_count will
1313          remain on.  If not, we loop to compare the newly read name.  */
1314
1315       if (same_order_option && namelist && namelist->found_count)
1316         {
1317           name_gather ();       /* read one more */
1318           if (namelist->found_count)
1319             return 0;
1320         }
1321       else
1322         return 0;
1323     }
1324 }
1325
1326 /* This returns a name from the namelist which doesn't have ->found
1327    set.  It sets ->found before returning, so successive calls will
1328    find and return all the non-found names in the namelist.  */
1329 struct name *gnu_list_name;
1330
1331 struct name const *
1332 name_from_list (void)
1333 {
1334   if (!gnu_list_name)
1335     gnu_list_name = namelist;
1336   while (gnu_list_name
1337          && (gnu_list_name->found_count || gnu_list_name->name[0] == 0))
1338     gnu_list_name = gnu_list_name->next;
1339   if (gnu_list_name)
1340     {
1341       gnu_list_name->found_count++;
1342       chdir_do (gnu_list_name->change_dir);
1343       return gnu_list_name;
1344     }
1345   return NULL;
1346 }
1347
1348 void
1349 blank_name_list (void)
1350 {
1351   struct name *name;
1352
1353   gnu_list_name = 0;
1354   for (name = namelist; name; name = name->next)
1355     name->found_count = 0;
1356 }
1357
1358 /* Yield a newly allocated file name consisting of FILE_NAME concatenated to
1359    NAME, with an intervening slash if FILE_NAME does not already end in one. */
1360 char *
1361 new_name (const char *file_name, const char *name)
1362 {
1363   size_t file_name_len = strlen (file_name);
1364   size_t namesize = strlen (name) + 1;
1365   int slash = file_name_len && ! ISSLASH (file_name[file_name_len - 1]);
1366   char *buffer = xmalloc (file_name_len + slash + namesize);
1367   memcpy (buffer, file_name, file_name_len);
1368   buffer[file_name_len] = '/';
1369   memcpy (buffer + file_name_len + slash, name, namesize);
1370   return buffer;
1371 }
1372
1373 /* Return nonzero if file NAME is excluded.  */
1374 bool
1375 excluded_name (char const *name)
1376 {
1377   return excluded_file_name (excluded, name + FILE_SYSTEM_PREFIX_LEN (name));
1378 }
1379 \f
1380
1381 /* Return the size of the prefix of FILE_NAME that is removed after
1382    stripping NUM leading file name components.  NUM must be
1383    positive.  */
1384
1385 size_t
1386 stripped_prefix_len (char const *file_name, size_t num)
1387 {
1388   char const *p = file_name + FILE_SYSTEM_PREFIX_LEN (file_name);
1389   while (ISSLASH (*p))
1390     p++;
1391   while (*p)
1392     {
1393       bool slash = ISSLASH (*p);
1394       p++;
1395       if (slash)
1396         {
1397           if (--num == 0)
1398             return p - file_name;
1399           while (ISSLASH (*p))
1400             p++;
1401         }
1402     }
1403   return -1;
1404 }
1405 \f
1406 /* Return nonzero if NAME contains ".." as a file name component.  */
1407 bool
1408 contains_dot_dot (char const *name)
1409 {
1410   char const *p = name + FILE_SYSTEM_PREFIX_LEN (name);
1411
1412   for (;; p++)
1413     {
1414       if (p[0] == '.' && p[1] == '.' && (ISSLASH (p[2]) || !p[2]))
1415         return 1;
1416
1417       while (! ISSLASH (*p))
1418         {
1419           if (! *p++)
1420             return 0;
1421         }
1422     }
1423 }