/*	tar.c	1.7	*/
#include "stdio.h"
#include "types.h"
#include "stat.h"
#include "dir.h"
#include "signal.h"

char	*sprintf();

#define TBLOCK	512
#define NBLOCK	20
#define NAMSIZ	100
union hblock {
	char dummy[TBLOCK];
	struct header {
		char name[NAMSIZ];
		char mode[8];
		char uid[8];
		char gid[8];
		char size[12];
		char mtime[12];
		char chksum[8];
		char linkflag;
		char linkname[NAMSIZ];
	} dbuf;
} dblock, tbuf[NBLOCK];

struct linkbuf {
	ino_t	inum;
	dev_t	devnum;
	int	count;
	char	pathname[NAMSIZ];
	struct	linkbuf *nextp;
} *ihead;

struct stat stbuf;

int	rflag, xflag, vflag, tflag, mt, cflag, mflag, oflag;
int	term, chksum, wflag, recno, first, linkerrok;
int	freemem = 1;
int	nblock = 1;


char	*usefile;
char	*use1fil;
char	magtape[]	= "/dev/rmt";
char	mag1tap[]	= "/dev/mt";


_main(argc, argv)
int	argc;
char	*argv[];
{
	char *cp;
	int speed;
	int onintr(), onquit(), onhup(), onterm();

	if (argc < 2)
		usage();

	usefile =  magtape;
	use1fil =  mag1tap;
	argv[argc] = 0;
	argv++;
	for (cp = *argv++, speed = 0; *cp; cp++, speed--)
		switch(*cp) {
		case 'f':
			usefile = *argv++;
			if (nblock == 1)
				nblock = 0;
			break;
		case 'c':
			cflag++;
			rflag++;
			break;
		case 'u':
			fprintf(stderr,"Can't do u\n");
			/* Fall through */
		case 'r':
			rflag++;
			if (nblock != 1 && cflag == 0) {
noupdate:
				fprintf(stderr, "Tar: Blocked tapes cannot be updated (yet)\n");
				done(1);
			}
			break;
		case 'v':
			vflag++;
			break;
		case 'w':
			wflag++;
			break;
		case 'x':
			xflag++;
			break;
		case 't':
			tflag++;
			break;
		case 'm':
			if (speed != 1)		/* if speed=1 'm' means */
				mflag++;	/* medium speed		*/
			break;
		case '-':
			break;
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
			magtape[8] = *cp;
			mag1tap[7] = *cp;
			speed = 2;		/* next time will be 1 */

			usefile = magtape;
			use1fil = mag1tap;
			break;
		case 'b':
			nblock = atoi(*argv++);
			if (nblock > NBLOCK || nblock <= 0) {
				fprintf(stderr, "Invalid blocksize. (Max %d)\n", NBLOCK);
				done(1);
			}
			if (rflag && !cflag)
				goto noupdate;
			break;
		case 'l':
			if (speed == 1) {
				magtape[9] = *cp;
				usefile = magtape;
			}
			else
				linkerrok++;
			break;
		case 'o':
			oflag++;
			break;
		case 'h':
			if (speed == 1) {
				magtape[9] = *cp;
				usefile = magtape;
				break;
			}
			/*	else fall thru -- error */
		default:
			fprintf(stderr, "tar: %c: unknown option\n", *cp);
			usage();
		}

	if (rflag) {
		if (signal(SIGINT, SIG_IGN) != SIG_IGN)
			signal(SIGINT, onintr);
		if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
			signal(SIGHUP, onhup);
		if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
			signal(SIGQUIT, onquit);
/*
		if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
			signal(SIGTERM, onterm);
*/
		if (strcmp(usefile, "-") == 0) {
			if (cflag == 0) {
				fprintf(stderr, "Can only create standard output archives\n");
				done(1);
			}
			mt = dup(1);
			nblock = 1;
		}
		else
		if ((mt = open(usefile,2)) < 0 && (mt = open(use1fil,2)) < 0) {
			if (cflag == 0 || (mt =  creat(usefile, 0666)) < 0) {
				fprintf(stderr, "tar: cannot open %s\n", usefile);
				done(1);
			}
		}
		if (cflag == 0 && nblock == 0)
			nblock = 1;
		dorep(argv);
	}
	else if (xflag)  {
		if (strcmp(usefile, "-") == 0) {
			mt = dup(0);
			nblock = 1;
		}
		else
		if ((mt = open(usefile,0)) < 0 && (mt = open(use1fil,0)) < 0) {
			fprintf(stderr, "tar: cannot open %s\n", usefile);
			done(1);
		}
		doxtract(argv);
	}
	else if (tflag) {
		if (strcmp(usefile, "-") == 0) {
			mt = dup(0);
			nblock = 1;
		}
		else
		if ((mt = open(usefile,0)) < 0 && (mt = open(use1fil,0)) < 0) {
			fprintf(stderr, "tar: cannot open %s\n", usefile);
			done(1);
		}
		dotable();
	}
	else
		usage();
	done(0);
}

