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