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