usage()
{
/*	fprintf(stderr, "tar: usage  tar -{txruc}[vwfblmh] [tapefile] [blocksize] file1 file2...\n");	*/
	fprintf(stderr, "tar: usage  tar [-]{txruc}[vwfblm][0-7[lmh]] [tapefile] [blocksize] file1 file2...\n");	/* For version 1.2 of tar */
	done(1);
}

dorep(argv)
char	*argv[];
{
	register char *cp, *cp2;
	char wdir[60];

	if (!cflag) {
		getdir();
		do {
			passtape();
			if (term)
				done(0);
			getdir();
		} while (!endtape());
	}

	if (getcwd(wdir,sizeof(wdir)) == NULL) {
		fprintf(stderr,"Getcwd fails\n");
		done(3);
	}

	while (*argv && ! term) {
		cp2 = *argv;
		for (cp = *argv; *cp; cp++)
			if (*cp == '/')
				cp2 = cp;
		if (cp2 != *argv) {
			*cp2 = '\0';
			chdir(*argv);
			*cp2 = '/';
			cp2++;
		}
		putfile(*argv++, cp2);
		chdir(wdir);
	}
	putempty();
	putempty();
	flushtape();
	if (linkerrok == 1)
		for (; ihead != NULL; ihead = ihead->nextp)
			if (ihead->count != 0)
				fprintf(stderr, "Missing links to %s\n", ihead->pathname);
}

endtape()
{
	if (dblock.dbuf.name[0] == '\0') {
		backtape();
		return(1);
	}
	else
		return(0);
}

getdir()
{
	register struct stat *sp;
	int i;
	int csum;

	readtape( (char *) &dblock);
	if (dblock.dbuf.name[0] == '\0')
		return;
	sscanf(dblock.dbuf.chksum, "%o", &chksum);
	if (chksum != (csum=checksum())) {
		fprintf(stderr, "directory checksum error\n");
		done(2);
	}
	sp = &stbuf;
	sscanf(dblock.dbuf.mode, "%o", &i);
	sp->st_mode = i;
	sscanf(dblock.dbuf.uid, "%o", &i);
	sp->st_uid = i;
	sscanf(dblock.dbuf.gid, "%o", &i);
	sp->st_gid = i;
	getsize(dblock.dbuf.size, &sp->st_size);
	getdate(dblock.dbuf.mtime, &sp->st_mtime);
}

passtape()
{
	unsigned blocks;
	char buf[TBLOCK];

	if (dblock.dbuf.linkflag == '1')
		return;
 	blocks = stbuf.st_size.o_blkno;
	if (stbuf.st_size.o_offset)
		++blocks;

	while (blocks-- > 0)
		readtape(buf);
}

