]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - contrib/cpio/src/copyin.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / contrib / cpio / src / copyin.c
1 /* $FreeBSD$ */
2
3 /* copyin.c - extract or list a cpio archive
4    Copyright (C) 1990,1991,1992,2001,2002,2003,2004 Free Software Foundation, Inc.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2, or (at your option)
9    any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General 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, write to the Free Software Foundation, Inc.,
18    59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
19
20 #include <system.h>
21
22 #include <stdio.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include "filetypes.h"
26 #include "cpiohdr.h"
27 #include "dstring.h"
28 #include "extern.h"
29 #include "defer.h"
30 #include "dirname.h"
31 #include <rmt.h>
32 #ifndef FNM_PATHNAME
33 #include <fnmatch.h>
34 #endif
35 #include <langinfo.h>
36
37 #ifndef HAVE_LCHOWN
38 #define lchown chown
39 #endif
40
41 static void copyin_regular_file(struct new_cpio_header* file_hdr,
42                                 int in_file_des);
43
44 void
45 warn_junk_bytes (long bytes_skipped)
46 {
47   error (0, 0, ngettext ("warning: skipped %ld byte of junk",
48                          "warning: skipped %ld bytes of junk", bytes_skipped),
49          bytes_skipped);
50 }
51
52 \f
53 static int
54 query_rename(struct new_cpio_header* file_hdr, FILE *tty_in, FILE *tty_out,
55              FILE *rename_in)
56 {
57   char *str_res;                /* Result for string function.  */
58   static dynamic_string new_name;       /* New file name for rename option.  */
59   static int initialized_new_name = false;
60   if (!initialized_new_name)
61   {
62     ds_init (&new_name, 128);
63     initialized_new_name = true;
64   }
65
66   if (rename_flag)
67     {
68       fprintf (tty_out, _("rename %s -> "), file_hdr->c_name);
69       fflush (tty_out);
70       str_res = ds_fgets (tty_in, &new_name);
71     }
72   else
73     {
74       str_res = ds_fgetstr (rename_in, &new_name, '\n');
75     }
76   if (str_res == NULL || str_res[0] == 0)
77     {
78       return -1;
79     }
80   else
81   /* Debian hack: file_hrd.c_name is sometimes set to
82      point to static memory by code in tar.c.  This
83      causes a segfault.  This has been fixed and an
84      additional check to ensure that the file name
85      is not too long has been added.  (Reported by
86      Horst Knobloch.)  This bug has been reported to
87      "bug-gnu-utils@prep.ai.mit.edu". (99/1/6) -BEM */
88     {
89       if (archive_format != arf_tar && archive_format != arf_ustar)
90         {
91           free (file_hdr->c_name);
92           file_hdr->c_name = xstrdup (new_name.ds_string);
93         }
94       else
95         {
96           if (is_tar_filename_too_long (new_name.ds_string))
97             error (0, 0, _("%s: file name too long"),
98                    new_name.ds_string);
99           else
100             strcpy (file_hdr->c_name, new_name.ds_string);
101         }
102     }
103   return 0;
104 }
105 \f
106 /* Skip the padding on IN_FILE_DES after a header or file,
107    up to the next header.
108    The number of bytes skipped is based on OFFSET -- the current offset
109    from the last start of a header (or file) -- and the current
110    header type.  */
111
112 static void
113 tape_skip_padding (int in_file_des, int offset)
114 {
115   int pad;
116
117   if (archive_format == arf_crcascii || archive_format == arf_newascii)
118     pad = (4 - (offset % 4)) % 4;
119   else if (archive_format == arf_binary || archive_format == arf_hpbinary)
120     pad = (2 - (offset % 2)) % 2;
121   else if (archive_format == arf_tar || archive_format == arf_ustar)
122     pad = (512 - (offset % 512)) % 512;
123   else
124     pad = 0;
125
126   if (pad != 0)
127     tape_toss_input (in_file_des, pad);
128 }
129
130 \f
131 static void
132 list_file(struct new_cpio_header* file_hdr, int in_file_des)
133 {
134   if (verbose_flag)
135     {
136 #ifdef CP_IFLNK
137       if ((file_hdr->c_mode & CP_IFMT) == CP_IFLNK)
138         {
139           if (archive_format != arf_tar && archive_format != arf_ustar)
140             {
141               char *link_name = NULL;   /* Name of hard and symbolic links.  */
142
143               link_name = (char *) xmalloc ((unsigned int) file_hdr->c_filesize + 1);
144               link_name[file_hdr->c_filesize] = '\0';
145               tape_buffered_read (link_name, in_file_des, file_hdr->c_filesize);
146               long_format (file_hdr, link_name);
147               free (link_name);
148               tape_skip_padding (in_file_des, file_hdr->c_filesize);
149               return;
150             }
151           else
152             {
153               long_format (file_hdr, file_hdr->c_tar_linkname);
154               return;
155             }
156         }
157       else
158 #endif
159         long_format (file_hdr, (char *) 0);
160     }
161   else
162     {
163       /* Debian hack: Modified to print a list of filenames
164          terminiated by a null character when the -t and -0
165          flags are used.  This has been submitted as a
166          suggestion to "bug-gnu-utils@prep.ai.mit.edu".  -BEM */
167       printf ("%s%c", file_hdr->c_name, name_end);
168     }
169
170   crc = 0;
171   tape_toss_input (in_file_des, file_hdr->c_filesize);
172   tape_skip_padding (in_file_des, file_hdr->c_filesize);
173   if (only_verify_crc_flag)
174     {
175 #ifdef CP_IFLNK
176       if ((file_hdr->c_mode & CP_IFMT) == CP_IFLNK)
177         {
178           return;   /* links don't have a checksum */
179         }
180 #endif
181       if (crc != file_hdr->c_chksum)
182         {
183           error (0, 0, _("%s: checksum error (0x%x, should be 0x%x)"),
184                  file_hdr->c_name, crc, file_hdr->c_chksum);
185         }
186     }
187 }
188 \f
189 static int
190 try_existing_file(struct new_cpio_header* file_hdr, int in_file_des,
191                   int *existing_dir)
192 {
193   struct stat file_stat;
194
195   *existing_dir = false;
196   if (lstat (file_hdr->c_name, &file_stat) == 0)
197     {
198       if (S_ISDIR (file_stat.st_mode)
199           && ((file_hdr->c_mode & CP_IFMT) == CP_IFDIR))
200         {
201           /* If there is already a directory there that
202              we are trying to create, don't complain about
203              it.  */
204           *existing_dir = true;
205           return 0;
206         }
207       else if (!unconditional_flag
208                && file_hdr->c_mtime <= file_stat.st_mtime)
209         {
210           error (0, 0, _("%s not created: newer or same age version exists"),
211                  file_hdr->c_name);
212           tape_toss_input (in_file_des, file_hdr->c_filesize);
213           tape_skip_padding (in_file_des, file_hdr->c_filesize);
214           return -1;    /* Go to the next file.  */
215         }
216       else if (S_ISDIR (file_stat.st_mode) 
217                 ? rmdir (file_hdr->c_name)
218                 : unlink (file_hdr->c_name))
219         {
220           error (0, errno, _("cannot remove current %s"),
221                  file_hdr->c_name);
222           tape_toss_input (in_file_des, file_hdr->c_filesize);
223           tape_skip_padding (in_file_des, file_hdr->c_filesize);
224           return -1;    /* Go to the next file.  */
225         }
226     }
227   return 0;
228 }
229 \f
230 /* The newc and crc formats store multiply linked copies of the same file 
231    in the archive only once.  The actual data is attached to the last link 
232    in the archive, and the other links all have a filesize of 0.  When a 
233    file in the archive has multiple links and a filesize of 0, its data is 
234    probably "attatched" to another file in the archive, so we can't create
235    it right away.  We have to "defer" creating it until we have created
236    the file that has the data "attatched" to it.  We keep a list of the
237    "defered" links on deferments.  */
238
239 struct deferment *deferments = NULL;
240
241 /* Add a file header to the deferments list.  For now they all just
242    go on one list, although we could optimize this if necessary.  */
243
244 static void
245 defer_copyin (struct new_cpio_header *file_hdr)
246 {
247   struct deferment *d;
248   d = create_deferment (file_hdr);
249   d->next = deferments;
250   deferments = d;
251   return;
252 }
253
254 /* We just created a file that (probably) has some other links to it
255    which have been defered.  Go through all of the links on the deferments
256    list and create any which are links to this file.  */
257
258 static void
259 create_defered_links (struct new_cpio_header *file_hdr)
260 {
261   struct deferment *d;
262   struct deferment *d_prev;
263   int   ino;
264   int   maj;
265   int   min;
266   int   link_res;
267   ino = file_hdr->c_ino;
268   maj = file_hdr->c_dev_maj;
269   min = file_hdr->c_dev_min;
270   d = deferments;
271   d_prev = NULL;
272   while (d != NULL)
273     {
274       if ( (d->header.c_ino == ino) && (d->header.c_dev_maj == maj)
275           && (d->header.c_dev_min == min) )
276         {
277           struct deferment *d_free;
278           link_res = link_to_name (d->header.c_name, file_hdr->c_name);
279           if (link_res < 0)
280             {
281               error (0, errno, _("cannot link %s to %s"),
282                      d->header.c_name, file_hdr->c_name);
283             }
284           if (d_prev != NULL)
285             d_prev->next = d->next;
286           else
287             deferments = d->next;
288           d_free = d;
289           d = d->next;
290           free_deferment (d_free);
291         }
292       else
293         {
294           d_prev = d;
295           d = d->next;
296         }
297     }
298 }
299
300 /* We are skipping a file but there might be other links to it that we
301    did not skip, so we have to copy its data for the other links.  Find
302    the first link that we didn't skip and try to create that.  That will
303    then create the other deferred links.  */
304
305 static int
306 create_defered_links_to_skipped (struct new_cpio_header *file_hdr,
307                                  int in_file_des)
308 {
309   struct deferment *d;
310   struct deferment *d_prev;
311   int   ino;
312   int   maj;
313   int   min;
314   int   link_res;
315   if (file_hdr->c_filesize == 0)
316     {
317       /* The file doesn't have any data attached to it so we don't have
318          to bother.  */
319       return -1;
320     }
321   ino = file_hdr->c_ino;
322   maj = file_hdr->c_dev_maj;
323   min = file_hdr->c_dev_min;
324   d = deferments;
325   d_prev = NULL;
326   while (d != NULL)
327     {
328       if ( (d->header.c_ino == ino) && (d->header.c_dev_maj == maj)
329           && (d->header.c_dev_min == min) )
330         {
331           if (d_prev != NULL)
332             d_prev->next = d->next;
333           else
334             deferments = d->next;
335           free (file_hdr->c_name);
336           file_hdr->c_name = xstrdup(d->header.c_name);
337           free_deferment (d);
338           copyin_regular_file(file_hdr, in_file_des);
339           return 0;
340         }
341       else
342         {
343           d_prev = d;
344           d = d->next;
345         }
346     }
347   return -1;
348 }
349
350 /* If we had a multiply linked file that really was empty then we would
351    have defered all of its links, since we never found any with data
352    "attached", and they will still be on the deferment list even when
353    we are done reading the whole archive.  Write out all of these
354    empty links that are still on the deferments list.  */
355
356 static void
357 create_final_defers ()
358 {
359   struct deferment *d;
360   int   link_res;
361   int   out_file_des;
362   struct utimbuf times;         /* For setting file times.  */
363   /* Initialize this in case it has members we don't know to set.  */
364   bzero (&times, sizeof (struct utimbuf));
365   
366   for (d = deferments; d != NULL; d = d->next)
367     {
368       /* Debian hack: A line, which could cause an endless loop, was
369          removed (97/1/2).  It was reported by Ronald F. Guilmette to
370          the upstream maintainers. -BEM */
371       /* Debian hack:  This was reported by Horst Knobloch. This bug has
372          been reported to "bug-gnu-utils@prep.ai.mit.edu". (99/1/6) -BEM
373          */
374       link_res = link_to_maj_min_ino (d->header.c_name, 
375                     d->header.c_dev_maj, d->header.c_dev_min,
376                     d->header.c_ino);
377       if (link_res == 0)
378         {
379           continue;
380         }
381       out_file_des = open (d->header.c_name,
382                            O_CREAT | O_WRONLY | O_BINARY, 0600);
383       if (out_file_des < 0 && create_dir_flag)
384         {
385           create_all_directories (d->header.c_name);
386           out_file_des = open (d->header.c_name,
387                                O_CREAT | O_WRONLY | O_BINARY,
388                                0600);
389         }
390       if (out_file_des < 0)
391         {
392           error (0, errno, "%s", d->header.c_name);
393           continue;
394         }
395
396       /*
397        *  Avoid race condition.
398        *  Set chown and chmod before closing the file desc.
399        *  pvrabec@redhat.com
400        */
401        
402       /* File is now copied; set attributes.  */
403       if (!no_chown_flag)
404         if ((fchown (out_file_des,
405                     set_owner_flag ? set_owner : d->header.c_uid,
406                set_group_flag ? set_group : d->header.c_gid) < 0)
407             && errno != EPERM)
408           error (0, errno, "%s", d->header.c_name);
409       /* chown may have turned off some permissions we wanted. */
410       if (fchmod (out_file_des, (int) d->header.c_mode) < 0)
411         error (0, errno, "%s", d->header.c_name);
412
413       if (close (out_file_des) < 0)
414         error (0, errno, "%s", d->header.c_name);
415
416       if (retain_time_flag)
417         {
418           times.actime = times.modtime = d->header.c_mtime;
419           if (utime (d->header.c_name, &times) < 0)
420             error (0, errno, "%s", d->header.c_name);
421         }
422     }
423 }
424 \f
425 static void
426 copyin_regular_file (struct new_cpio_header* file_hdr, int in_file_des)
427 {
428   int out_file_des;             /* Output file descriptor.  */
429
430   if (to_stdout_option)
431     out_file_des = STDOUT_FILENO;
432   else
433     {
434       /* Can the current file be linked to a previously copied file? */
435       if (file_hdr->c_nlink > 1
436           && (archive_format == arf_newascii
437               || archive_format == arf_crcascii) )
438         {
439           int link_res;
440           if (file_hdr->c_filesize == 0)
441             {
442               /* The newc and crc formats store multiply linked copies
443                  of the same file in the archive only once.  The
444                  actual data is attached to the last link in the
445                  archive, and the other links all have a filesize
446                  of 0.  Since this file has multiple links and a
447                  filesize of 0, its data is probably attatched to
448                  another file in the archive.  Save the link, and
449                  process it later when we get the actual data.  We
450                  can't just create it with length 0 and add the
451                  data later, in case the file is readonly.  We still
452                  lose if its parent directory is readonly (and we aren't
453                  running as root), but there's nothing we can do about
454                  that.  */
455               defer_copyin (file_hdr);
456               tape_toss_input (in_file_des, file_hdr->c_filesize);
457               tape_skip_padding (in_file_des, file_hdr->c_filesize);
458               return;
459             }
460           /* If the file has data (filesize != 0), then presumably
461              any other links have already been defer_copyin'ed(),
462              but GNU cpio version 2.0-2.2 didn't do that, so we
463              still have to check for links here (and also in case
464              the archive was created and later appeneded to). */
465           /* Debian hack: (97/1/2) This was reported by Ronald
466              F. Guilmette to the upstream maintainers. -BEM */
467           link_res = link_to_maj_min_ino (file_hdr->c_name, 
468                     file_hdr->c_dev_maj, file_hdr->c_dev_min,
469                                           file_hdr->c_ino);
470           if (link_res == 0)
471             {
472               tape_toss_input (in_file_des, file_hdr->c_filesize);
473               tape_skip_padding (in_file_des, file_hdr->c_filesize);
474           return;
475             }
476         }
477       else if (file_hdr->c_nlink > 1
478                && archive_format != arf_tar
479                && archive_format != arf_ustar)
480         {
481           int link_res;
482           /* Debian hack: (97/1/2) This was reported by Ronald
483              F. Guilmette to the upstream maintainers. -BEM */
484           link_res = link_to_maj_min_ino (file_hdr->c_name, 
485                                           file_hdr->c_dev_maj,
486                                           file_hdr->c_dev_min,
487                                           file_hdr->c_ino);
488           if (link_res == 0)
489             {
490               tape_toss_input (in_file_des, file_hdr->c_filesize);
491               tape_skip_padding (in_file_des, file_hdr->c_filesize);
492               return;
493             }
494         }
495       else if ((archive_format == arf_tar || archive_format == arf_ustar)
496                && file_hdr->c_tar_linkname
497                && file_hdr->c_tar_linkname[0] != '\0')
498         {
499           int   link_res;
500           link_res = link_to_name (file_hdr->c_name, file_hdr->c_tar_linkname);
501           if (link_res < 0)
502             {
503               error (0, errno, _("cannot link %s to %s"),
504                      file_hdr->c_tar_linkname, file_hdr->c_name);
505             }
506           return;
507         }
508     
509       /* If not linked, copy the contents of the file.  */
510       out_file_des = open (file_hdr->c_name,
511                            O_CREAT | O_WRONLY | O_BINARY, 0600);
512   
513       if (out_file_des < 0 && create_dir_flag)
514         {
515           create_all_directories (file_hdr->c_name);
516           out_file_des = open (file_hdr->c_name,
517                                O_CREAT | O_WRONLY | O_BINARY,
518                                0600);
519         }
520       
521       if (out_file_des < 0)
522         {
523           error (0, errno, "%s", file_hdr->c_name);
524           tape_toss_input (in_file_des, file_hdr->c_filesize);
525           tape_skip_padding (in_file_des, file_hdr->c_filesize);
526           return;
527         }
528     }
529   
530   crc = 0;
531   if (swap_halfwords_flag)
532     {
533       if ((file_hdr->c_filesize % 4) == 0)
534         swapping_halfwords = true;
535       else
536         error (0, 0, _("cannot swap halfwords of %s: odd number of halfwords"),
537                file_hdr->c_name);
538     }
539   if (swap_bytes_flag)
540     {
541       if ((file_hdr->c_filesize % 2) == 0)
542         swapping_bytes = true;
543       else
544         error (0, 0, _("cannot swap bytes of %s: odd number of bytes"),
545                file_hdr->c_name);
546     }
547   copy_files_tape_to_disk (in_file_des, out_file_des, file_hdr->c_filesize);
548   disk_empty_output_buffer (out_file_des);
549   
550   if (to_stdout_option)
551     {
552       if (archive_format == arf_crcascii)
553         {
554           if (crc != file_hdr->c_chksum)
555             error (0, 0, _("%s: checksum error (0x%x, should be 0x%x)"),
556                    file_hdr->c_name, crc, file_hdr->c_chksum);
557         }
558       tape_skip_padding (in_file_des, file_hdr->c_filesize);
559       return;
560     }
561       
562   /* Debian hack to fix a bug in the --sparse option.
563      This bug has been reported to
564      "bug-gnu-utils@prep.ai.mit.edu".  (96/7/10) -BEM */
565   if (delayed_seek_count > 0)
566     {
567       lseek (out_file_des, delayed_seek_count-1, SEEK_CUR);
568       write (out_file_des, "", 1);
569       delayed_seek_count = 0;
570     }
571     
572   /*
573    *  Avoid race condition.
574    *  Set chown and chmod before closing the file desc.
575    *  pvrabec@redhat.com
576    */
577    
578   /* File is now copied; set attributes.  */
579   if (!no_chown_flag)
580     if ((fchown (out_file_des,
581                 set_owner_flag ? set_owner : file_hdr->c_uid,
582            set_group_flag ? set_group : file_hdr->c_gid) < 0)
583         && errno != EPERM)
584       error (0, errno, "%s", file_hdr->c_name);
585   
586   /* chown may have turned off some permissions we wanted. */
587   if (fchmod (out_file_des, (int) file_hdr->c_mode) < 0)
588     error (0, errno, "%s", file_hdr->c_name);
589      
590   if (close (out_file_des) < 0)
591     error (0, errno, "%s", file_hdr->c_name);
592
593   if (archive_format == arf_crcascii)
594     {
595       if (crc != file_hdr->c_chksum)
596         error (0, 0, _("%s: checksum error (0x%x, should be 0x%x)"),
597                file_hdr->c_name, crc, file_hdr->c_chksum);
598     }
599
600   if (retain_time_flag)
601     {
602       struct utimbuf times;             /* For setting file times.  */
603       /* Initialize this in case it has members we don't know to set.  */
604       bzero (&times, sizeof (struct utimbuf));
605
606       times.actime = times.modtime = file_hdr->c_mtime;
607       if (utime (file_hdr->c_name, &times) < 0)
608         error (0, errno, "%s", file_hdr->c_name);
609     }
610     
611   tape_skip_padding (in_file_des, file_hdr->c_filesize);
612   if (file_hdr->c_nlink > 1
613       && (archive_format == arf_newascii || archive_format == arf_crcascii) )
614     {
615       /* (see comment above for how the newc and crc formats 
616          store multiple links).  Now that we have the data 
617          for this file, create any other links to it which
618          we defered.  */
619       create_defered_links (file_hdr);
620     }
621 }
622 \f
623 static void
624 copyin_directory(struct new_cpio_header* file_hdr, int existing_dir)
625 {
626   int res;                      /* Result of various function calls.  */
627 #ifdef HPUX_CDF
628   int cdf_flag;                 /* True if file is a CDF.  */
629   int cdf_char;                 /* Index of `+' char indicating a CDF.  */
630 #endif
631
632   if (to_stdout_option)
633     return;
634   
635   /* Strip any trailing `/'s off the filename; tar puts
636      them on.  We might as well do it here in case anybody
637      else does too, since they cause strange things to happen.  */
638   strip_trailing_slashes (file_hdr->c_name);
639
640   /* Ignore the current directory.  It must already exist,
641      and we don't want to change its permission, ownership
642      or time.  */
643   if (file_hdr->c_name[0] == '.' && file_hdr->c_name[1] == '\0')
644     {
645       return;
646     }
647
648 #ifdef HPUX_CDF
649   cdf_flag = 0;
650 #endif
651   if (!existing_dir)
652
653     {
654 #ifdef HPUX_CDF
655       /* If the directory name ends in a + and is SUID,
656          then it is a CDF.  Strip the trailing + from
657          the name before creating it.  */
658       cdf_char = strlen (file_hdr->c_name) - 1;
659       if ( (cdf_char > 0) &&
660            (file_hdr->c_mode & 04000) && 
661            (file_hdr->c_name [cdf_char] == '+') )
662         {
663           file_hdr->c_name [cdf_char] = '\0';
664           cdf_flag = 1;
665         }
666 #endif
667       res = mkdir (file_hdr->c_name, file_hdr->c_mode);
668     }
669   else
670     res = 0;
671   if (res < 0 && create_dir_flag)
672     {
673       create_all_directories (file_hdr->c_name);
674       res = mkdir (file_hdr->c_name, file_hdr->c_mode);
675     }
676   if (res < 0)
677     {
678       /* In some odd cases where the file_hdr->c_name includes `.',
679          the directory may have actually been created by
680          create_all_directories(), so the mkdir will fail
681          because the directory exists.  If that's the case,
682          don't complain about it.  */
683       struct stat file_stat;
684       if ( (errno != EEXIST) ||
685            (lstat (file_hdr->c_name, &file_stat) != 0) ||
686            !(S_ISDIR (file_stat.st_mode) ) )
687         {
688           error (0, errno, "%s", file_hdr->c_name);
689           return;
690         }
691     }
692   if (!no_chown_flag)
693     if ((chown (file_hdr->c_name,
694                 set_owner_flag ? set_owner : file_hdr->c_uid,
695                 set_group_flag ? set_group : file_hdr->c_gid) < 0)
696         && errno != EPERM)
697       error (0, errno, "%s", file_hdr->c_name);
698   /* chown may have turned off some permissions we wanted. */
699   if (chmod (file_hdr->c_name, (int) file_hdr->c_mode) < 0)
700     error (0, errno, "%s", file_hdr->c_name);
701 #ifdef HPUX_CDF
702   if (cdf_flag)
703     /* Once we "hide" the directory with the chmod(),
704        we have to refer to it using name+ instead of name.  */
705     file_hdr->c_name [cdf_char] = '+';
706 #endif
707   if (retain_time_flag)
708     {
709       struct utimbuf times;             /* For setting file times.  */
710       /* Initialize this in case it has members we don't know to set.  */
711       bzero (&times, sizeof (struct utimbuf));
712
713       times.actime = times.modtime = file_hdr->c_mtime;
714       if (utime (file_hdr->c_name, &times) < 0)
715         error (0, errno, "%s", file_hdr->c_name);
716     }
717 }
718 \f
719 static void
720 copyin_device(struct new_cpio_header* file_hdr)
721 {
722   int res;                      /* Result of various function calls.  */
723
724   if (to_stdout_option)
725     return;
726
727   if (file_hdr->c_nlink > 1 && archive_format != arf_tar
728       && archive_format != arf_ustar)
729     {
730       int link_res;
731       /* Debian hack:  This was reported by Horst
732          Knobloch. This bug has been reported to
733          "bug-gnu-utils@prep.ai.mit.edu". (99/1/6) -BEM */
734       link_res = link_to_maj_min_ino (file_hdr->c_name, 
735                     file_hdr->c_dev_maj, file_hdr->c_dev_min,
736                     file_hdr->c_ino);
737       if (link_res == 0)
738         {
739           return;
740         }
741     }
742   else if (archive_format == arf_ustar &&
743            file_hdr->c_tar_linkname && 
744            file_hdr->c_tar_linkname [0] != '\0')
745     {
746       int       link_res;
747       link_res = link_to_name (file_hdr->c_name,
748                                file_hdr->c_tar_linkname);
749       if (link_res < 0)
750         {
751           error (0, errno, _("cannot link %s to %s"),
752                  file_hdr->c_tar_linkname, file_hdr->c_name);
753           /* Something must be wrong, because we couldn't
754              find the file to link to.  But can we assume
755              that the device maj/min numbers are correct
756              and fall through to the mknod?  It's probably
757              safer to just return, rather than possibly
758              creating a bogus device file.  */
759         }
760       return;
761     }
762   
763 #ifdef CP_IFIFO
764   if ((file_hdr->c_mode & CP_IFMT) == CP_IFIFO)
765     res = mkfifo (file_hdr->c_name, file_hdr->c_mode);
766   else
767 #endif
768     res = mknod (file_hdr->c_name, file_hdr->c_mode,
769               makedev (file_hdr->c_rdev_maj, file_hdr->c_rdev_min));
770   if (res < 0 && create_dir_flag)
771     {
772       create_all_directories (file_hdr->c_name);
773 #ifdef CP_IFIFO
774       if ((file_hdr->c_mode & CP_IFMT) == CP_IFIFO)
775         res = mkfifo (file_hdr->c_name, file_hdr->c_mode);
776       else
777 #endif
778         res = mknod (file_hdr->c_name, file_hdr->c_mode,
779               makedev (file_hdr->c_rdev_maj, file_hdr->c_rdev_min));
780     }
781   if (res < 0)
782     {
783       error (0, errno, "%s", file_hdr->c_name);
784       return;
785     }
786   if (!no_chown_flag)
787     if ((chown (file_hdr->c_name,
788                 set_owner_flag ? set_owner : file_hdr->c_uid,
789                 set_group_flag ? set_group : file_hdr->c_gid) < 0)
790         && errno != EPERM)
791       error (0, errno, "%s", file_hdr->c_name);
792   /* chown may have turned off some permissions we wanted. */
793   if (chmod (file_hdr->c_name, file_hdr->c_mode) < 0)
794     error (0, errno, "%s", file_hdr->c_name);
795   if (retain_time_flag)
796     {
797       struct utimbuf times;             /* For setting file times.  */
798       /* Initialize this in case it has members we don't know to set.  */
799       bzero (&times, sizeof (struct utimbuf));
800
801       times.actime = times.modtime = file_hdr->c_mtime;
802       if (utime (file_hdr->c_name, &times) < 0)
803         error (0, errno, "%s", file_hdr->c_name);
804     }
805 }
806 \f
807 static void
808 copyin_link(struct new_cpio_header *file_hdr, int in_file_des)
809 {
810   char *link_name = NULL;       /* Name of hard and symbolic links.  */
811   int res;                      /* Result of various function calls.  */
812
813   if (to_stdout_option)
814     return;
815
816   if (archive_format != arf_tar && archive_format != arf_ustar)
817     {
818       link_name = (char *) xmalloc ((unsigned int) file_hdr->c_filesize + 1);
819       link_name[file_hdr->c_filesize] = '\0';
820       tape_buffered_read (link_name, in_file_des, file_hdr->c_filesize);
821       tape_skip_padding (in_file_des, file_hdr->c_filesize);
822     }
823   else
824     {
825       link_name = xstrdup (file_hdr->c_tar_linkname);
826     }
827
828   res = UMASKED_SYMLINK (link_name, file_hdr->c_name,
829                          file_hdr->c_mode);
830   if (res < 0 && create_dir_flag)
831     {
832       create_all_directories (file_hdr->c_name);
833       res = UMASKED_SYMLINK (link_name, file_hdr->c_name,
834                              file_hdr->c_mode);
835     }
836   if (res < 0)
837     {
838       error (0, errno, "%s", file_hdr->c_name);
839       free (link_name);
840       return;
841     }
842   if (!no_chown_flag)
843     if ((lchown (file_hdr->c_name,
844                  set_owner_flag ? set_owner : file_hdr->c_uid,
845              set_group_flag ? set_group : file_hdr->c_gid) < 0)
846         && errno != EPERM)
847       {
848         error (0, errno, "%s", file_hdr->c_name);
849       }
850   free (link_name);
851 }
852 \f
853 static void
854 copyin_file (struct new_cpio_header* file_hdr, int in_file_des)
855 {
856   int existing_dir;
857
858   if (!to_stdout_option
859       && try_existing_file (file_hdr, in_file_des, &existing_dir) < 0)
860     return;
861
862   /* Do the real copy or link.  */
863   switch (file_hdr->c_mode & CP_IFMT)
864     {
865     case CP_IFREG:
866       copyin_regular_file(file_hdr, in_file_des);
867       break;
868
869     case CP_IFDIR:
870       copyin_directory(file_hdr, existing_dir);
871       break;
872
873     case CP_IFCHR:
874     case CP_IFBLK:
875 #ifdef CP_IFSOCK
876     case CP_IFSOCK:
877 #endif
878 #ifdef CP_IFIFO
879     case CP_IFIFO:
880 #endif
881       copyin_device(file_hdr);
882       break;
883
884 #ifdef CP_IFLNK
885     case CP_IFLNK:
886       copyin_link(file_hdr, in_file_des);
887       break;
888 #endif
889
890     default:
891       error (0, 0, _("%s: unknown file type"), file_hdr->c_name);
892       tape_toss_input (in_file_des, file_hdr->c_filesize);
893       tape_skip_padding (in_file_des, file_hdr->c_filesize);
894     }
895 }
896 \f
897
898 /* Current time for verbose table.  */
899 static time_t current_time;
900
901
902 /* Print the file described by FILE_HDR in long format.
903    If LINK_NAME is nonzero, it is the name of the file that
904    this file is a symbolic link to.  */
905
906 void
907 long_format (struct new_cpio_header *file_hdr, char *link_name)
908 {
909   char mbuf[11];
910   char tbuf[40];
911   time_t when;
912   char *ptbuf;
913   static int d_first = -1;
914
915   mode_string (file_hdr->c_mode, mbuf);
916   mbuf[10] = '\0';
917
918   /* Get time values ready to print.  */
919   when = file_hdr->c_mtime;
920   if (d_first < 0)
921     d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
922   if (current_time - when > 6L * 30L * 24L * 60L * 60L
923       || current_time - when < 0L)
924         ptbuf = d_first ? "%e %b  %Y" : "%b %e  %Y";
925   else
926         ptbuf = d_first ? "%e %b %R" : "%b %e %R";
927   strftime(tbuf, sizeof(tbuf), ptbuf, localtime(&when));
928   ptbuf = tbuf;
929
930   printf ("%s %3lu ", mbuf, file_hdr->c_nlink);
931
932   if (numeric_uid)
933     printf ("%-8u %-8u ", (unsigned int) file_hdr->c_uid,
934             (unsigned int) file_hdr->c_gid);
935   else
936     printf ("%-8.8s %-8.8s ", getuser (file_hdr->c_uid),
937             getgroup (file_hdr->c_gid));
938
939   if ((file_hdr->c_mode & CP_IFMT) == CP_IFCHR
940       || (file_hdr->c_mode & CP_IFMT) == CP_IFBLK)
941     printf ("%3lu, %3lu ", file_hdr->c_rdev_maj,
942             file_hdr->c_rdev_min);
943   else
944     printf ("%8lu ", file_hdr->c_filesize);
945
946   printf ("%s ", ptbuf);
947
948   print_name_with_quoting (file_hdr->c_name);
949   if (link_name)
950     {
951       printf (" -> ");
952       print_name_with_quoting (link_name);
953     }
954   putc ('\n', stdout);
955 }
956
957 void
958 print_name_with_quoting (register char *p)
959 {
960   register unsigned char c;
961
962   while ( (c = *p++) )
963     {
964       switch (c)
965         {
966         case '\\':
967           printf ("\\\\");
968           break;
969
970         case '\n':
971           printf ("\\n");
972           break;
973
974         case '\b':
975           printf ("\\b");
976           break;
977
978         case '\r':
979           printf ("\\r");
980           break;
981
982         case '\t':
983           printf ("\\t");
984           break;
985
986         case '\f':
987           printf ("\\f");
988           break;
989
990         case ' ':
991           printf ("\\ ");
992           break;
993
994         case '"':
995           printf ("\\\"");
996           break;
997
998         default:
999           if (isprint (c))
1000             putchar (c);
1001           else
1002             printf ("\\%03o", (unsigned int) c);
1003         }
1004     }
1005 }
1006
1007 /* Read a pattern file (for the -E option).  Put a list of
1008    `num_patterns' elements in `save_patterns'.  Any patterns that were
1009    already in `save_patterns' (from the command line) are preserved.  */
1010
1011 static void
1012 read_pattern_file ()
1013 {
1014   int max_new_patterns;
1015   char **new_save_patterns;
1016   int new_num_patterns;
1017   int i;
1018   dynamic_string pattern_name;
1019   FILE *pattern_fp;
1020
1021   if (num_patterns < 0)
1022     num_patterns = 0;
1023   max_new_patterns = 1 + num_patterns;
1024   new_save_patterns = (char **) xmalloc (max_new_patterns * sizeof (char *));
1025   new_num_patterns = num_patterns;
1026   ds_init (&pattern_name, 128);
1027
1028   pattern_fp = fopen (pattern_file_name, "r");
1029   if (pattern_fp == NULL)
1030     error (1, errno, "%s", pattern_file_name);
1031   while (ds_fgetstr (pattern_fp, &pattern_name, '\n') != NULL)
1032     {
1033       if (new_num_patterns >= max_new_patterns)
1034         {
1035           max_new_patterns += 1;
1036           new_save_patterns = (char **)
1037             xrealloc ((char *) new_save_patterns,
1038                       max_new_patterns * sizeof (char *));
1039         }
1040       new_save_patterns[new_num_patterns] = xstrdup (pattern_name.ds_string);
1041       ++new_num_patterns;
1042     }
1043   if (ferror (pattern_fp) || fclose (pattern_fp) == EOF)
1044     error (1, errno, "%s", pattern_file_name);
1045
1046   for (i = 0; i < num_patterns; ++i)
1047     new_save_patterns[i] = save_patterns[i];
1048
1049   save_patterns = new_save_patterns;
1050   num_patterns = new_num_patterns;
1051 }
1052
1053
1054 \f
1055
1056 /* Return 16-bit integer I with the bytes swapped.  */
1057 #define swab_short(i) ((((i) << 8) & 0xff00) | (((i) >> 8) & 0x00ff))
1058
1059 /* Read the header, including the name of the file, from file
1060    descriptor IN_DES into FILE_HDR.  */
1061
1062 void
1063 read_in_header (struct new_cpio_header *file_hdr, int in_des)
1064 {
1065   long bytes_skipped = 0;       /* Bytes of junk found before magic number.  */
1066
1067   /* Search for a valid magic number.  */
1068
1069   if (archive_format == arf_unknown)
1070     {
1071       char tmpbuf[512];
1072       int check_tar;
1073       int peeked_bytes;
1074
1075       while (archive_format == arf_unknown)
1076         {
1077           peeked_bytes = tape_buffered_peek (tmpbuf, in_des, 512);
1078           if (peeked_bytes < 6)
1079             error (1, 0, _("premature end of archive"));
1080
1081           if (!strncmp (tmpbuf, "070701", 6))
1082             archive_format = arf_newascii;
1083           else if (!strncmp (tmpbuf, "070707", 6))
1084             archive_format = arf_oldascii;
1085           else if (!strncmp (tmpbuf, "070702", 6))
1086             {
1087               archive_format = arf_crcascii;
1088               crc_i_flag = true;
1089             }
1090           else if ((*((unsigned short *) tmpbuf) == 070707) ||
1091                    (*((unsigned short *) tmpbuf) == swab_short ((unsigned short) 070707)))
1092             archive_format = arf_binary;
1093           else if (peeked_bytes >= 512
1094                    && (check_tar = is_tar_header (tmpbuf)))
1095             {
1096               if (check_tar == 2)
1097                 archive_format = arf_ustar;
1098               else
1099                 archive_format = arf_tar;
1100             }
1101           else
1102             {
1103               tape_buffered_read ((char *) tmpbuf, in_des, 1L);
1104               ++bytes_skipped;
1105             }
1106         }
1107     }
1108
1109   if (archive_format == arf_tar || archive_format == arf_ustar)
1110     {
1111       if (append_flag)
1112         last_header_start = input_bytes - io_block_size +
1113           (in_buff - input_buffer);
1114       if (bytes_skipped > 0)
1115         warn_junk_bytes (bytes_skipped);
1116
1117       read_in_tar_header (file_hdr, in_des);
1118       return;
1119     }
1120
1121   file_hdr->c_tar_linkname = NULL;
1122
1123   tape_buffered_read ((char *) file_hdr, in_des, 6L);
1124   while (1)
1125     {
1126       if (append_flag)
1127         last_header_start = input_bytes - io_block_size
1128           + (in_buff - input_buffer) - 6;
1129       if (archive_format == arf_newascii
1130           && !strncmp ((char *) file_hdr, "070701", 6))
1131         {
1132           if (bytes_skipped > 0)
1133             warn_junk_bytes (bytes_skipped);
1134           read_in_new_ascii (file_hdr, in_des);
1135           break;
1136         }
1137       if (archive_format == arf_crcascii
1138           && !strncmp ((char *) file_hdr, "070702", 6))
1139         {
1140           if (bytes_skipped > 0)
1141             warn_junk_bytes (bytes_skipped);
1142
1143           read_in_new_ascii (file_hdr, in_des);
1144           break;
1145         }
1146       if ( (archive_format == arf_oldascii || archive_format == arf_hpoldascii)
1147           && !strncmp ((char *) file_hdr, "070707", 6))
1148         {
1149           if (bytes_skipped > 0)
1150             warn_junk_bytes (bytes_skipped);
1151           
1152           read_in_old_ascii (file_hdr, in_des);
1153           break;
1154         }
1155       if ( (archive_format == arf_binary || archive_format == arf_hpbinary)
1156           && (file_hdr->c_magic == 070707
1157               || file_hdr->c_magic == swab_short ((unsigned short) 070707)))
1158         {
1159           /* Having to skip 1 byte because of word alignment is normal.  */
1160           if (bytes_skipped > 0)
1161             warn_junk_bytes (bytes_skipped);
1162           
1163           read_in_binary (file_hdr, in_des);
1164           break;
1165         }
1166       bytes_skipped++;
1167       bcopy ((char *) file_hdr + 1, (char *) file_hdr, 5);
1168       tape_buffered_read ((char *) file_hdr + 5, in_des, 1L);
1169     }
1170 }
1171
1172 /* Fill in FILE_HDR by reading an old-format ASCII format cpio header from
1173    file descriptor IN_DES, except for the magic number, which is
1174    already filled in.  */
1175
1176 void
1177 read_in_old_ascii (struct new_cpio_header *file_hdr, int in_des)
1178 {
1179   char ascii_header[78];
1180   unsigned long dev;
1181   unsigned long rdev;
1182
1183   tape_buffered_read (ascii_header, in_des, 70L);
1184   ascii_header[70] = '\0';
1185   sscanf (ascii_header,
1186           "%6lo%6lo%6lo%6lo%6lo%6lo%6lo%11lo%6lo%11lo",
1187           &dev, &file_hdr->c_ino,
1188           &file_hdr->c_mode, &file_hdr->c_uid, &file_hdr->c_gid,
1189           &file_hdr->c_nlink, &rdev, &file_hdr->c_mtime,
1190           &file_hdr->c_namesize, &file_hdr->c_filesize);
1191   file_hdr->c_dev_maj = major (dev);
1192   file_hdr->c_dev_min = minor (dev);
1193   file_hdr->c_rdev_maj = major (rdev);
1194   file_hdr->c_rdev_min = minor (rdev);
1195
1196   /* Read file name from input.  */
1197   if (file_hdr->c_name != NULL)
1198     free (file_hdr->c_name);
1199   file_hdr->c_name = (char *) xmalloc (file_hdr->c_namesize + 1);
1200   tape_buffered_read (file_hdr->c_name, in_des, (long) file_hdr->c_namesize);
1201
1202   /* HP/UX cpio creates archives that look just like ordinary archives,
1203      but for devices it sets major = 0, minor = 1, and puts the
1204      actual major/minor number in the filesize field.  See if this
1205      is an HP/UX cpio archive, and if so fix it.  We have to do this
1206      here because process_copy_in() assumes filesize is always 0
1207      for devices.  */
1208   switch (file_hdr->c_mode & CP_IFMT)
1209     {
1210       case CP_IFCHR:
1211       case CP_IFBLK:
1212 #ifdef CP_IFSOCK
1213       case CP_IFSOCK:
1214 #endif
1215 #ifdef CP_IFIFO
1216       case CP_IFIFO:
1217 #endif
1218         if (file_hdr->c_filesize != 0
1219             && file_hdr->c_rdev_maj == 0
1220             && file_hdr->c_rdev_min == 1)
1221           {
1222             file_hdr->c_rdev_maj = major (file_hdr->c_filesize);
1223             file_hdr->c_rdev_min = minor (file_hdr->c_filesize);
1224             file_hdr->c_filesize = 0;
1225           }
1226         break;
1227       default:
1228         break;
1229     }
1230 }
1231
1232 /* Fill in FILE_HDR by reading a new-format ASCII format cpio header from
1233    file descriptor IN_DES, except for the magic number, which is
1234    already filled in.  */
1235
1236 void
1237 read_in_new_ascii (struct new_cpio_header *file_hdr, int in_des)
1238 {
1239   char ascii_header[112];
1240
1241   tape_buffered_read (ascii_header, in_des, 104L);
1242   ascii_header[104] = '\0';
1243   sscanf (ascii_header,
1244           "%8lx%8lx%8lx%8lx%8lx%8lx%8lx%8lx%8lx%8lx%8lx%8lx%8lx",
1245           &file_hdr->c_ino, &file_hdr->c_mode, &file_hdr->c_uid,
1246           &file_hdr->c_gid, &file_hdr->c_nlink, &file_hdr->c_mtime,
1247           &file_hdr->c_filesize, &file_hdr->c_dev_maj, &file_hdr->c_dev_min,
1248         &file_hdr->c_rdev_maj, &file_hdr->c_rdev_min, &file_hdr->c_namesize,
1249           &file_hdr->c_chksum);
1250   /* Read file name from input.  */
1251   if (file_hdr->c_name != NULL)
1252     free (file_hdr->c_name);
1253   file_hdr->c_name = (char *) xmalloc (file_hdr->c_namesize);
1254   tape_buffered_read (file_hdr->c_name, in_des, (long) file_hdr->c_namesize);
1255
1256   /* In SVR4 ASCII format, the amount of space allocated for the header
1257      is rounded up to the next long-word, so we might need to drop
1258      1-3 bytes.  */
1259   tape_skip_padding (in_des, file_hdr->c_namesize + 110);
1260 }
1261
1262 /* Fill in FILE_HDR by reading a binary format cpio header from
1263    file descriptor IN_DES, except for the first 6 bytes (the magic
1264    number, device, and inode number), which are already filled in.  */
1265
1266 void
1267 read_in_binary (struct new_cpio_header *file_hdr, int in_des)
1268 {
1269   struct old_cpio_header short_hdr;
1270
1271   /* Copy the data into the short header, then later transfer
1272      it into the argument long header.  */
1273   short_hdr.c_dev = ((struct old_cpio_header *) file_hdr)->c_dev;
1274   short_hdr.c_ino = ((struct old_cpio_header *) file_hdr)->c_ino;
1275   tape_buffered_read (((char *) &short_hdr) + 6, in_des, 20L);
1276
1277   /* If the magic number is byte swapped, fix the header.  */
1278   if (file_hdr->c_magic == swab_short ((unsigned short) 070707))
1279     {
1280       static int warned = 0;
1281
1282       /* Alert the user that they might have to do byte swapping on
1283          the file contents.  */
1284       if (warned == 0)
1285         {
1286           error (0, 0, _("warning: archive header has reverse byte-order"));
1287           warned = 1;
1288         }
1289       swab_array ((char *) &short_hdr, 13);
1290     }
1291
1292   file_hdr->c_dev_maj = major (short_hdr.c_dev);
1293   file_hdr->c_dev_min = minor (short_hdr.c_dev);
1294   file_hdr->c_ino = short_hdr.c_ino;
1295   file_hdr->c_mode = short_hdr.c_mode;
1296   file_hdr->c_uid = short_hdr.c_uid;
1297   file_hdr->c_gid = short_hdr.c_gid;
1298   file_hdr->c_nlink = short_hdr.c_nlink;
1299   file_hdr->c_rdev_maj = major (short_hdr.c_rdev);
1300   file_hdr->c_rdev_min = minor (short_hdr.c_rdev);
1301   file_hdr->c_mtime = (unsigned long) short_hdr.c_mtimes[0] << 16
1302     | short_hdr.c_mtimes[1];
1303
1304   file_hdr->c_namesize = short_hdr.c_namesize;
1305   file_hdr->c_filesize = (unsigned long) short_hdr.c_filesizes[0] << 16
1306     | short_hdr.c_filesizes[1];
1307
1308   /* Read file name from input.  */
1309   if (file_hdr->c_name != NULL)
1310     free (file_hdr->c_name);
1311   file_hdr->c_name = (char *) xmalloc (file_hdr->c_namesize);
1312   tape_buffered_read (file_hdr->c_name, in_des, (long) file_hdr->c_namesize);
1313
1314   /* In binary mode, the amount of space allocated in the header for
1315      the filename is `c_namesize' rounded up to the next short-word,
1316      so we might need to drop a byte.  */
1317   if (file_hdr->c_namesize % 2)
1318     tape_toss_input (in_des, 1L);
1319
1320   /* HP/UX cpio creates archives that look just like ordinary archives,
1321      but for devices it sets major = 0, minor = 1, and puts the
1322      actual major/minor number in the filesize field.  See if this
1323      is an HP/UX cpio archive, and if so fix it.  We have to do this
1324      here because process_copy_in() assumes filesize is always 0
1325      for devices.  */
1326   switch (file_hdr->c_mode & CP_IFMT)
1327     {
1328       case CP_IFCHR:
1329       case CP_IFBLK:
1330 #ifdef CP_IFSOCK
1331       case CP_IFSOCK:
1332 #endif
1333 #ifdef CP_IFIFO
1334       case CP_IFIFO:
1335 #endif
1336         if (file_hdr->c_filesize != 0
1337             && file_hdr->c_rdev_maj == 0
1338             && file_hdr->c_rdev_min == 1)
1339           {
1340             file_hdr->c_rdev_maj = major (file_hdr->c_filesize);
1341             file_hdr->c_rdev_min = minor (file_hdr->c_filesize);
1342             file_hdr->c_filesize = 0;
1343           }
1344         break;
1345       default:
1346         break;
1347     }
1348 }
1349
1350 /* Exchange the bytes of each element of the array of COUNT shorts
1351    starting at PTR.  */
1352
1353 void
1354 swab_array (char *ptr, int count)
1355 {
1356   char tmp;
1357
1358   while (count-- > 0)
1359     {
1360       tmp = *ptr;
1361       *ptr = *(ptr + 1);
1362       ++ptr;
1363       *ptr = tmp;
1364       ++ptr;
1365     }
1366 }
1367
1368 /* Return a safer suffix of FILE_NAME, or "." if it has no safer
1369    suffix.  Check for fully specified file names and other atrocities.  */
1370
1371 static const char *
1372 safer_name_suffix (char const *file_name)
1373 {
1374   char const *p;
1375
1376   /* Skip file system prefixes, leading file name components that contain
1377      "..", and leading slashes.  */
1378
1379   size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (file_name);
1380
1381   for (p = file_name + prefix_len; *p;)
1382     {
1383       if (p[0] == '.' && p[1] == '.' && (ISSLASH (p[2]) || !p[2]))
1384         prefix_len = p + 2 - file_name;
1385
1386       do
1387         {
1388           char c = *p++;
1389           if (ISSLASH (c))
1390             break;
1391         }
1392       while (*p);
1393     }
1394
1395   for (p = file_name + prefix_len; ISSLASH (*p); p++)
1396     continue;
1397   prefix_len = p - file_name;
1398
1399   if (prefix_len)
1400     {
1401       char *prefix = alloca (prefix_len + 1);
1402       memcpy (prefix, file_name, prefix_len);
1403       prefix[prefix_len] = '\0';
1404
1405
1406       error (0, 0, _("Removing leading `%s' from member names"), prefix);
1407     }
1408
1409   if (!*p)
1410     p = ".";
1411
1412   return p;
1413 }
1414
1415 /* Read the collection from standard input and create files
1416    in the file system.  */
1417
1418 void
1419 process_copy_in ()
1420 {
1421   char done = false;            /* True if trailer reached.  */
1422   FILE *tty_in;                 /* Interactive file for rename option.  */
1423   FILE *tty_out;                /* Interactive file for rename option.  */
1424   FILE *rename_in;              /* Batch file for rename option.  */
1425   struct stat file_stat;        /* Output file stat record.  */
1426   struct new_cpio_header file_hdr;      /* Output header information.  */
1427   int in_file_des;              /* Input file descriptor.  */
1428   char skip_file;               /* Flag for use with patterns.  */
1429   int i;                        /* Loop index variable.  */
1430
1431   /* Initialize the copy in.  */
1432   if (pattern_file_name)
1433     {
1434       read_pattern_file ();
1435     }
1436   file_hdr.c_name = NULL;
1437
1438   if (rename_batch_file)
1439     {
1440       rename_in = fopen (rename_batch_file, "r");
1441       if (rename_in == NULL)
1442         {
1443           error (2, errno, TTY_NAME);
1444         }
1445     }
1446   else if (rename_flag)
1447     {
1448       /* Open interactive file pair for rename operation.  */
1449       tty_in = fopen (TTY_NAME, "r");
1450       if (tty_in == NULL)
1451         {
1452           error (2, errno, TTY_NAME);
1453         }
1454       tty_out = fopen (TTY_NAME, "w");
1455       if (tty_out == NULL)
1456         {
1457           error (2, errno, TTY_NAME);
1458         }
1459     }
1460
1461   /* Get date and time if needed for processing the table option.  */
1462   if (table_flag && verbose_flag)
1463     {
1464       time (&current_time);
1465     }
1466
1467   /* Check whether the input file might be a tape.  */
1468   in_file_des = archive_des;
1469   if (_isrmt (in_file_des))
1470     {
1471       input_is_special = 1;
1472       input_is_seekable = 0;
1473     }
1474   else
1475     {
1476       if (fstat (in_file_des, &file_stat))
1477         error (1, errno, _("standard input is closed"));
1478       input_is_special =
1479 #ifdef S_ISBLK
1480         S_ISBLK (file_stat.st_mode) ||
1481 #endif
1482         S_ISCHR (file_stat.st_mode);
1483       input_is_seekable = S_ISREG (file_stat.st_mode);
1484     }
1485   output_is_seekable = true;
1486
1487   /* While there is more input in the collection, process the input.  */
1488   while (!done)
1489     {
1490       swapping_halfwords = swapping_bytes = false;
1491
1492       /* Start processing the next file by reading the header.  */
1493       read_in_header (&file_hdr, in_file_des);
1494
1495 #ifdef DEBUG_CPIO
1496       if (debug_flag)
1497         {
1498           struct new_cpio_header *h;
1499           h = &file_hdr;
1500           fprintf (stderr, 
1501                 "magic = 0%o, ino = %d, mode = 0%o, uid = %d, gid = %d\n",
1502                 h->c_magic, h->c_ino, h->c_mode, h->c_uid, h->c_gid);
1503           fprintf (stderr, 
1504                 "nlink = %d, mtime = %d, filesize = %d, dev_maj = 0x%x\n",
1505                 h->c_nlink, h->c_mtime, h->c_filesize, h->c_dev_maj);
1506           fprintf (stderr, 
1507                 "dev_min = 0x%x, rdev_maj = 0x%x, rdev_min = 0x%x, namesize = %d\n",
1508                 h->c_dev_min, h->c_rdev_maj, h->c_rdev_min, h->c_namesize);
1509           fprintf (stderr, 
1510                 "chksum = %d, name = \"%s\", tar_linkname = \"%s\"\n",
1511                 h->c_chksum, h->c_name, 
1512                 h->c_tar_linkname ? h->c_tar_linkname : "(null)" );
1513
1514         }
1515 #endif
1516       /* Is this the header for the TRAILER file?  */
1517       if (strcmp ("TRAILER!!!", file_hdr.c_name) == 0)
1518         {
1519           done = true;
1520           break;
1521         }
1522
1523       /* Do we have to ignore absolute paths, and if so, does the filename
1524          have an absolute path?  */
1525       if (!abs_paths_flag && file_hdr.c_name && file_hdr.c_name [0])
1526         {
1527           const char *p = safer_name_suffix (file_hdr.c_name);
1528
1529           if (p != file_hdr.c_name)
1530             {
1531               /* Debian hack: file_hrd.c_name is sometimes set to
1532                  point to static memory by code in tar.c.  This
1533                  causes a segfault.  Therefore, memmove is used
1534                  instead of freeing and reallocating.  (Reported by
1535                  Horst Knobloch.)  This bug has been reported to
1536                  "bug-gnu-utils@prep.ai.mit.edu". (99/1/6) -BEM */
1537               (void)memmove (file_hdr.c_name, p, (size_t)(strlen (p) + 1));
1538             }
1539         }
1540
1541       /* Does the file name match one of the given patterns?  */
1542       if (num_patterns <= 0)
1543         skip_file = false;
1544       else
1545         {
1546           skip_file = copy_matching_files;
1547           for (i = 0; i < num_patterns
1548                && skip_file == copy_matching_files; i++)
1549             {
1550               if (fnmatch (save_patterns[i], file_hdr.c_name, 0) == 0)
1551                 skip_file = !copy_matching_files;
1552             }
1553         }
1554
1555       if (skip_file)
1556         {
1557           /* If we're skipping a file with links, there might be other
1558              links that we didn't skip, and this file might have the
1559              data for the links.  If it does, we'll copy in the data
1560              to the links, but not to this file.  */
1561           if (file_hdr.c_nlink > 1 && (archive_format == arf_newascii
1562               || archive_format == arf_crcascii) )
1563             {
1564               if (create_defered_links_to_skipped(&file_hdr, in_file_des) < 0)
1565                 {
1566                   tape_toss_input (in_file_des, file_hdr.c_filesize);
1567                   tape_skip_padding (in_file_des, file_hdr.c_filesize);
1568                 }
1569             }
1570           else
1571             {
1572               tape_toss_input (in_file_des, file_hdr.c_filesize);
1573               tape_skip_padding (in_file_des, file_hdr.c_filesize);
1574             }
1575         }
1576       else if (table_flag)
1577         {
1578           list_file(&file_hdr, in_file_des);
1579         }
1580       else if (append_flag)
1581         {
1582           tape_toss_input (in_file_des, file_hdr.c_filesize);
1583           tape_skip_padding (in_file_des, file_hdr.c_filesize);
1584         }
1585       else if (only_verify_crc_flag)
1586         {
1587 #ifdef CP_IFLNK
1588           if ((file_hdr.c_mode & CP_IFMT) == CP_IFLNK)
1589             {
1590               if (archive_format != arf_tar && archive_format != arf_ustar)
1591                 {
1592                   tape_toss_input (in_file_des, file_hdr.c_filesize);
1593                   tape_skip_padding (in_file_des, file_hdr.c_filesize);
1594                   continue;
1595                 }
1596             }
1597 #endif
1598             crc = 0;
1599             tape_toss_input (in_file_des, file_hdr.c_filesize);
1600             tape_skip_padding (in_file_des, file_hdr.c_filesize);
1601             if (crc != file_hdr.c_chksum)
1602               {
1603                 error (0, 0, _("%s: checksum error (0x%x, should be 0x%x)"),
1604                        file_hdr.c_name, crc, file_hdr.c_chksum);
1605               }
1606          /* Debian hack: -v and -V now work with --only-verify-crc.
1607             (99/11/10) -BEM */
1608             if (verbose_flag)
1609               {
1610                 fprintf (stderr, "%s\n", file_hdr.c_name);
1611               }
1612             if (dot_flag)
1613               {
1614                 fputc ('.', stderr);
1615               }
1616         }
1617       else
1618         {
1619           /* Copy the input file into the directory structure.  */
1620
1621           /* Do we need to rename the file? */
1622           if (rename_flag || rename_batch_file)
1623             {
1624               if (query_rename(&file_hdr, tty_in, tty_out, rename_in) < 0)
1625                 {
1626                   tape_toss_input (in_file_des, file_hdr.c_filesize);
1627                   tape_skip_padding (in_file_des, file_hdr.c_filesize);
1628                   continue;
1629                 }
1630             }
1631
1632           copyin_file(&file_hdr, in_file_des);
1633
1634           if (verbose_flag)
1635             fprintf (stderr, "%s\n", file_hdr.c_name);
1636           if (dot_flag)
1637             fputc ('.', stderr);
1638         }
1639     }
1640
1641   if (dot_flag)
1642     fputc ('\n', stderr);
1643
1644   if (append_flag)
1645     return;
1646
1647   if (archive_format == arf_newascii || archive_format == arf_crcascii)
1648     {
1649       create_final_defers ();
1650     }
1651   if (!quiet_flag)
1652     {
1653       int blocks;
1654       blocks = (input_bytes + io_block_size - 1) / io_block_size;
1655       fprintf (stderr, ngettext ("%d block\n", "%d blocks\n", blocks), blocks);
1656     }
1657 }
1658