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