putfile(longname, shortname)
char *longname;
char *shortname;
{
	int infile;
	unsigned blocks;
	char buf[TBLOCK];
	register char *cp, *cp2;
	struct direct dbuf;
	int i, j;
	struct linkbuf *lp;
	int found;

	infile = open(shortname, 0);
	if (infile < 0) {
		fprintf(stderr, "tar: %s: cannot open file\n", longname);
		return;
	}

	fstat(infile, &stbuf);

	if (checkw('r', longname) == 0) {
		close(infile);
		return;
	}

	if ((stbuf.st_mode & S_IFMT) == S_IFDIR) {
		for (i = 0, cp = buf; *cp++ = longname[i++];);
		*--cp = '/';
		cp++;
		i = 0;
		chdir(shortname);
		while (read(infile, (char *)&dbuf, sizeof(dbuf)) > 0 && !term) {
			if (dbuf.d_ino == 0) {
				i++;
				continue;
			}
			if (strcmp(".", dbuf.d_name) == 0 || strcmp("..", dbuf.d_name) == 0) {
				i++;
				continue;
			}
			cp2 = cp;
			for (j=0; j < DIRSIZ; j++)
				*cp2++ = dbuf.d_name[j];
			*cp2 = '\0';
			close(infile);
			putfile(buf, cp);
			infile = open(".", 0);
			i++;
			seek(infile, (unsigned) (sizeof(dbuf) * i), 0);
		}
		close(infile);
		chdir("..");
		return;
	}
	if ((stbuf.st_mode & S_IFMT) != S_IFREG) {
		fprintf(stderr, "tar: %s is not a file. Not dumped\n", longname);
		return;
	}

	tomodes(&stbuf);

	cp2 = longname;
	for (cp = dblock.dbuf.name, i=0; (*cp++ = *cp2++) && i < NAMSIZ; i++);
	if (i >= NAMSIZ) {
		fprintf(stderr, "%s: file name too long\n", longname);
		close(infile);
		return;
	}

	if (stbuf.st_nlink > 1) {
		found = 0;

		for (lp = ihead; lp != NULL; lp = lp->nextp) {
			if (lp->inum == stbuf.st_ino && lp->devnum == stbuf.st_dev) {
				found++;
				break;
			}
		}
		if (found) {
			strcpy(dblock.dbuf.linkname, lp->pathname);
			dblock.dbuf.linkflag = '1';
			sprintf(dblock.dbuf.chksum, "%6o", checksum());
			writetape( (char *) &dblock);
			if (vflag) {
				fprintf(stderr, "a %s ", longname);
				fprintf(stderr, "link to %s\n", lp->pathname);
			}
			lp->count--;
			close(infile);
			return;
		}
		else {
			lp = (struct linkbuf *) sbrk(sizeof(*lp));
			if (lp == (struct linkbuf *)-1) {
				if (freemem) {
					fprintf(stderr, "Out of memory. Link information lost\n");
					freemem = 0;
				}
			}
			else {
				lp->nextp = ihead;
				ihead = lp;
				lp->inum = stbuf.st_ino;
				lp->devnum = stbuf.st_dev;
				lp->count = stbuf.st_nlink - 1;
				strcpy(lp->pathname, longname);
			}
		}
	}

 	blocks = stbuf.st_size.o_blkno;
	if (stbuf.st_size.o_offset)
		++blocks;
	if (vflag) {
		fprintf(stderr, "a %s ", longname);
		fprintf(stderr, "%u blocks\n", blocks);
	}
	sprintf(dblock.dbuf.chksum, "%6o", checksum());
	writetape( (char *) &dblock);

	while ((i = read(infile, buf, TBLOCK)) > 0 && blocks > 0) {
		writetape(buf);
		blocks--;
	}
	close(infile);
	if (blocks != 0 || i != 0)
		fprintf(stderr, "%s: file changed size\n", longname);
	while (blocks-- >  0)
		putempty();
}



