xref: /original-bsd/old/tar/tar.c (revision a3087256)
1 /*-
2  * Copyright (c) 1991 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.proprietary.c%
6  */
7 
8 #ifndef lint
9 char copyright[] =
10 "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
11  All rights reserved.\n";
12 #endif /* not lint */
13 
14 #ifndef lint
15 static char sccsid[] = "@(#)tar.c	5.18 (Berkeley) 06/01/92";
16 #endif /* not lint */
17 
18 /*
19  * Tape Archival Program
20  */
21 #include <sys/param.h>
22 #include <sys/stat.h>
23 #include <sys/ioctl.h>
24 #include <sys/mtio.h>
25 #include <sys/time.h>
26 #include <dirent.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #include "pathnames.h"
36 
37 #define TBLOCK	512
38 #define NBLOCK	20
39 #define NAMSIZ	100
40 
41 #define ARGV 0
42 #define PUTFILE 1
43 
44 #define	writetape(b)	writetbuf(b, 1)
45 #define	min(a,b)  ((a) < (b) ? (a) : (b))
46 #define	max(a,b)  ((a) > (b) ? (a) : (b))
47 
48 union hblock {
49 	char dummy[TBLOCK];
50 	struct header {
51 		char name[NAMSIZ];
52 		char mode[8];
53 		char uid[8];
54 		char gid[8];
55 		char size[12];
56 		char mtime[12];
57 		char chksum[8];
58 		char linkflag;
59 		char linkname[NAMSIZ];
60 	} dbuf;
61 };
62 
63 struct linkbuf {
64 	ino_t	inum;
65 	dev_t	devnum;
66 	int	count;
67 	char	pathname[NAMSIZ];
68 	struct	linkbuf *nextp;
69 };
70 
71 union	hblock dblock;
72 union	hblock *tbuf;
73 struct	linkbuf *ihead;
74 struct	stat stbuf;
75 
76 int	rflag;
77 int	sflag;
78 int	xflag;
79 int	vflag;
80 int	tflag;
81 int	cflag;
82 int	mflag;
83 int	fflag;
84 int	iflag;
85 int	oflag;
86 int	pflag;
87 int	wflag;
88 int	hflag;
89 int     Hflag;
90 int	Bflag;
91 int	Fflag;
92 
93 int	mt;
94 int	term;
95 int	chksum;
96 int	recno;
97 int	first;
98 int	prtlinkerr;
99 int	freemem = 1;
100 int	nblock = 0;
101 void	onintr(), onquit(), onhup();
102 #ifdef notdef
103 void	onterm();
104 #endif
105 
106 daddr_t	low;
107 daddr_t	high;
108 daddr_t	bsrch();
109 
110 FILE	*vfile = stdout;
111 FILE	*tfile;
112 char	tname[] = _PATH_TMP;
113 char	*usefile;
114 char	magtape[] = _PATH_MAGTAPE;
115 char	*cwd();
116 char	*getmem();
117 
118 extern int errno;
119 
120 main(argc, argv)
121 	int argc;
122 	char **argv;
123 {
124 	char *cp;
125 
126 	if (argc < 2)
127 		usage();
128 
129 	tfile = NULL;
130 	usefile =  magtape;
131 	argv[argc] = 0;
132 	argv++;
133 	for (cp = *argv++; *cp; cp++)
134 		switch(*cp) {
135 
136 		case 'H':
137 			Hflag++;
138 			break;
139 		case 'f':
140 			if (*argv == 0) {
141 				fprintf(stderr,
142 			"tar: tapefile must be specified with 'f' option\n");
143 				usage();
144 			}
145 			usefile = *argv++;
146 			fflag++;
147 			break;
148 
149 		case 'c':
150 			cflag++;
151 			rflag++;
152 			break;
153 
154 		case 'o':
155 			oflag++;
156 			break;
157 
158 		case 'p':
159 			pflag++;
160 			break;
161 
162 		case 'u':
163 			(void)mktemp(tname);
164 			if ((tfile = fopen(tname, "w")) == NULL) {
165 				fprintf(stderr,
166 				 "tar: cannot create temporary file (%s)\n",
167 				 tname);
168 				done(1);
169 			}
170 			fprintf(tfile, "!!!!!/!/!/!/!/!/!/! 000\n");
171 			/*FALL THRU*/
172 
173 		case 'r':
174 			rflag++;
175 			break;
176 
177 		case 's':
178 			sflag++;
179 			break;
180 
181 		case 'v':
182 			vflag++;
183 			break;
184 
185 		case 'w':
186 			wflag++;
187 			break;
188 
189 		case 'x':
190 			xflag++;
191 			break;
192 
193 		case 't':
194 			tflag++;
195 			break;
196 
197 		case 'm':
198 			mflag++;
199 			break;
200 
201 		case '-':
202 			break;
203 
204 		case '0':
205 		case '1':
206 		case '4':
207 		case '5':
208 		case '7':
209 		case '8':
210 			magtape[8] = *cp;
211 			usefile = magtape;
212 			break;
213 
214 		case 'b':
215 			if (*argv == 0) {
216 				fprintf(stderr,
217 			"tar: blocksize must be specified with 'b' option\n");
218 				usage();
219 			}
220 			nblock = atoi(*argv);
221 			if (nblock <= 0) {
222 				fprintf(stderr,
223 				    "tar: invalid blocksize \"%s\"\n", *argv);
224 				done(1);
225 			}
226 			argv++;
227 			break;
228 
229 		case 'l':
230 			prtlinkerr++;
231 			break;
232 
233 		case 'h':
234 			hflag++;
235 			break;
236 
237 		case 'i':
238 			iflag++;
239 			break;
240 
241 		case 'B':
242 			Bflag++;
243 			break;
244 
245 		case 'F':
246 			Fflag++;
247 			break;
248 
249 		default:
250 			fprintf(stderr, "tar: %c: unknown option\n", *cp);
251 			usage();
252 		}
253 
254 	if (!rflag && !xflag && !tflag)
255 		usage();
256 	if (rflag) {
257 		if (cflag && tfile != NULL)
258 			usage();
259 		if (signal(SIGINT, SIG_IGN) != SIG_IGN)
260 			(void) signal(SIGINT, onintr);
261 		if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
262 			(void) signal(SIGHUP, onhup);
263 		if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
264 			(void) signal(SIGQUIT, onquit);
265 #ifdef notdef
266 		if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
267 			(void) signal(SIGTERM, onterm);
268 #endif
269 		mt = openmt(usefile, 1);
270 		dorep(argv);
271 		done(0);
272 	}
273 	mt = openmt(usefile, 0);
274 	if (xflag)
275 		doxtract(argv);
276 	else
277 		dotable(argv);
278 	done(0);
279 }
280 
281 usage()
282 {
283 	fprintf(stderr,
284 "tar: usage: tar -{txru}[cvfblmhopwBi] [tapefile] [blocksize] file1 file2...\n");
285 	done(1);
286 }
287 
288 int
289 openmt(tape, writing)
290 	char *tape;
291 	int writing;
292 {
293 	if (strcmp(tape, "-") == 0) {
294 		/*
295 		 * Read from standard input or write to standard output.
296 		 */
297 		if (writing) {
298 			if (cflag == 0) {
299 				fprintf(stderr,
300 			 "tar: can only create standard output archives\n");
301 				done(1);
302 			}
303 			vfile = stderr;
304 			setlinebuf(vfile);
305 			mt = dup(1);
306 		} else {
307 			mt = dup(0);
308 			Bflag++;
309 		}
310 	} else {
311 		/*
312 		 * Use file or tape on local machine.
313 		 */
314 		if (writing) {
315 			if (cflag)
316 				mt = open(tape, O_RDWR|O_CREAT|O_TRUNC, 0666);
317 			else
318 				mt = open(tape, O_RDWR);
319 		} else
320 			mt = open(tape, O_RDONLY);
321 		if (mt < 0) {
322 			fprintf(stderr, "tar: %s: %s\n", tape, strerror(errno));
323 			done(1);
324 		}
325 	}
326 	return(mt);
327 }
328 
329 dorep(argv)
330 	char *argv[];
331 {
332 	register char *cp, *cp2;
333 	char *parent, *wdir;
334 
335 	if (!cflag) {
336 		getdir();
337 		do {
338 			passtape();
339 			if (term)
340 				done(0);
341 			getdir();
342 		} while (!endtape());
343 		backtape();
344 		if (tfile != NULL) {
345 			char buf[200];
346 
347 			(void)sprintf(buf,
348 "sort +0 -1 +1nr %s -o %s; awk '$1 != prev {print; prev=$1}' %s >%sX; mv %sX %s",
349 				tname, tname, tname, tname, tname, tname);
350 			fflush(tfile);
351 			system(buf);
352 			freopen(tname, "r", tfile);
353 			fstat(fileno(tfile), &stbuf);
354 			high = stbuf.st_size;
355 		}
356 	}
357 
358 	wdir = cwd();
359 	while (*argv && ! term) {
360 		cp2 = *argv;
361 		if (!strcmp(cp2, "-C") && argv[1]) {
362 			argv++;
363 			if (chdir(*argv) < 0) {
364 				fprintf(stderr,
365 				    "tar: can't change directories to %s: %s\n",
366 				    *argv, strerror(errno));
367 			} else {
368 				free(wdir);
369 				wdir = cwd();
370 			}
371 			argv++;
372 			continue;
373 		}
374 		parent = wdir;
375 		for (cp = *argv; *cp; cp++)
376 			if (*cp == '/')
377 				cp2 = cp;
378 		if (cp2 != *argv) {
379 			*cp2 = '\0';
380 			if (chdir(*argv) < 0) {
381 				fprintf(stderr,
382 				    "tar: can't change directories to %s: %s\n",
383 				    *argv, strerror(errno));
384 				continue;
385 			}
386 			parent = cwd();
387 			*cp2 = '/';
388 			cp2++;
389 		}
390 		putfile(*argv++, cp2, parent, ARGV);
391 		if (chdir(wdir) < 0)
392 			fprintf(stderr, "tar: cannot change back?: %s: %s\n",
393 			    wdir, strerror(errno));
394 	}
395 	putempty();
396 	putempty();
397 	flushtape();
398 	if (prtlinkerr == 0)
399 		return;
400 	for (; ihead != NULL; ihead = ihead->nextp) {
401 		if (ihead->count == 0)
402 			continue;
403 		fprintf(stderr, "tar: missing links to %s\n", ihead->pathname);
404 	}
405 }
406 
407 endtape()
408 {
409 	return (dblock.dbuf.name[0] == '\0');
410 }
411 
412 getdir()
413 {
414 	register struct stat *sp;
415 	int i;
416 
417 top:
418 	readtape((char *)&dblock);
419 	if (dblock.dbuf.name[0] == '\0')
420 		return;
421 	sp = &stbuf;
422 	sscanf(dblock.dbuf.mode, "%o", &i);
423 	sp->st_mode = i;
424 	sscanf(dblock.dbuf.uid, "%o", &i);
425 	sp->st_uid = i;
426 	sscanf(dblock.dbuf.gid, "%o", &i);
427 	sp->st_gid = i;
428 	sscanf(dblock.dbuf.size, "%lo", &sp->st_size);
429 	sscanf(dblock.dbuf.mtime, "%lo", &sp->st_mtime);
430 	sscanf(dblock.dbuf.chksum, "%o", &chksum);
431 	if (chksum != (i = checksum())) {
432 		fprintf(stderr, "tar: directory checksum error (%d != %d)\n",
433 		    chksum, i);
434 		if (iflag)
435 			goto top;
436 		done(2);
437 	}
438 	/* strip off leading "/" if present */
439 	if (sflag && dblock.dbuf.name[0] == '/') {
440 		register char *cp1, *cp2;
441 		for (cp1 = cp2 = dblock.dbuf.name; *cp2 && *cp2 == '/'; ++cp2);
442 		if (!*cp2)
443 			goto top;
444 		while (*cp1++ = *cp2++);
445 	}
446 	if (tfile != NULL)
447 		fprintf(tfile, "%s %s\n", dblock.dbuf.name, dblock.dbuf.mtime);
448 }
449 
450 passtape()
451 {
452 	long blocks;
453 	char *bufp;
454 
455 	if (dblock.dbuf.linkflag == '1')
456 		return;
457 	blocks = stbuf.st_size;
458 	blocks += TBLOCK-1;
459 	blocks /= TBLOCK;
460 
461 	while (blocks-- > 0)
462 		(void) readtbuf(&bufp, TBLOCK);
463 }
464 
465 putfile(longname, shortname, parent, source)
466 	char *longname;
467 	char *shortname;
468 	char *parent;
469 {
470 	int infile = 0;
471 	long blocks;
472 	char buf[TBLOCK];
473 	char *bigbuf;
474 	register char *cp;
475 	struct dirent *dp;
476 	DIR *dirp;
477 	register int i;
478 	long l;
479 	char newparent[NAMSIZ+64];
480 	int	maxread;
481 	int	hint;		/* amount to write to get "in sync" */
482 
483 	if (hflag || (Hflag && source == ARGV))
484 		i = stat(shortname, &stbuf);
485 	else
486 		i = lstat(shortname, &stbuf);
487 
488 	if (i < 0) {
489 		fprintf(stderr, "tar: %s: %s\n", longname, strerror(errno));
490 		return;
491 	}
492 	if (tfile != NULL && checkupdate(longname) == 0)
493 		return;
494 	if (checkw('r', longname) == 0)
495 		return;
496 	if (Fflag && checkf(shortname, stbuf.st_mode, Fflag) == 0)
497 		return;
498 
499 	switch (stbuf.st_mode & S_IFMT) {
500 	case S_IFDIR:
501 		for (i = 0, cp = buf; *cp++ = longname[i++];)
502 			;
503 		*--cp = '/';
504 		*++cp = 0  ;
505 		if (!oflag) {
506 			if ((cp - buf) >= NAMSIZ) {
507 				fprintf(stderr, "tar: %s: file name too long\n",
508 				    longname);
509 				return;
510 			}
511 			stbuf.st_size = 0;
512 			tomodes(&stbuf);
513 			strcpy(dblock.dbuf.name,buf);
514 			(void)sprintf(dblock.dbuf.chksum, "%6o", checksum());
515 			(void) writetape((char *)&dblock);
516 		}
517 		(void)sprintf(newparent, "%s/%s", parent, shortname);
518 		if (chdir(shortname) < 0) {
519 			fprintf(stderr, "tar: chdir %s: %s\n",
520 			    shortname, strerror(errno));
521 			return;
522 		}
523 		if ((dirp = opendir(".")) == NULL) {
524 			fprintf(stderr, "tar: %s: directory read error\n",
525 			    longname);
526 			if (chdir(parent) < 0) {
527 				fprintf(stderr,
528 				    "tar: cannot change back?: %s: %s\n",
529 				    parent, strerror(errno));
530 			}
531 			return;
532 		}
533 		while ((dp = readdir(dirp)) != NULL && !term) {
534 			if (!strcmp(".", dp->d_name) ||
535 			    !strcmp("..", dp->d_name))
536 				continue;
537 			strcpy(cp, dp->d_name);
538 			l = telldir(dirp);
539 			closedir(dirp);
540 			putfile(buf, cp, newparent, PUTFILE);
541 			dirp = opendir(".");
542 			seekdir(dirp, l);
543 		}
544 		closedir(dirp);
545 		if (chdir(parent) < 0) {
546 			fprintf(stderr,
547 			    "tar: cannot change back?: %s: %s\n",
548 			    parent, strerror(errno));
549 		}
550 		break;
551 
552 	case S_IFLNK:
553 		tomodes(&stbuf);
554 		if (strlen(longname) >= NAMSIZ) {
555 			fprintf(stderr, "tar: %s: file name too long\n",
556 			    longname);
557 			return;
558 		}
559 		strcpy(dblock.dbuf.name, longname);
560 		if (stbuf.st_size + 1 >= NAMSIZ) {
561 			fprintf(stderr, "tar: %s: symbolic link too long\n",
562 			    longname);
563 			return;
564 		}
565 		i = readlink(shortname, dblock.dbuf.linkname, NAMSIZ - 1);
566 		if (i < 0) {
567 			fprintf(stderr,
568 			    "tar: can't read symbolic link %s: %s\n",
569 			    longname, strerror(errno));
570 			return;
571 		}
572 		dblock.dbuf.linkname[i] = '\0';
573 		dblock.dbuf.linkflag = '2';
574 		if (vflag)
575 			fprintf(vfile, "a %s symbolic link to %s\n",
576 			    longname, dblock.dbuf.linkname);
577 		(void)sprintf(dblock.dbuf.size, "%11lo", 0L);
578 		(void)sprintf(dblock.dbuf.chksum, "%6o", checksum());
579 		(void) writetape((char *)&dblock);
580 		break;
581 
582 	case S_IFREG:
583 		if ((infile = open(shortname, 0)) < 0) {
584 			fprintf(stderr, "tar: %s: %s\n",
585 			    longname, strerror(errno));
586 			return;
587 		}
588 		tomodes(&stbuf);
589 		if (strlen(longname) >= NAMSIZ) {
590 			fprintf(stderr, "tar: %s: file name too long\n",
591 			    longname);
592 			close(infile);
593 			return;
594 		}
595 		strcpy(dblock.dbuf.name, longname);
596 		if (stbuf.st_nlink > 1) {
597 			struct linkbuf *lp;
598 			int found = 0;
599 
600 			for (lp = ihead; lp != NULL; lp = lp->nextp)
601 				if (lp->inum == stbuf.st_ino &&
602 				    lp->devnum == stbuf.st_dev) {
603 					found++;
604 					break;
605 				}
606 			if (found) {
607 				strcpy(dblock.dbuf.linkname, lp->pathname);
608 				dblock.dbuf.linkflag = '1';
609 				(void)sprintf(dblock.dbuf.chksum, "%6o", checksum());
610 				(void) writetape( (char *) &dblock);
611 				if (vflag)
612 					fprintf(vfile, "a %s link to %s\n",
613 					    longname, lp->pathname);
614 				lp->count--;
615 				close(infile);
616 				return;
617 			}
618 			lp = (struct linkbuf *) getmem(sizeof(*lp));
619 			if (lp != NULL) {
620 				lp->nextp = ihead;
621 				ihead = lp;
622 				lp->inum = stbuf.st_ino;
623 				lp->devnum = stbuf.st_dev;
624 				lp->count = stbuf.st_nlink - 1;
625 				strcpy(lp->pathname, longname);
626 			}
627 		}
628 		blocks = (stbuf.st_size + (TBLOCK-1)) / TBLOCK;
629 		if (vflag)
630 			fprintf(vfile, "a %s %ld blocks\n", longname, blocks);
631 		(void)sprintf(dblock.dbuf.chksum, "%6o", checksum());
632 		hint = writetape((char *)&dblock);
633 		maxread = max(stbuf.st_blksize, (nblock * TBLOCK));
634 		if ((bigbuf = malloc((unsigned)maxread)) == 0) {
635 			maxread = TBLOCK;
636 			bigbuf = buf;
637 		}
638 
639 		while ((i = read(infile, bigbuf, min((hint*TBLOCK), maxread))) > 0
640 		  && blocks > 0) {
641 		  	register int nblks;
642 
643 			nblks = ((i-1)/TBLOCK)+1;
644 		  	if (nblks > blocks)
645 		  		nblks = blocks;
646 			hint = writetbuf(bigbuf, nblks);
647 			blocks -= nblks;
648 		}
649 		close(infile);
650 		if (bigbuf != buf)
651 			free(bigbuf);
652 		if (i < 0) {
653 			fprintf(stderr, "tar: Read error on %s: %s\n",
654 			    longname, strerror(errno));
655 		} else if (blocks != 0 || i != 0)
656 			fprintf(stderr, "tar: %s: file changed size\n",
657 			    longname);
658 		while (--blocks >=  0)
659 			putempty();
660 		break;
661 
662 	default:
663 		fprintf(stderr, "tar: %s is not a file. Not dumped\n",
664 		    longname);
665 		break;
666 	}
667 }
668 
669 doxtract(argv)
670 	char *argv[];
671 {
672 	long blocks, bytes;
673 	int ofile, i;
674 
675 	for (;;) {
676 		if ((i = wantit(argv)) == 0)
677 			continue;
678 		if (i == -1)
679 			break;		/* end of tape */
680 		if (checkw('x', dblock.dbuf.name) == 0) {
681 			passtape();
682 			continue;
683 		}
684 		if (Fflag) {
685 			char *s;
686 
687 			if ((s = rindex(dblock.dbuf.name, '/')) == 0)
688 				s = dblock.dbuf.name;
689 			else
690 				s++;
691 			if (checkf(s, stbuf.st_mode, Fflag) == 0) {
692 				passtape();
693 				continue;
694 			}
695 		}
696 		if (checkdir(dblock.dbuf.name)) {	/* have a directory */
697 			if (mflag == 0)
698 				dodirtimes(&dblock);
699 			continue;
700 		}
701 		if (dblock.dbuf.linkflag == '2') {	/* symlink */
702 			/*
703 			 * only unlink non directories or empty
704 			 * directories
705 			 */
706 			if (rmdir(dblock.dbuf.name) < 0) {
707 				if (errno == ENOTDIR)
708 					unlink(dblock.dbuf.name);
709 			}
710 			if (symlink(dblock.dbuf.linkname, dblock.dbuf.name)<0) {
711 				fprintf(stderr,
712 				    "tar: %s: symbolic link failed: %s\n",
713 				    dblock.dbuf.name, strerror(errno));
714 				continue;
715 			}
716 			if (vflag)
717 				fprintf(vfile, "x %s symbolic link to %s\n",
718 				    dblock.dbuf.name, dblock.dbuf.linkname);
719 #ifdef notdef
720 			/* ignore alien orders */
721 			chown(dblock.dbuf.name, stbuf.st_uid, stbuf.st_gid);
722 			if (mflag == 0)
723 				setimes(dblock.dbuf.name, stbuf.st_mtime);
724 			if (pflag)
725 				chmod(dblock.dbuf.name, stbuf.st_mode & 07777);
726 #endif
727 			continue;
728 		}
729 		if (dblock.dbuf.linkflag == '1') {	/* regular link */
730 			/*
731 			 * only unlink non directories or empty
732 			 * directories
733 			 */
734 			if (rmdir(dblock.dbuf.name) < 0) {
735 				if (errno == ENOTDIR)
736 					unlink(dblock.dbuf.name);
737 			}
738 			if (link(dblock.dbuf.linkname, dblock.dbuf.name) < 0) {
739 				fprintf(stderr,
740 				    "tar: can't link %s to %s: %s\n",
741 				    dblock.dbuf.name, dblock.dbuf.linkname,
742 				    strerror(errno));
743 				continue;
744 			}
745 			if (vflag)
746 				fprintf(vfile, "%s linked to %s\n",
747 				    dblock.dbuf.name, dblock.dbuf.linkname);
748 			continue;
749 		}
750 		if ((ofile = creat(dblock.dbuf.name,stbuf.st_mode&0xfff)) < 0) {
751 			fprintf(stderr, "tar: can't create %s: %s\n",
752 			    dblock.dbuf.name, strerror(errno));
753 			passtape();
754 			continue;
755 		}
756 		chown(dblock.dbuf.name, stbuf.st_uid, stbuf.st_gid);
757 		blocks = ((bytes = stbuf.st_size) + TBLOCK-1)/TBLOCK;
758 		if (vflag)
759 			fprintf(vfile, "x %s, %ld bytes, %ld tape blocks\n",
760 			    dblock.dbuf.name, bytes, blocks);
761 		for (; blocks > 0;) {
762 			register int nread;
763 			char	*bufp;
764 			register int nwant;
765 
766 			nwant = NBLOCK*TBLOCK;
767 			if (nwant > (blocks*TBLOCK))
768 				nwant = (blocks*TBLOCK);
769 			nread = readtbuf(&bufp, nwant);
770 			if (write(ofile, bufp, (int)min(nread, bytes)) < 0) {
771 				fprintf(stderr,
772 				    "tar: %s: HELP - extract write error: %s\n",
773 				    dblock.dbuf.name, strerror(errno));
774 				done(2);
775 			}
776 			bytes -= nread;
777 			blocks -= (((nread-1)/TBLOCK)+1);
778 		}
779 		close(ofile);
780 		if (mflag == 0)
781 			setimes(dblock.dbuf.name, stbuf.st_mtime);
782 		if (pflag)
783 			chmod(dblock.dbuf.name, stbuf.st_mode & 07777);
784 	}
785 	if (mflag == 0) {
786 		dblock.dbuf.name[0] = '\0';	/* process the whole stack */
787 		dodirtimes(&dblock);
788 	}
789 }
790 
791 dotable(argv)
792 	char *argv[];
793 {
794 	register int i;
795 
796 	for (;;) {
797 		if ((i = wantit(argv)) == 0)
798 			continue;
799 		if (i == -1)
800 			break;		/* end of tape */
801 		if (vflag)
802 			longt(&stbuf);
803 		printf("%s", dblock.dbuf.name);
804 		if (dblock.dbuf.linkflag == '1')
805 			printf(" linked to %s", dblock.dbuf.linkname);
806 		if (dblock.dbuf.linkflag == '2')
807 			printf(" symbolic link to %s", dblock.dbuf.linkname);
808 		printf("\n");
809 		passtape();
810 	}
811 }
812 
813 putempty()
814 {
815 	char buf[TBLOCK];
816 
817 	bzero(buf, sizeof (buf));
818 	(void) writetape(buf);
819 }
820 
821 longt(st)
822 	register struct stat *st;
823 {
824 	register char *cp;
825 	char *ctime();
826 
827 	pmode(st);
828 	printf("%3u/%1u", st->st_uid, st->st_gid);
829 	printf("%7ld", st->st_size);
830 	cp = ctime(&st->st_mtime);
831 	printf(" %-12.12s %-4.4s ", cp+4, cp+20);
832 }
833 
834 #define	SUID	04000
835 #define	SGID	02000
836 #define	ROWN	0400
837 #define	WOWN	0200
838 #define	XOWN	0100
839 #define	RGRP	040
840 #define	WGRP	020
841 #define	XGRP	010
842 #define	ROTH	04
843 #define	WOTH	02
844 #define	XOTH	01
845 #define	STXT	01000
846 int	m1[] = { 1, ROWN, 'r', '-' };
847 int	m2[] = { 1, WOWN, 'w', '-' };
848 int	m3[] = { 2, SUID, 's', XOWN, 'x', '-' };
849 int	m4[] = { 1, RGRP, 'r', '-' };
850 int	m5[] = { 1, WGRP, 'w', '-' };
851 int	m6[] = { 2, SGID, 's', XGRP, 'x', '-' };
852 int	m7[] = { 1, ROTH, 'r', '-' };
853 int	m8[] = { 1, WOTH, 'w', '-' };
854 int	m9[] = { 2, STXT, 't', XOTH, 'x', '-' };
855 
856 int	*m[] = { m1, m2, m3, m4, m5, m6, m7, m8, m9};
857 
858 pmode(st)
859 	register struct stat *st;
860 {
861 	register int **mp;
862 
863 	for (mp = &m[0]; mp < &m[9];)
864 		selectbits(*mp++, st);
865 }
866 
867 selectbits(pairp, st)
868 	int *pairp;
869 	struct stat *st;
870 {
871 	register int n, *ap;
872 
873 	ap = pairp;
874 	n = *ap++;
875 	while (--n>=0 && (st->st_mode&*ap++)==0)
876 		ap++;
877 	putchar(*ap);
878 }
879 
880 /*
881  * Make all directories needed by `name'.  If `name' is itself
882  * a directory on the tar tape (indicated by a trailing '/'),
883  * return 1; else 0.
884  */
885 checkdir(name)
886 	register char *name;
887 {
888 	register char *cp;
889 
890 	/*
891 	 * Quick check for existence of directory.
892 	 */
893 	if ((cp = rindex(name, '/')) == 0)
894 		return (0);
895 	*cp = '\0';
896 	if (access(name, F_OK) == 0) {	/* already exists */
897 		*cp = '/';
898 		return (cp[1] == '\0');	/* return (lastchar == '/') */
899 	}
900 	*cp = '/';
901 
902 	/*
903 	 * No luck, try to make all directories in path.
904 	 */
905 	for (cp = name; *cp; cp++) {
906 		if (*cp != '/')
907 			continue;
908 		*cp = '\0';
909 		if (access(name, F_OK) < 0) {
910 			if (mkdir(name, 0777) < 0) {
911 				fprintf(stderr, "tar: mkdir: %s: %s\n",
912 				    name, strerror(errno));
913 				*cp = '/';
914 				return (0);
915 			}
916 			chown(name, stbuf.st_uid, stbuf.st_gid);
917 			if (pflag && cp[1] == '\0')	/* dir on the tape */
918 				chmod(name, stbuf.st_mode & 07777);
919 		}
920 		*cp = '/';
921 	}
922 	return (cp[-1]=='/');
923 }
924 
925 void
926 onintr()
927 {
928 	(void) signal(SIGINT, SIG_IGN);
929 	term++;
930 }
931 
932 void
933 onquit()
934 {
935 	(void) signal(SIGQUIT, SIG_IGN);
936 	term++;
937 }
938 
939 void
940 onhup()
941 {
942 	(void) signal(SIGHUP, SIG_IGN);
943 	term++;
944 }
945 
946 #ifdef notdef
947 void
948 onterm()
949 {
950 	(void) signal(SIGTERM, SIG_IGN);
951 	term++;
952 }
953 #endif
954 
955 tomodes(sp)
956 register struct stat *sp;
957 {
958 	register char *cp;
959 
960 	for (cp = dblock.dummy; cp < &dblock.dummy[TBLOCK]; cp++)
961 		*cp = '\0';
962 	(void)sprintf(dblock.dbuf.mode, "%6o ", sp->st_mode & 07777);
963 	(void)sprintf(dblock.dbuf.uid, "%6o ", sp->st_uid);
964 	(void)sprintf(dblock.dbuf.gid, "%6o ", sp->st_gid);
965 	(void)sprintf(dblock.dbuf.size, "%11lo ", sp->st_size);
966 	(void)sprintf(dblock.dbuf.mtime, "%11lo ", sp->st_mtime);
967 }
968 
969 checksum()
970 {
971 	register i;
972 	register char *cp;
973 
974 	for (cp = dblock.dbuf.chksum;
975 	     cp < &dblock.dbuf.chksum[sizeof(dblock.dbuf.chksum)]; cp++)
976 		*cp = ' ';
977 	i = 0;
978 	for (cp = dblock.dummy; cp < &dblock.dummy[TBLOCK]; cp++)
979 		i += *cp;
980 	return (i);
981 }
982 
983 checkw(c, name)
984 	char *name;
985 {
986 	if (!wflag)
987 		return (1);
988 	printf("%c ", c);
989 	if (vflag)
990 		longt(&stbuf);
991 	printf("%s: ", name);
992 	return (response() == 'y');
993 }
994 
995 response()
996 {
997 	char c;
998 
999 	c = getchar();
1000 	if (c != '\n')
1001 		while (getchar() != '\n')
1002 			;
1003 	else
1004 		c = 'n';
1005 	return (c);
1006 }
1007 
1008 checkf(name, mode, howmuch)
1009 	char *name;
1010 	int mode, howmuch;
1011 {
1012 	int l;
1013 
1014 	if ((mode & S_IFMT) == S_IFDIR){
1015 		if ((strcmp(name, "SCCS")==0) || (strcmp(name, "RCS")==0))
1016 			return(0);
1017 		return(1);
1018 	}
1019 	if ((l = strlen(name)) < 3)
1020 		return (1);
1021 	if (howmuch > 1 && name[l-2] == '.' && name[l-1] == 'o')
1022 		return (0);
1023 	if (strcmp(name, "core") == 0 ||
1024 	    strcmp(name, "errs") == 0 ||
1025 	    (howmuch > 1 && strcmp(name, "a.out") == 0))
1026 		return (0);
1027 	/* SHOULD CHECK IF IT IS EXECUTABLE */
1028 	return (1);
1029 }
1030 
1031 /* Is the current file a new file, or the newest one of the same name? */
1032 checkupdate(arg)
1033 	char *arg;
1034 {
1035 	char name[100];
1036 	long mtime;
1037 	daddr_t seekp;
1038 	daddr_t	lookup();
1039 
1040 	rewind(tfile);
1041 	for (;;) {
1042 		if ((seekp = lookup(arg)) < 0)
1043 			return (1);
1044 		fseek(tfile, seekp, 0);
1045 		fscanf(tfile, "%s %lo", name, &mtime);
1046 		return (stbuf.st_mtime > mtime);
1047 	}
1048 }
1049 
1050 done(n)
1051 {
1052 	unlink(tname);
1053 	exit(n);
1054 }
1055 
1056 /*
1057  * Do we want the next entry on the tape, i.e. is it selected?  If
1058  * not, skip over the entire entry.  Return -1 if reached end of tape.
1059  */
1060 wantit(argv)
1061 	char *argv[];
1062 {
1063 	register char **cp;
1064 
1065 	getdir();
1066 	if (endtape())
1067 		return (-1);
1068 	if (*argv == 0)
1069 		return (1);
1070 	for (cp = argv; *cp; cp++)
1071 		if (prefix(*cp, dblock.dbuf.name))
1072 			return (1);
1073 	passtape();
1074 	return (0);
1075 }
1076 
1077 /*
1078  * Does s2 begin with the string s1, on a directory boundary?
1079  */
1080 prefix(s1, s2)
1081 	register char *s1, *s2;
1082 {
1083 	while (*s1)
1084 		if (*s1++ != *s2++)
1085 			return (0);
1086 	if (*s2)
1087 		return (*s2 == '/');
1088 	return (1);
1089 }
1090 
1091 #define	N	200
1092 int	njab;
1093 
1094 daddr_t
1095 lookup(s)
1096 	char *s;
1097 {
1098 	register i;
1099 	daddr_t a;
1100 
1101 	for(i=0; s[i]; i++)
1102 		if (s[i] == ' ')
1103 			break;
1104 	a = bsrch(s, i, low, high);
1105 	return (a);
1106 }
1107 
1108 daddr_t
1109 bsrch(s, n, l, h)
1110 	daddr_t l, h;
1111 	char *s;
1112 {
1113 	register i, j;
1114 	char b[N];
1115 	daddr_t m, m1;
1116 
1117 	njab = 0;
1118 
1119 loop:
1120 	if (l >= h)
1121 		return ((daddr_t) -1);
1122 	m = l + (h-l)/2 - N/2;
1123 	if (m < l)
1124 		m = l;
1125 	fseek(tfile, m, 0);
1126 	fread(b, 1, N, tfile);
1127 	njab++;
1128 	for(i=0; i<N; i++) {
1129 		if (b[i] == '\n')
1130 			break;
1131 		m++;
1132 	}
1133 	if (m >= h)
1134 		return ((daddr_t) -1);
1135 	m1 = m;
1136 	j = i;
1137 	for(i++; i<N; i++) {
1138 		m1++;
1139 		if (b[i] == '\n')
1140 			break;
1141 	}
1142 	i = cmp(b+j, s, n);
1143 	if (i < 0) {
1144 		h = m;
1145 		goto loop;
1146 	}
1147 	if (i > 0) {
1148 		l = m1;
1149 		goto loop;
1150 	}
1151 	return (m);
1152 }
1153 
1154 cmp(b, s, n)
1155 	char *b, *s;
1156 {
1157 	register i;
1158 
1159 	if (b[0] != '\n')
1160 		exit(2);
1161 	for(i=0; i<n; i++) {
1162 		if (b[i+1] > s[i])
1163 			return (-1);
1164 		if (b[i+1] < s[i])
1165 			return (1);
1166 	}
1167 	return (b[i+1] == ' '? 0 : -1);
1168 }
1169 
1170 readtape(buffer)
1171 	char *buffer;
1172 {
1173 	char *bufp;
1174 
1175 	if (first == 0)
1176 		getbuf();
1177 	(void) readtbuf(&bufp, TBLOCK);
1178 	bcopy(bufp, buffer, TBLOCK);
1179 	return(TBLOCK);
1180 }
1181 
1182 readtbuf(bufpp, size)
1183 	char **bufpp;
1184 	int size;
1185 {
1186 	register int i;
1187 
1188 	if (recno >= nblock || first == 0) {
1189 		if ((i = bread(mt, (char *)tbuf, TBLOCK*nblock)) < 0)
1190 			mterr("read", i, 3);
1191 		if (first == 0) {
1192 			if ((i % TBLOCK) != 0) {
1193 				fprintf(stderr, "tar: tape blocksize error\n");
1194 				done(3);
1195 			}
1196 			i /= TBLOCK;
1197 			if (i != nblock) {
1198 				fprintf(stderr, "tar: blocksize = %d\n", i);
1199 				nblock = i;
1200 			}
1201 			first = 1;
1202 		}
1203 		recno = 0;
1204 	}
1205 	if (size > ((nblock-recno)*TBLOCK))
1206 		size = (nblock-recno)*TBLOCK;
1207 	*bufpp = (char *)&tbuf[recno];
1208 	recno += (size/TBLOCK);
1209 	return (size);
1210 }
1211 
1212 writetbuf(buffer, n)
1213 	register char *buffer;
1214 	register int n;
1215 {
1216 	int i;
1217 
1218 	if (first == 0) {
1219 		getbuf();
1220 		first = 1;
1221 	}
1222 	if (recno >= nblock) {
1223 		i = write(mt, (char *)tbuf, TBLOCK*nblock);
1224 		if (i != TBLOCK*nblock)
1225 			mterr("write", i, 2);
1226 		recno = 0;
1227 	}
1228 
1229 	/*
1230 	 *  Special case:  We have an empty tape buffer, and the
1231 	 *  users data size is >= the tape block size:  Avoid
1232 	 *  the bcopy and dma direct to tape.  BIG WIN.  Add the
1233 	 *  residual to the tape buffer.
1234 	 */
1235 	while (recno == 0 && n >= nblock) {
1236 		i = write(mt, buffer, TBLOCK*nblock);
1237 		if (i != TBLOCK*nblock)
1238 			mterr("write", i, 2);
1239 		n -= nblock;
1240 		buffer += (nblock * TBLOCK);
1241 	}
1242 
1243 	while (n-- > 0) {
1244 		bcopy(buffer, (char *)&tbuf[recno++], TBLOCK);
1245 		buffer += TBLOCK;
1246 		if (recno >= nblock) {
1247 			i = write(mt, (char *)tbuf, TBLOCK*nblock);
1248 			if (i != TBLOCK*nblock)
1249 				mterr("write", i, 2);
1250 			recno = 0;
1251 		}
1252 	}
1253 
1254 	/* Tell the user how much to write to get in sync */
1255 	return (nblock - recno);
1256 }
1257 
1258 backtape()
1259 {
1260 	static int mtdev = 1;
1261 	static struct mtop mtop = {MTBSR, 1};
1262 	struct mtget mtget;
1263 
1264 	if (mtdev == 1)
1265 		mtdev = ioctl(mt, MTIOCGET, (char *)&mtget);
1266 	if (mtdev == 0) {
1267 		if (ioctl(mt, MTIOCTOP, (char *)&mtop) < 0) {
1268 			fprintf(stderr, "tar: tape backspace error: %s\n",
1269 			    strerror(errno));
1270 			done(4);
1271 		}
1272 	} else
1273 		(void)lseek(mt, (daddr_t) -TBLOCK*nblock, 1);
1274 	recno--;
1275 }
1276 
1277 flushtape()
1278 {
1279 	int i;
1280 
1281 	i = write(mt, (char *)tbuf, TBLOCK*nblock);
1282 	if (i != TBLOCK*nblock)
1283 		mterr("write", i, 2);
1284 }
1285 
1286 mterr(operation, i, exitcode)
1287 	char *operation;
1288 	int i;
1289 {
1290 	fprintf(stderr, "tar: tape %s error: %s\n",
1291 	    operation, i < 0 ? strerror(errno) : "unexpected EOF");
1292 	done(exitcode);
1293 }
1294 
1295 bread(fd, buf, size)
1296 	int fd;
1297 	char *buf;
1298 	int size;
1299 {
1300 	int count;
1301 	static int lastread = 0;
1302 
1303 	if (!Bflag)
1304 		return (read(fd, buf, size));
1305 
1306 	for (count = 0; count < size; count += lastread) {
1307 		lastread = read(fd, buf, size - count);
1308 		if (lastread <= 0) {
1309 			if (count > 0)
1310 				return (count);
1311 			return (lastread);
1312 		}
1313 		buf += lastread;
1314 	}
1315 	return (count);
1316 }
1317 
1318 char *
1319 cwd()
1320 {
1321 	char *p;
1322 
1323 	p = getcwd((char *)NULL, 0);
1324 	if (p == NULL) {
1325 		(void)fprintf(stderr, "tar: %s\n", strerror(errno));
1326 		exit(1);
1327 	}
1328 	return (p);
1329 }
1330 
1331 getbuf()
1332 {
1333 
1334 	if (nblock == 0) {
1335 		fstat(mt, &stbuf);
1336 		if ((stbuf.st_mode & S_IFMT) == S_IFCHR)
1337 			nblock = NBLOCK;
1338 		else {
1339 			nblock = stbuf.st_blksize / TBLOCK;
1340 			if (nblock == 0)
1341 				nblock = NBLOCK;
1342 		}
1343 	}
1344 	tbuf = (union hblock *)malloc((unsigned)nblock*TBLOCK);
1345 	if (tbuf == NULL) {
1346 		fprintf(stderr, "tar: blocksize %d too big, can't get memory\n",
1347 		    nblock);
1348 		done(1);
1349 	}
1350 }
1351 
1352 /*
1353  * Save this directory and its mtime on the stack, popping and setting
1354  * the mtimes of any stacked dirs which aren't parents of this one.
1355  * A null directory causes the entire stack to be unwound and set.
1356  *
1357  * Since all the elements of the directory "stack" share a common
1358  * prefix, we can make do with one string.  We keep only the current
1359  * directory path, with an associated array of mtime's, one for each
1360  * '/' in the path.  A negative mtime means no mtime.  The mtime's are
1361  * offset by one (first index 1, not 0) because calling this with a null
1362  * directory causes mtime[0] to be set.
1363  *
1364  * This stack algorithm is not guaranteed to work for tapes created
1365  * with the 'r' option, but the vast majority of tapes with
1366  * directories are not.  This avoids saving every directory record on
1367  * the tape and setting all the times at the end.
1368  */
1369 char dirstack[NAMSIZ];
1370 #define NTIM (NAMSIZ/2+1)		/* a/b/c/d/... */
1371 time_t mtime[NTIM];
1372 
1373 dodirtimes(hp)
1374 	union hblock *hp;
1375 {
1376 	register char *p = dirstack;
1377 	register char *q = hp->dbuf.name;
1378 	register int ndir = 0;
1379 	char *savp;
1380 	int savndir;
1381 
1382 	/* Find common prefix */
1383 	while (*p == *q && *p) {
1384 		if (*p++ == '/')
1385 			++ndir;
1386 		q++;
1387 	}
1388 
1389 	savp = p;
1390 	savndir = ndir;
1391 	while (*p) {
1392 		/*
1393 		 * Not a child: unwind the stack, setting the times.
1394 		 * The order we do this doesn't matter, so we go "forward."
1395 		 */
1396 		if (*p++ == '/')
1397 			if (mtime[++ndir] >= 0) {
1398 				*--p = '\0';	/* zap the slash */
1399 				setimes(dirstack, mtime[ndir]);
1400 				*p++ = '/';
1401 			}
1402 	}
1403 	p = savp;
1404 	ndir = savndir;
1405 
1406 	/* Push this one on the "stack" */
1407 	while (*p = *q++)	/* append the rest of the new dir */
1408 		if (*p++ == '/')
1409 			mtime[++ndir] = -1;
1410 	mtime[ndir] = stbuf.st_mtime;	/* overwrite the last one */
1411 }
1412 
1413 setimes(path, mt)
1414 	char *path;
1415 	time_t mt;
1416 {
1417 	struct timeval tv[2];
1418 
1419 	tv[0].tv_sec = time((time_t *) 0);
1420 	tv[1].tv_sec = mt;
1421 	tv[0].tv_usec = tv[1].tv_usec = 0;
1422 	if (utimes(path, tv) < 0)
1423 		fprintf(stderr, "tar: can't set time on %s: %s\n",
1424 		    path, strerror(errno));
1425 }
1426 
1427 char *
1428 getmem(size)
1429 {
1430 	char *p = malloc((unsigned) size);
1431 
1432 	if (p == NULL && freemem) {
1433 		fprintf(stderr,
1434 		    "tar: out of memory, link and directory modtime info lost\n");
1435 		freemem = 0;
1436 	}
1437 	return (p);
1438 }
1439