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