doxtract(argv)
char	*argv[];
{
	unsigned blocks, bytes;
	char buf[TBLOCK];
	char **cp;
	int ofile;
	time_t timep[2];

	for (;;) {
		getdir();
		if (endtape())
			break;

		if (*argv == 0)
			goto gotit;

		for (cp = argv; *cp; cp++)
			if (prefix(*cp, dblock.dbuf.name))
				goto gotit;
		passtape();
		continue;

gotit:
		if (checkw('x', dblock.dbuf.name) == 0) {
			passtape();
			continue;
		}

		checkdir(dblock.dbuf.name);

		if (dblock.dbuf.linkflag == '1') {
			unlink(dblock.dbuf.name);
			if (link(dblock.dbuf.linkname, dblock.dbuf.name) < 0) {
				fprintf(stderr, "%s: cannot link\n", dblock.dbuf.name);
				continue;
			}
			if (vflag)
				fprintf(stderr, "%s linked to %s\n", dblock.dbuf.name, dblock.dbuf.linkname);
			continue;
		}
		if ((ofile = creat(dblock.dbuf.name, stbuf.st_mode & 07777)) < 0) {
			fprintf(stderr, "tar: %s - cannot create\n", dblock.dbuf.name);
			passtape();
			continue;
		}

		if (!oflag)
			chown(dblock.dbuf.name, stbuf.st_uid, stbuf.st_gid);

	 	blocks = stbuf.st_size.o_blkno;  /* Not counting partial end blk */
		bytes = 512*blocks + stbuf.st_size.o_offset;
		if (vflag)
			fprintf(stderr, "x %s, %u bytes, %u tape blocks\n",
				 dblock.dbuf.name, bytes, blocks);
		while (blocks-- > 0) {
			readtape(buf);
			if (write(ofile, buf, TBLOCK) < 0) {
				fprintf(stderr, "tar: %s: HELP - extract write error\n", dblock.dbuf.name);
				done(2);
			}
		}
		if (stbuf.st_size.o_offset)
		{
			readtape(buf);
			if (write(ofile, buf, stbuf.st_size.o_offset) < 0) {
				fprintf(stderr, "tar: %s: HELP - extract write error\n", dblock.dbuf.name);
				done(2);
			}
		}
		close(ofile);
		if (mflag == 0) {

/*			timep[0].t_time = stbuf.st_atime.t_time;
			timep[0].t_date = stbuf.st_atime.t_date;
			timep[1].t_time = stbuf.st_mtime.t_time;
			timep[1].t_date = stbuf.st_mtime.t_date;
			utime(dblock.dbuf.name, timep);  */
		}
	}
}

dotable()
{
	for (;;) {
		getdir();
		if (endtape())
			break;
		if (vflag)
			longt(&stbuf);
		printf("%s", dblock.dbuf.name);
		if (dblock.dbuf.linkflag == '1')
			printf(" linked to %s", dblock.dbuf.linkname);
		printf("\n");
		passtape();
	}
}

putempty()
{
	char buf[TBLOCK];
	char *cp;

	for (cp = buf; cp < &buf[TBLOCK]; )
		*cp++ = '\0';
	writetape(buf);
}

longt(st)
register struct stat *st;
{
	register char *cp;
	char *ctime();

	pmode(st);
	printf("%3d/%1d", st->st_uid, st->st_gid);
	printf("%7u", 512*st->st_size.o_blkno + st->st_size.o_offset);
	cp = ctime(&st->st_mtime);
	printf(" %s ", cp);
}

#define	SUID	04000
#define	SGID	02000
#define	ROWN	0400
#define	WOWN	0200
#define	XOWN	0100
#define	RGRP	040
#define	WGRP	020
#define	XGRP	010
#define	ROTH	04
#define	WOTH	02
#define	XOTH	01
#define	STXT	01000
int	m1[] = { 1, ROWN, 'r', '-' };
int	m2[] = { 1, WOWN, 'w', '-' };
int	m3[] = { 2, SUID, 's', XOWN, 'x', '-' };
int	m4[] = { 1, RGRP, 'r', '-' };
int	m5[] = { 1, WGRP, 'w', '-' };
int	m6[] = { 2, SGID, 's', XGRP, 'x', '-' };
int	m7[] = { 1, ROTH, 'r', '-' };
int	m8[] = { 1, WOTH, 'w', '-' };
int	m9[] = { 2, STXT, 't', XOTH, 'x', '-' };

