add a config file for git-buildpackage
[debian/pax] / ar_subs.c
1 /*      $OpenBSD: ar_subs.c,v 1.14 1998/09/20 02:22:21 millert Exp $    */
2 /*      $NetBSD: ar_subs.c,v 1.5 1995/03/21 09:07:06 cgd Exp $  */
3
4 /*-
5  * Copyright (c) 1992 Keith Muller.
6  * Copyright (c) 1992, 1993
7  *      The Regents of the University of California.  All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * Keith Muller of the University of California, San Diego.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *      This product includes software developed by the University of
23  *      California, Berkeley and its contributors.
24  * 4. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)ar_subs.c   8.2 (Berkeley) 4/18/94";
44 #else
45 static char rcsid[] = "$OpenBSD: ar_subs.c,v 1.14 1998/09/20 02:22:21 millert Exp $";
46 #endif
47 #endif /* not lint */
48
49 #include <sys/types.h>
50 #include <sys/time.h>
51 #include <time.h>
52 #include <sys/stat.h>
53 #include <sys/param.h>
54 #include <signal.h>
55 #include <string.h>
56 #include <stdio.h>
57 #include <fcntl.h>
58 #include <errno.h>
59 #include <unistd.h>
60 #include <stdlib.h>
61 #include "pax.h"
62 #include "extern.h"
63
64 static void wr_archive __P((register ARCHD *, int is_app));
65 static int get_arc __P((void));
66 static int next_head __P((register ARCHD *));
67 extern sigset_t s_mask;
68
69 /*
70  * Routines which control the overall operation modes of pax as specified by
71  * the user: list, append, read ...
72  */
73
74 static char hdbuf[BLKMULT];             /* space for archive header on read */
75 u_long flcnt;                           /* number of files processed */
76
77 /*
78  * list()
79  *      list the contents of an archive which match user supplied pattern(s)
80  *      (no pattern matches all).
81  */
82
83 #ifdef __STDC__
84 void
85 list(void)
86 #else
87 void
88 list()
89 #endif
90 {
91         register ARCHD *arcn;
92         register int res;
93         ARCHD archd;
94         time_t now;
95
96         arcn = &archd;
97         /*
98          * figure out archive type; pass any format specific options to the
99          * archive option processing routine; call the format init routine. We
100          * also save current time for ls_list() so we do not make a system
101          * call for each file we need to print. If verbose (vflag) start up
102          * the name and group caches.
103          */
104         if ((get_arc() < 0) || ((*frmt->options)() < 0) ||
105             ((*frmt->st_rd)() < 0))
106                 return;
107
108         if (vflag && ((uidtb_start() < 0) || (gidtb_start() < 0)))
109                 return;
110
111         now = time(NULL);
112
113         /*
114          * step through the archive until the format says it is done
115          */
116         while (next_head(arcn) == 0) {
117                 /*
118                  * check for pattern, and user specified options match.
119                  * When all patterns are matched we are done.
120                  */
121                 if ((res = pat_match(arcn)) < 0)
122                         break;
123
124                 if ((res == 0) && (sel_chk(arcn) == 0)) {
125                         /*
126                          * pattern resulted in a selected file
127                          */
128                         if (pat_sel(arcn) < 0)
129                                 break;
130
131                         /*
132                          * modify the name as requested by the user if name
133                          * survives modification, do a listing of the file
134                          */
135                         if ((res = mod_name(arcn)) < 0)
136                                 break;
137                         if (res == 0)
138                                 ls_list(arcn, now, stdout);
139                 }
140
141                 /*
142                  * skip to next archive format header using values calculated
143                  * by the format header read routine
144                  */
145                 if (rd_skip(arcn->skip + arcn->pad) == 1)
146                         break;
147         }
148
149         /*
150          * all done, let format have a chance to cleanup, and make sure that
151          * the patterns supplied by the user were all matched
152          */
153         (void)(*frmt->end_rd)();
154         (void)sigprocmask(SIG_BLOCK, &s_mask, NULL);
155         ar_close();
156         pat_chk();
157 }
158
159 /*
160  * extract()
161  *      extract the member(s) of an archive as specified by user supplied
162  *      pattern(s) (no patterns extracts all members)
163  */
164
165 #ifdef __STDC__
166 void
167 extract(void)
168 #else
169 void
170 extract()
171 #endif
172 {
173         register ARCHD *arcn;
174         register int res;
175         off_t cnt;
176         ARCHD archd;
177         struct stat sb;
178         int fd;
179         time_t now;
180
181         arcn = &archd;
182         /*
183          * figure out archive type; pass any format specific options to the
184          * archive option processing routine; call the format init routine;
185          * start up the directory modification time and access mode database
186          */
187         if ((get_arc() < 0) || ((*frmt->options)() < 0) ||
188             ((*frmt->st_rd)() < 0) || (dir_start() < 0))
189                 return;
190
191         /*
192          * When we are doing interactive rename, we store the mapping of names
193          * so we can fix up hard links files later in the archive.
194          */
195         if (iflag && (name_start() < 0))
196                 return;
197
198         now = time(NULL);
199
200         /*
201          * step through each entry on the archive until the format read routine
202          * says it is done
203          */
204         while (next_head(arcn) == 0) {
205
206                 /*
207                  * check for pattern, and user specified options match. When
208                  * all the patterns are matched we are done
209                  */
210                 if ((res = pat_match(arcn)) < 0)
211                         break;
212
213                 if ((res > 0) || (sel_chk(arcn) != 0)) {
214                         /*
215                          * file is not selected. skip past any file data and
216                          * padding and go back for the next archive member
217                          */
218                         (void)rd_skip(arcn->skip + arcn->pad);
219                         continue;
220                 }
221
222                 /*
223                  * with -u or -D only extract when the archive member is newer
224                  * than the file with the same name in the file system (nos
225                  * test of being the same type is required).
226                  * NOTE: this test is done BEFORE name modifications as
227                  * specified by pax. this operation can be confusing to the
228                  * user who might expect the test to be done on an existing
229                  * file AFTER the name mod. In honesty the pax spec is probably
230                  * flawed in this respect.
231                  */
232                 if ((uflag || Dflag) && ((lstat(arcn->name, &sb) == 0))) {
233                         if (uflag && Dflag) {
234                                 if ((arcn->sb.st_mtime <= sb.st_mtime) &&
235                                     (arcn->sb.st_ctime <= sb.st_ctime)) {
236                                         (void)rd_skip(arcn->skip + arcn->pad);
237                                         continue;
238                                 }
239                         } else if (Dflag) {
240                                 if (arcn->sb.st_ctime <= sb.st_ctime) {
241                                         (void)rd_skip(arcn->skip + arcn->pad);
242                                         continue;
243                                 }
244                         } else if (arcn->sb.st_mtime <= sb.st_mtime) {
245                                 (void)rd_skip(arcn->skip + arcn->pad);
246                                 continue;
247                         }
248                 }
249
250                 /*
251                  * this archive member is now been selected. modify the name.
252                  */
253                 if ((pat_sel(arcn) < 0) || ((res = mod_name(arcn)) < 0))
254                         break;
255                 if (res > 0) {
256                         /*
257                          * a bad name mod, skip and purge name from link table
258                          */
259                         purg_lnk(arcn);
260                         (void)rd_skip(arcn->skip + arcn->pad);
261                         continue;
262                 }
263
264                 /*
265                  * Non standard -Y and -Z flag. When the exisiting file is
266                  * same age or newer skip
267                  */
268                 if ((Yflag || Zflag) && ((lstat(arcn->name, &sb) == 0))) {
269                         if (Yflag && Zflag) {
270                                 if ((arcn->sb.st_mtime <= sb.st_mtime) &&
271                                     (arcn->sb.st_ctime <= sb.st_ctime)) {
272                                         (void)rd_skip(arcn->skip + arcn->pad);
273                                         continue;
274                                 }
275                         } else if (Yflag) {
276                                 if (arcn->sb.st_ctime <= sb.st_ctime) {
277                                         (void)rd_skip(arcn->skip + arcn->pad);
278                                         continue;
279                                 }
280                         } else if (arcn->sb.st_mtime <= sb.st_mtime) {
281                                 (void)rd_skip(arcn->skip + arcn->pad);
282                                 continue;
283                         }
284                 }
285
286                 if (vflag) {
287                         if (vflag > 1)
288                                 ls_list(arcn, now, listf);
289                         else {
290                                 (void)fputs(arcn->name, listf);
291                                 vfpart = 1;
292                         }
293                 }
294
295                 /*
296                  * if required, chdir around.
297                  */
298                 if ((arcn->pat != NULL) && (arcn->pat->chdname != NULL))
299                         if (chdir(arcn->pat->chdname) != 0)
300                                 syswarn(1, errno, "Cannot chdir to %s",
301                                     arcn->pat->chdname);
302
303                 /*
304                  * all ok, extract this member based on type
305                  */
306                 if ((arcn->type != PAX_REG) && (arcn->type != PAX_CTG)) {
307                         /*
308                          * process archive members that are not regular files.
309                          * throw out padding and any data that might follow the
310                          * header (as determined by the format).
311                          */
312                         if ((arcn->type == PAX_HLK) || (arcn->type == PAX_HRG))
313                                 res = lnk_creat(arcn);
314                         else
315                                 res = node_creat(arcn);
316
317                         (void)rd_skip(arcn->skip + arcn->pad);
318                         if (res < 0)
319                                 purg_lnk(arcn);
320
321                         if (vflag && vfpart) {
322                                 (void)putc('\n', listf);
323                                 vfpart = 0;
324                         }
325                         continue;
326                 }
327                 /*
328                  * we have a file with data here. If we can not create it, skip
329                  * over the data and purge the name from hard link table
330                  */
331                 if ((fd = file_creat(arcn)) < 0) {
332                         (void)rd_skip(arcn->skip + arcn->pad);
333                         purg_lnk(arcn);
334                         continue;
335                 }
336                 /*
337                  * extract the file from the archive and skip over padding and
338                  * any unprocessed data
339                  */
340                 res = (*frmt->rd_data)(arcn, fd, &cnt);
341                 file_close(arcn, fd);
342                 if (vflag && vfpart) {
343                         (void)putc('\n', listf);
344                         vfpart = 0;
345                 }
346                 if (!res)
347                         (void)rd_skip(cnt + arcn->pad);
348
349                 /*
350                  * if required, chdir around.
351                  */
352                 if ((arcn->pat != NULL) && (arcn->pat->chdname != NULL))
353                         if (fchdir(cwdfd) != 0)
354                                 syswarn(1, errno,
355                                     "Can't fchdir to starting directory");
356         }
357
358         /*
359          * all done, restore directory modes and times as required; make sure
360          * all patterns supplied by the user were matched; block off signals
361          * to avoid chance for multiple entry into the cleanup code.
362          */
363         (void)(*frmt->end_rd)();
364         (void)sigprocmask(SIG_BLOCK, &s_mask, NULL);
365         ar_close();
366         proc_dir();
367         pat_chk();
368 }
369
370 /*
371  * wr_archive()
372  *      Write an archive. used in both creating a new archive and appends on
373  *      previously written archive.
374  */
375
376 #ifdef __STDC__
377 static void
378 wr_archive(register ARCHD *arcn, int is_app)
379 #else
380 static void
381 wr_archive(arcn, is_app)
382         register ARCHD *arcn;
383         int is_app;
384 #endif
385 {
386         register int res;
387         register int hlk;
388         register int wr_one;
389         off_t cnt;
390         int (*wrf)();
391         int fd = -1;
392         time_t now;
393
394         /*
395          * if this format supports hard link storage, start up the database
396          * that detects them.
397          */
398         if (((hlk = frmt->hlk) == 1) && (lnk_start() < 0))
399                 return;
400
401         /*
402          * start up the file traversal code and format specific write
403          */
404         if ((ftree_start() < 0) || ((*frmt->st_wr)() < 0))
405                 return;
406         wrf = frmt->wr;
407
408         /*
409          * When we are doing interactive rename, we store the mapping of names
410          * so we can fix up hard links files later in the archive.
411          */
412         if (iflag && (name_start() < 0))
413                 return;
414
415         /*
416          * if this not append, and there are no files, we do no write a trailer
417          */
418         wr_one = is_app;
419
420         now = time(NULL);
421
422         /*
423          * while there are files to archive, process them one at at time
424          */
425         while (next_file(arcn) == 0) {
426                 /*
427                  * check if this file meets user specified options match.
428                  */
429                 if (sel_chk(arcn) != 0)
430                         continue;
431                 fd = -1;
432                 if (uflag) {
433                         /*
434                          * only archive if this file is newer than a file with
435                          * the same name that is already stored on the archive
436                          */
437                         if ((res = chk_ftime(arcn)) < 0)
438                                 break;
439                         if (res > 0)
440                                 continue;
441                 }
442
443                 /*
444                  * this file is considered selected now. see if this is a hard
445                  * link to a file already stored
446                  */
447                 ftree_sel(arcn);
448                 if (hlk && (chk_lnk(arcn) < 0))
449                         break;
450
451                 if ((arcn->type == PAX_REG) || (arcn->type == PAX_HRG) ||
452                     (arcn->type == PAX_CTG)) {
453                         /*
454                          * we will have to read this file. by opening it now we
455                          * can avoid writing a header to the archive for a file
456                          * we were later unable to read (we also purge it from
457                          * the link table).
458                          */
459                         if ((fd = open(arcn->org_name, O_RDONLY, 0)) < 0) {
460                                 syswarn(1,errno, "Unable to open %s to read",
461                                         arcn->org_name);
462                                 purg_lnk(arcn);
463                                 continue;
464                         }
465                 }
466
467                 /*
468                  * Now modify the name as requested by the user
469                  */
470                 if ((res = mod_name(arcn)) < 0) {
471                         /*
472                          * name modification says to skip this file, close the
473                          * file and purge link table entry
474                          */
475                         rdfile_close(arcn, &fd);
476                         purg_lnk(arcn);
477                         break;
478                 }
479
480                 if ((res > 0) || (docrc && (set_crc(arcn, fd) < 0))) {
481                         /*
482                          * unable to obtain the crc we need, close the file,
483                          * purge link table entry 
484                          */
485                         rdfile_close(arcn, &fd);
486                         purg_lnk(arcn);
487                         continue;
488                 }
489
490                 if (vflag) {
491                         if (vflag > 1)
492                                 ls_list(arcn, now, listf);
493                         else {
494                                 (void)fputs(arcn->name, listf);
495                                 vfpart = 1;
496                         }
497                 }
498                 ++flcnt;
499
500                 /*
501                  * looks safe to store the file, have the format specific
502                  * routine write routine store the file header on the archive
503                  */
504                 if ((res = (*wrf)(arcn)) < 0) {
505                         rdfile_close(arcn, &fd);
506                         break;
507                 }
508                 wr_one = 1;
509                 if (res > 0) {
510                         /* 
511                          * format write says no file data needs to be stored
512                          * so we are done messing with this file
513                          */
514                         if (vflag && vfpart) {
515                                 (void)putc('\n', listf);
516                                 vfpart = 0;
517                         }
518                         rdfile_close(arcn, &fd);
519                         continue;
520                 }
521
522                 /*
523                  * Add file data to the archive, quit on write error. if we
524                  * cannot write the entire file contents to the archive we
525                  * must pad the archive to replace the missing file data
526                  * (otherwise during an extract the file header for the file
527                  * which FOLLOWS this one will not be where we expect it to
528                  * be).
529                  */
530                 res = (*frmt->wr_data)(arcn, fd, &cnt);
531                 rdfile_close(arcn, &fd);
532                 if (vflag && vfpart) {
533                         (void)putc('\n', listf);
534                         vfpart = 0;
535                 }
536                 if (res < 0)
537                         break;
538
539                 /*
540                  * pad as required, cnt is number of bytes not written
541                  */
542                 if (((cnt > 0) && (wr_skip(cnt) < 0)) ||
543                     ((arcn->pad > 0) && (wr_skip(arcn->pad) < 0)))
544                         break;
545         }
546
547         /*
548          * tell format to write trailer; pad to block boundry; reset directory
549          * mode/access times, and check if all patterns supplied by the user
550          * were matched. block off signals to avoid chance for multiple entry
551          * into the cleanup code
552          */
553         if (wr_one) {
554                 (*frmt->end_wr)();
555                 wr_fin();
556         }
557         (void)sigprocmask(SIG_BLOCK, &s_mask, NULL);
558         ar_close();
559         if (tflag)
560                 proc_dir();
561         ftree_chk();
562 }
563
564 /*
565  * append()
566  *      Add file to previously written archive. Archive format specified by the
567  *      user must agree with archive. The archive is read first to collect
568  *      modification times (if -u) and locate the archive trailer. The archive
569  *      is positioned in front of the record with the trailer and wr_archive()
570  *      is called to add the new members.
571  *      PAX IMPLEMENTATION DETAIL NOTE:
572  *      -u is implemented by adding the new members to the end of the archive.
573  *      Care is taken so that these do not end up as links to the older 
574  *      version of the same file already stored in the archive. It is expected
575  *      when extraction occurs these newer versions will over-write the older
576  *      ones stored "earlier" in the archive (this may be a bad assumption as
577  *      it depends on the implementation of the program doing the extraction).
578  *      It is really difficult to splice in members without either re-writing
579  *      the entire archive (from the point were the old version was), or having
580  *      assistance of the format specification in terms of a special update
581  *      header that invalidates a previous archive record. The posix spec left
582  *      the method used to implement -u unspecified. This pax is able to
583  *      over write existing files that it creates.
584  */
585
586 #ifdef __STDC__
587 void
588 append(void)
589 #else
590 void
591 append()
592 #endif
593 {
594         register ARCHD *arcn;
595         register int res;
596         ARCHD archd;
597         FSUB *orgfrmt;
598         int udev;
599         off_t tlen;
600
601         arcn = &archd;
602         orgfrmt = frmt;
603
604         /*
605          * Do not allow an append operation if the actual archive is of a
606          * different format than the user specified foramt.
607          */
608         if (get_arc() < 0)
609                 return;
610         if ((orgfrmt != NULL) && (orgfrmt != frmt)) {
611                 paxwarn(1, "Cannot mix current archive format %s with %s",
612                     frmt->name, orgfrmt->name);
613                 return;
614         }
615
616         /*
617          * pass the format any options and start up format
618          */
619         if (((*frmt->options)() < 0) || ((*frmt->st_rd)() < 0))
620                 return;
621
622         /*
623          * if we only are adding members that are newer, we need to save the
624          * mod times for all files we see.
625          */
626         if (uflag && (ftime_start() < 0))
627                 return;
628
629         /*
630          * some archive formats encode hard links by recording the device and
631          * file serial number (inode) but copy the file anyway (multiple times)
632          * to the archive. When we append, we run the risk that newly added
633          * files may have the same device and inode numbers as those recorded
634          * on the archive but during a previous run. If this happens, when the
635          * archive is extracted we get INCORRECT hard links. We avoid this by
636          * remapping the device numbers so that newly added files will never
637          * use the same device number as one found on the archive. remapping
638          * allows new members to safely have links among themselves. remapping
639          * also avoids problems with file inode (serial number) truncations
640          * when the inode number is larger than storage space in the archive
641          * header. See the remap routines for more details.
642          */
643         if ((udev = frmt->udev) && (dev_start() < 0))
644                 return;
645
646         /*
647          * reading the archive may take a long time. If verbose tell the user
648          */
649         if (vflag) {
650                 (void)fprintf(listf,
651                         "%s: Reading archive to position at the end...", argv0);
652                 vfpart = 1;
653         }
654
655         /*
656          * step through the archive until the format says it is done
657          */
658         while (next_head(arcn) == 0) {
659                 /*
660                  * check if this file meets user specified options.
661                  */
662                 if (sel_chk(arcn) != 0) {
663                         if (rd_skip(arcn->skip + arcn->pad) == 1)
664                                 break;
665                         continue;
666                 }
667
668                 if (uflag) {
669                         /*
670                          * see if this is the newest version of this file has
671                          * already been seen, if so skip.
672                          */
673                         if ((res = chk_ftime(arcn)) < 0)
674                                 break;
675                         if (res > 0) {
676                                 if (rd_skip(arcn->skip + arcn->pad) == 1)
677                                         break;
678                                 continue;
679                         }
680                 }
681
682                 /*
683                  * Store this device number. Device numbers seen during the
684                  * read phase of append will cause newly appended files with a
685                  * device number seen in the old part of the archive to be
686                  * remapped to an unused device number.
687                  */
688                 if ((udev && (add_dev(arcn) < 0)) ||
689                     (rd_skip(arcn->skip + arcn->pad) == 1))
690                         break;
691         }
692
693         /*
694          * done, finish up read and get the number of bytes to back up so we
695          * can add new members. The format might have used the hard link table,
696          * purge it.
697          */
698         tlen = (*frmt->end_rd)();
699         lnk_end();
700
701         /*
702          * try to postion for write, if this fails quit. if any error occurs,
703          * we will refuse to write
704          */
705         if (appnd_start(tlen) < 0)
706                 return;
707
708         /*
709          * tell the user we are done reading.
710          */
711         if (vflag && vfpart) {
712                 (void)fputs("done.\n", listf);
713                 vfpart = 0;
714         }
715        
716         /*
717          * go to the writing phase to add the new members
718          */
719         wr_archive(arcn, 1);
720 }
721
722 /*
723  * archive()
724  *      write a new archive
725  */
726
727 #ifdef __STDC__
728 void
729 archive(void)
730 #else
731 void
732 archive()
733 #endif
734 {
735         ARCHD archd;
736
737         /*
738          * if we only are adding members that are newer, we need to save the
739          * mod times for all files; set up for writing; pass the format any
740          * options write the archive
741          */
742         if ((uflag && (ftime_start() < 0)) || (wr_start() < 0))
743                 return;
744         if ((*frmt->options)() < 0)
745                 return;
746
747         wr_archive(&archd, 0);
748 }
749
750 /*
751  * copy()
752  *      copy files from one part of the file system to another. this does not
753  *      use any archive storage. The EFFECT OF THE COPY IS THE SAME as if an
754  *      archive was written and then extracted in the destination directory
755  *      (except the files are forced to be under the destination directory).
756  */
757
758 #ifdef __STDC__
759 void
760 copy(void)
761 #else
762 void
763 copy()
764 #endif
765 {
766         register ARCHD *arcn;
767         register int res;
768         register int fddest;
769         register char *dest_pt;
770         register int dlen;
771         register int drem;
772         int fdsrc = -1;
773         struct stat sb;
774         ARCHD archd;
775         char dirbuf[PAXPATHLEN+1];
776
777         arcn = &archd;
778         /*
779          * set up the destination dir path and make sure it is a directory. We
780          * make sure we have a trailing / on the destination
781          */
782         dlen = l_strncpy(dirbuf, dirptr, sizeof(dirbuf) - 1);
783         dest_pt = dirbuf + dlen;
784         if (*(dest_pt-1) != '/') {
785                 *dest_pt++ = '/';
786                 ++dlen;
787         }
788         *dest_pt = '\0';
789         drem = PAXPATHLEN - dlen;
790
791         if (stat(dirptr, &sb) < 0) {
792                 syswarn(1, errno, "Cannot access destination directory %s",
793                         dirptr);
794                 return;
795         }
796         if (!S_ISDIR(sb.st_mode)) {
797                 paxwarn(1, "Destination is not a directory %s", dirptr);
798                 return;
799         }
800
801         /*
802          * start up the hard link table; file traversal routines and the
803          * modification time and access mode database 
804          */
805         if ((lnk_start() < 0) || (ftree_start() < 0) || (dir_start() < 0))
806                 return;
807
808         /*
809          * When we are doing interactive rename, we store the mapping of names
810          * so we can fix up hard links files later in the archive.
811          */
812         if (iflag && (name_start() < 0))
813                 return;
814
815         /*
816          * set up to cp file trees
817          */
818         cp_start();
819
820         /*
821          * while there are files to archive, process them
822          */
823         while (next_file(arcn) == 0) {
824                 fdsrc = -1;
825
826                 /*
827                  * check if this file meets user specified options
828                  */
829                 if (sel_chk(arcn) != 0)
830                         continue;
831
832                 /*
833                  * if there is already a file in the destination directory with
834                  * the same name and it is newer, skip the one stored on the
835                  * archive.
836                  * NOTE: this test is done BEFORE name modifications as
837                  * specified by pax. this can be confusing to the user who
838                  * might expect the test to be done on an existing file AFTER
839                  * the name mod. In honesty the pax spec is probably flawed in
840                  * this respect
841                  */
842                 if (uflag || Dflag) {
843                         /*
844                          * create the destination name
845                          */
846                         if (*(arcn->name) == '/')
847                                 res = 1;
848                         else
849                                 res = 0;
850                         if ((arcn->nlen - res) > drem) {
851                                 paxwarn(1, "Destination pathname too long %s",
852                                         arcn->name);
853                                 continue;
854                         }
855                         (void)strncpy(dest_pt, arcn->name + res, drem);
856                         dirbuf[PAXPATHLEN] = '\0';
857
858                         /*
859                          * if existing file is same age or newer skip
860                          */
861                         res = lstat(dirbuf, &sb);
862                         *dest_pt = '\0';
863
864                         if (res == 0) {
865                                 if (uflag && Dflag) {
866                                         if ((arcn->sb.st_mtime<=sb.st_mtime) &&
867                                             (arcn->sb.st_ctime<=sb.st_ctime))
868                                                 continue;
869                                 } else if (Dflag) {
870                                         if (arcn->sb.st_ctime <= sb.st_ctime)
871                                                 continue;
872                                 } else if (arcn->sb.st_mtime <= sb.st_mtime)
873                                         continue;
874                         }
875                 }
876
877                 /*
878                  * this file is considered selected. See if this is a hard link
879                  * to a previous file; modify the name as requested by the
880                  * user; set the final destination.
881                  */
882                 ftree_sel(arcn);
883                 if ((chk_lnk(arcn) < 0) || ((res = mod_name(arcn)) < 0))
884                         break;
885                 if ((res > 0) || (set_dest(arcn, dirbuf, dlen) < 0)) {
886                         /*
887                          * skip file, purge from link table
888                          */
889                         purg_lnk(arcn);
890                         continue;
891                 }
892
893                 /*
894                  * Non standard -Y and -Z flag. When the exisiting file is
895                  * same age or newer skip
896                  */
897                 if ((Yflag || Zflag) && ((lstat(arcn->name, &sb) == 0))) {
898                         if (Yflag && Zflag) {
899                                 if ((arcn->sb.st_mtime <= sb.st_mtime) &&
900                                     (arcn->sb.st_ctime <= sb.st_ctime))
901                                         continue;
902                         } else if (Yflag) {
903                                 if (arcn->sb.st_ctime <= sb.st_ctime)
904                                         continue;
905                         } else if (arcn->sb.st_mtime <= sb.st_mtime)
906                                 continue;
907                 }
908
909                 if (vflag) {
910                         (void)fputs(arcn->name, listf);
911                         vfpart = 1;
912                 }
913                 ++flcnt;
914
915                 /*
916                  * try to create a hard link to the src file if requested
917                  * but make sure we are not trying to overwrite ourselves.
918                  */
919                 if (lflag)
920                         res = cross_lnk(arcn);
921                 else
922                         res = chk_same(arcn);
923                 if (res <= 0) {
924                         if (vflag && vfpart) {
925                                 (void)putc('\n', listf);
926                                 vfpart = 0;
927                         }
928                         continue;
929                 }
930
931                 /*
932                  * have to create a new file
933                  */
934                 if ((arcn->type != PAX_REG) && (arcn->type != PAX_CTG)) {
935                         /*
936                          * create a link or special file
937                          */
938                         if ((arcn->type == PAX_HLK) || (arcn->type == PAX_HRG))
939                                 res = lnk_creat(arcn);
940                         else
941                                 res = node_creat(arcn);
942                         if (res < 0)
943                                 purg_lnk(arcn);
944                         if (vflag && vfpart) {
945                                 (void)putc('\n', listf);
946                                 vfpart = 0;
947                         }
948                         continue;
949                 }
950
951                 /*
952                  * have to copy a regular file to the destination directory.
953                  * first open source file and then create the destination file
954                  */
955                 if ((fdsrc = open(arcn->org_name, O_RDONLY, 0)) < 0) {
956                         syswarn(1, errno, "Unable to open %s to read",
957                             arcn->org_name);
958                         purg_lnk(arcn);
959                         continue;
960                 }
961                 if ((fddest = file_creat(arcn)) < 0) {
962                         rdfile_close(arcn, &fdsrc);
963                         purg_lnk(arcn);
964                         continue;
965                 }
966
967                 /*
968                  * copy source file data to the destination file
969                  */
970                 cp_file(arcn, fdsrc, fddest);
971                 file_close(arcn, fddest);
972                 rdfile_close(arcn, &fdsrc);
973
974                 if (vflag && vfpart) {
975                         (void)putc('\n', listf);
976                         vfpart = 0;
977                 }
978         }
979
980         /*
981          * restore directory modes and times as required; make sure all
982          * patterns were selected block off signals to avoid chance for
983          * multiple entry into the cleanup code.
984          */
985         (void)sigprocmask(SIG_BLOCK, &s_mask, NULL);
986         ar_close();
987         proc_dir();
988         ftree_chk();
989 }
990
991 /*
992  * next_head()
993  *      try to find a valid header in the archive. Uses format specific
994  *      routines to extract the header and id the trailer. Trailers may be
995  *      located within a valid header or in an invalid header (the location
996  *      is format specific. The inhead field from the option table tells us
997  *      where to look for the trailer).
998  *      We keep reading (and resyncing) until we get enough contiguous data
999  *      to check for a header. If we cannot find one, we shift by a byte
1000  *      add a new byte from the archive to the end of the buffer and try again.
1001  *      If we get a read error, we throw out what we have (as we must have
1002  *      contiguous data) and start over again.
1003  *      ASSUMED: headers fit within a BLKMULT header.
1004  * Return:
1005  *      0 if we got a header, -1 if we are unable to ever find another one
1006  *      (we reached the end of input, or we reached the limit on retries. see
1007  *      the specs for rd_wrbuf() for more details)
1008  */
1009
1010 #ifdef __STDC__
1011 static int
1012 next_head(register ARCHD *arcn)
1013 #else
1014 static int
1015 next_head(arcn)
1016         register ARCHD *arcn;
1017 #endif
1018 {
1019         register int ret;
1020         register char *hdend;
1021         register int res;
1022         register int shftsz;
1023         register int hsz;
1024         register int in_resync = 0;     /* set when we are in resync mode */
1025         int cnt = 0;                    /* counter for trailer function */
1026         int first = 1;                  /* on 1st read, EOF isn't premature. */
1027
1028         /*
1029          * set up initial conditions, we want a whole frmt->hsz block as we
1030          * have no data yet.
1031          */
1032         res = hsz = frmt->hsz;
1033         hdend = hdbuf;
1034         shftsz = hsz - 1;
1035         for(;;) {
1036                 /*
1037                  * keep looping until we get a contiguous FULL buffer
1038                  * (frmt->hsz is the proper size)
1039                  */
1040                 for (;;) {
1041                         if ((ret = rd_wrbuf(hdend, res)) == res)
1042                                 break;
1043
1044                         /*
1045                          * If we read 0 bytes (EOF) from an archive when we
1046                          * expect to find a header, we have stepped upon
1047                          * an archive without the customary block of zeroes
1048                          * end marker.  It's just stupid to error out on
1049                          * them, so exit gracefully.
1050                          */
1051                         if (first && ret == 0)
1052                                 return(-1);
1053                         first = 0;
1054
1055                         /*
1056                          * some kind of archive read problem, try to resync the
1057                          * storage device, better give the user the bad news.
1058                          */
1059                         if ((ret == 0) || (rd_sync() < 0)) {
1060                                 paxwarn(1,"Premature end of file on archive read");
1061                                 return(-1);
1062                         }
1063                         if (!in_resync) {
1064                                 if (act == APPND) {
1065                                         paxwarn(1,
1066                                           "Archive I/O error, cannot continue");
1067                                         return(-1);
1068                                 }
1069                                 paxwarn(1,"Archive I/O error. Trying to recover.");
1070                                 ++in_resync;
1071                         }
1072
1073                         /*
1074                          * oh well, throw it all out and start over
1075                          */
1076                         res = hsz;
1077                         hdend = hdbuf;
1078                 }
1079
1080                 /*
1081                  * ok we have a contiguous buffer of the right size. Call the
1082                  * format read routine. If this was not a valid header and this
1083                  * format stores trailers outside of the header, call the
1084                  * format specific trailer routine to check for a trailer. We
1085                  * have to watch out that we do not mis-identify file data or
1086                  * block padding as a header or trailer. Format specific
1087                  * trailer functions must NOT check for the trailer while we
1088                  * are running in resync mode. Some trailer functions may tell
1089                  * us that this block cannot contain a valid header either, so
1090                  * we then throw out the entire block and start over.
1091                  */
1092                 if ((*frmt->rd)(arcn, hdbuf) == 0)
1093                         break;
1094
1095                 if (!frmt->inhead) {
1096                         /*
1097                          * this format has trailers outside of valid headers
1098                          */
1099                         if ((ret = (*frmt->trail)(hdbuf,in_resync,&cnt)) == 0){
1100                                 /*
1101                                  * valid trailer found, drain input as required
1102                                  */
1103                                 ar_drain();
1104                                 return(-1);
1105                         }
1106
1107                         if (ret == 1) {
1108                                 /*
1109                                  * we are in resync and we were told to throw
1110                                  * the whole block out because none of the
1111                                  * bytes in this block can be used to form a
1112                                  * valid header
1113                                  */
1114                                 res = hsz;
1115                                 hdend = hdbuf;
1116                                 continue;
1117                         }
1118                 }
1119
1120                 /*
1121                  * Brute force section.
1122                  * not a valid header. We may be able to find a header yet. So
1123                  * we shift over by one byte, and set up to read one byte at a
1124                  * time from the archive and place it at the end of the buffer.
1125                  * We will keep moving byte at a time until we find a header or
1126                  * get a read error and have to start over.
1127                  */
1128                 if (!in_resync) {
1129                         if (act == APPND) {
1130                                 paxwarn(1,"Unable to append, archive header flaw");
1131                                 return(-1);
1132                         }
1133                         paxwarn(1,"Invalid header, starting valid header search.");
1134                         ++in_resync;
1135                 }
1136                 memmove(hdbuf, hdbuf+1, shftsz);
1137                 res = 1;
1138                 hdend = hdbuf + shftsz;
1139         }
1140
1141         /*
1142          * ok got a valid header, check for trailer if format encodes it in the
1143          * the header. NOTE: the parameters are different than trailer routines
1144          * which encode trailers outside of the header!
1145          */
1146         if (frmt->inhead && ((*frmt->trail)(arcn) == 0)) {
1147                 /*
1148                  * valid trailer found, drain input as required
1149                  */
1150                 ar_drain();
1151                 return(-1);
1152         }
1153
1154         ++flcnt;
1155         return(0);
1156 }
1157
1158 /*
1159  * get_arc()
1160  *      Figure out what format an archive is. Handles archive with flaws by
1161  *      brute force searches for a legal header in any supported format. The
1162  *      format id routines have to be careful to NOT mis-identify a format.
1163  *      ASSUMED: headers fit within a BLKMULT header.
1164  * Return:
1165  *      0 if archive found -1 otherwise
1166  */
1167
1168 #ifdef __STDC__
1169 static int
1170 get_arc(void)
1171 #else
1172 static int
1173 get_arc()
1174 #endif
1175 {
1176         register int i;
1177         register int hdsz = 0;
1178         register int res;
1179         register int minhd = BLKMULT;
1180         char *hdend;
1181         int notice = 0;
1182
1183         /*
1184          * find the smallest header size in all archive formats and then set up
1185          * to read the archive.
1186          */
1187         for (i = 0; ford[i] >= 0; ++i) {
1188                 if (fsub[ford[i]].hsz < minhd)
1189                         minhd = fsub[ford[i]].hsz;
1190         }
1191         if (rd_start() < 0)
1192                 return(-1);
1193         res = BLKMULT;
1194         hdsz = 0;
1195         hdend = hdbuf;
1196         for(;;) {
1197                 for (;;) {
1198                         /*
1199                          * fill the buffer with at least the smallest header
1200                          */
1201                         i = rd_wrbuf(hdend, res);
1202                         if (i > 0)
1203                                 hdsz += i;
1204                         if (hdsz >= minhd)
1205                                 break;
1206
1207                         /*
1208                          * if we cannot recover from a read error quit
1209                          */
1210                         if ((i == 0) || (rd_sync() < 0))
1211                                 goto out;
1212
1213                         /*
1214                          * when we get an error none of the data we already
1215                          * have can be used to create a legal header (we just
1216                          * got an error in the middle), so we throw it all out
1217                          * and refill the buffer with fresh data.
1218                          */
1219                         res = BLKMULT;
1220                         hdsz = 0;
1221                         hdend = hdbuf;
1222                         if (!notice) {
1223                                 if (act == APPND)
1224                                         return(-1);
1225                                 paxwarn(1,"Cannot identify format. Searching...");
1226                                 ++notice;
1227                         }
1228                 }
1229
1230                 /*
1231                  * we have at least the size of the smallest header in any
1232                  * archive format. Look to see if we have a match. The array
1233                  * ford[] is used to specify the header id order to reduce the
1234                  * chance of incorrectly id'ing a valid header (some formats
1235                  * may be subsets of each other and the order would then be
1236                  * important).
1237                  */
1238                 for (i = 0; ford[i] >= 0; ++i) {
1239                         if ((*fsub[ford[i]].id)(hdbuf, hdsz) < 0)
1240                                 continue;
1241                         frmt = &(fsub[ford[i]]);
1242                         /* 
1243                          * yuck, to avoid slow special case code in the extract
1244                          * routines, just push this header back as if it was
1245                          * not seen. We have left extra space at start of the
1246                          * buffer for this purpose. This is a bit ugly, but
1247                          * adding all the special case code is far worse.
1248                          */
1249                         pback(hdbuf, hdsz);
1250                         return(0);
1251                 }
1252
1253                 /*
1254                  * We have a flawed archive, no match. we start searching, but
1255                  * we never allow additions to flawed archives
1256                  */
1257                 if (!notice) {
1258                         if (act == APPND)
1259                                 return(-1);
1260                         paxwarn(1, "Cannot identify format. Searching...");
1261                         ++notice;
1262                 }
1263
1264                 /*
1265                  * brute force search for a header that we can id.
1266                  * we shift through byte at a time. this is slow, but we cannot
1267                  * determine the nature of the flaw in the archive in a
1268                  * portable manner
1269                  */
1270                 if (--hdsz > 0) {
1271                         memmove(hdbuf, hdbuf+1, hdsz);
1272                         res = BLKMULT - hdsz;
1273                         hdend = hdbuf + hdsz;
1274                 } else {
1275                         res = BLKMULT;
1276                         hdend = hdbuf;
1277                         hdsz = 0;
1278                 }
1279         }
1280
1281     out:
1282         /*
1283          * we cannot find a header, bow, apologize and quit
1284          */
1285         paxwarn(1, "Sorry, unable to determine archive format.");
1286         return(-1);
1287 }