int	*m[] = { m1, m2, m3, m4, m5, m6, m7, m8, m9};

pmode(st)
register struct stat *st;
{
	register int **mp;

	for (mp = &m[0]; mp < &m[9];)
		select(*mp++, st);
}

select(pairp, st)
int *pairp;
struct stat *st;
{
	register int n, *ap;

	ap = pairp;
	n = *ap++;
	while (--n>=0 && (st->st_mode&*ap++)==0)
		ap++;
	printf("%c", *ap);
}

checkdir(name)
register char *name;
{
	register char *cp;
	int i;
	static char *args[] = {"mkdir", 0, 0 };
	extern char **environ;

	cp = name;
 	for (cp++; *cp; cp++) {	/* start at *name++ */
		if (*cp == '/') {
			*cp = '\0';
			if (access(name, 01) < 0) {
				if (fork() == 0) {
					args[1] = name;
					execve("/bin/mkdir",args, environ);
					execve("/usr/bin/mkdir", args, environ);
					fprintf(stderr, "tar: cannot find mkdir!\n");
					done(0);
				}
				while (wait(&i) >= 0);
				if (!oflag)
					chown(name, stbuf.st_uid, stbuf.st_gid);
			}
			*cp = '/';
		}
	}
}

onintr()
{
	signal(SIGINT, SIG_IGN);
	term++;
}

onquit()
{
	signal(SIGQUIT, SIG_IGN);
	term++;
}

onhup()
{
	signal(SIGHUP, SIG_IGN);
	term++;
}

onterm()
{
	signal(SIGTERM, SIG_IGN);
	term++;
}

tomodes(sp)
register struct stat *sp;
{
	register char *cp;
	register offset;

	offset = sp->st_size.o_offset;
	for (cp = dblock.dummy; cp < &dblock.dummy[TBLOCK]; cp++)
		*cp = '\0';
	sprintf(dblock.dbuf.mode, "%6o ", sp->st_mode & 07777);
	sprintf(dblock.dbuf.uid, "%6o ", sp->st_uid);
	sprintf(dblock.dbuf.gid, "%6o ", sp->st_gid);
	sprintf(dblock.dbuf.size, "%8o%o%o%o", sp->st_size.o_blkno,
		(offset&0700)>>6, (offset&070)>>3, offset&07);
	putdate(dblock.dbuf.mtime, &sp->st_mtime);
}

checksum()
{
	register i;
	register char *cp;

	for (cp = dblock.dbuf.chksum; cp < &dblock.dbuf.chksum[sizeof(dblock.dbuf.chksum)]; cp++)
		*cp = ' ';
	i = 0;
	for (cp = dblock.dummy; cp < &dblock.dummy[TBLOCK]; cp++)
		i += *cp;
	return(i);
}

checkw(c, name)
char *name;
{
	if (wflag) {
		printf("%c ", c);
		if (vflag)
			longt(&stbuf);
		printf("%s: ", name);
		if (response() == 'y'){
			return(1);
		}
		return(0);
	}
	return(1);
}

response()
{
	char c;

	c = getchar();
	if (c != '\n')
		while (getchar() != '\n');
	else c = 'n';
	return(c);
}

done(n)
{
	exit(n);
}

prefix(s1, s2)
register char *s1, *s2;
{
	while (*s1)
		if (*s1++ != *s2++)
			return(0);
	if (*s2)
		return(*s2 == '/');
	return(1);
}



readtape(buffer)
char *buffer;
{
	int i, j;

	if (recno >= nblock || first == 0) {
		if (first == 0 && nblock == 0)
			j = NBLOCK;
		else
			j = nblock;
		if ((i = read(mt, tbuf, TBLOCK*j)) < 0) {
			fprintf(stderr, "Tar: tape read error\n");
			done(3);
		}
		if (first == 0) {
			if ((i % TBLOCK) != 0) {
				fprintf(stderr, "Tar: tape blocksize error\n");
				done(3);
			}
			i /= TBLOCK;
			if (rflag && i != 1) {
				fprintf(stderr, "Tar: Cannot update blocked tapes (yet)\n");
				done(4);
			}
			if (i != nblock && i != 1) {
				fprintf(stderr, "Tar: blocksize = %d\n", i);
				nblock = i;
			}
		}
		recno = 0;
	}
	first = 1;
	copy(buffer, &tbuf[recno++]);
	return(TBLOCK);
}

writetape(buffer)
char *buffer;
{
	first = 1;
	if (nblock == 0)
		nblock = 1;
	if (recno >= nblock) {
		if (write(mt, tbuf, TBLOCK*nblock) < 0) {
			fprintf(stderr, "Tar: tape write error\n");
			done(2);
		}
		recno = 0;
	}
	copy(&tbuf[recno++], buffer);
	if (recno >= nblock) {
		if (write(mt, tbuf, TBLOCK*nblock) < 0) {
			fprintf(stderr, "Tar: tape write error\n");
			done(2);
		}
		recno = 0;
	}
	return(TBLOCK);
}

backtape()
{
	seek(mt, (unsigned) -TBLOCK, 1);
	if (recno >= nblock) {
		recno = nblock - 1;
		if (read(mt, tbuf, TBLOCK*nblock) < 0) {
			fprintf(stderr, "Tar: tape read error after seek\n");
			done(4);
		}
		seek(mt, (unsigned) -TBLOCK, 1);
	}
}

flushtape()
{
	write(mt, tbuf, TBLOCK*nblock);
}

copy(to, from)
register char *to, *from;
{
	bcopy(from, to, TBLOCK);
}


/* Getsize takes a string containing a long octal integer,
and parses it into a st_size structure. */

getsize(str, size)
char *str;
off_t *size;
{
    char *op;

    op = str;
    while (*op++ == ' ')
	++op;	/* Skip leading whitespace */
    while (*op != ' ' && *op != '\0')
	++op;  /* Skip over digits */
    op -= 3;			/* Move back to 3rd from last digit */
    sscanf(op, "%3o", &(size->o_offset));  /* Extract offset */
    *op = '\0';		/* Mark end of block number part */
    if (sscanf(str, "%o", &(size->o_blkno)) != 1)
	size->o_blkno = 0;		;  /* Get blkno part */
}


#ifdef ODATE

/* Getdate takes a string containing a long octal integer,
and parses it into a time_t structure. */

getdate(str, date)
char *str;
time_t *date;
{
    char *op;

    op = str;
    while (*op == ' ')
	++op;	/* Skip leading whitespace */
    while (*op != ' ' && *op != '\0')
	++op;  /* Skip over digits */
    op -= 5;			/* Move back to 5th from last digit */
    sscanf(op, "%5o", &(date->t_time));  /* Extract time part */
    *op = '\0';		/* Mark end of date part */
    sscanf(str, "%o", &(date->t_date));  /* Get date part */

    /* Put lo-order bit of date into hi-order bit of time */
    if (date->t_date & 01)
 	date->t_time |= (1<<15);
    date->t_date >>= 1;
}


putdate(str, date)
char *str;
time_t *date;
{
    unsigned time;

    time = date->t_time;
    if (date->t_date & 01)
        time |= (1<<15);
    sprintf(str, "%o%3.3o", date->t_date >> 1, time);
}

#else


getdate(str, date)
char *str;
time_t *date;
{
    if (sscanf(str, "%x %x", &date->t_date, &date->t_time) != 2)
    {
	date->t_date = date->t_time = 0;
    }
}



putdate(str, date)
char *str;
time_t *date;
{
    sprintf(str, "%x %x", date->t_date, date->t_time);
}

#endif

